2017-06-13 61 views
1

我使用Backbone和Marionette创建了一个简单的应用程序。这只是获取一个Wordpress帖子列表(使用API​​)并显示它。 这是一个非常简单的应用程序,因此它不是模块化的。Backbone Marionette不是射击路线

我有以下的(这一切都放在同一个文件):

if (Backbone.history) 
    Backbone.history.start({ pushState: false }); 

if (Backbone.history.fragment === '') 
    API.listAllPosts(); 
else 
    API.listSinglePost(Backbone.history.fragment); 


// Is not firing anything from here... 
MyBlog.Router = Marionette.AppRouter.extend({ 
    appRoutes: { 
     '': 'listPosts', 
     ':post_name': 'listSingle' 
    }, 
    listPosts: function() { 
     console.log('router'); 
     API.listAllPosts(); 
    }, 
    listSingle: function(model) { 
     console.log('router, single'); 
     API.listSinglePost(model); 
    } 
}); 
// ...to here 

var API = { 
    listAllPosts: function() { 
     // Fetch all posts and display it. It's working 
    }, 
    listSinglePost: function(model) { 
     // Fetch a single post and display it. It's working 
    } 
} 

MyBlog.addInitializer(function() { 
    console.log('initializer'); // It's firing 

    new MyBlog.Router({ 
     controller: API 
    }); 
}); 

由于Derick Bailey, Marionette's creator, said有关使用上naviagate触发器:

鼓励糟糕的应用程序设计,我们强烈建议您不要 通过trigger:trueBackbone.history.navigate

我在这里错过了什么?

回答

0

您创建路由器实例之前启动骨干历史。

只需将其移至创建路由器后即可。

MyBlog.addInitializer(function() {  
    new MyBlog.Router({ controller: API }); 

    // should be started after a router has been created 
    Backbone.history.start({ pushState: false }); 
}); 

的另一件事是,回调should be defined inside of a controller或你应该改变appRoutesroutes

appRoutesroutes之间的主要区别是,我们提供一个控制器上 回调,而不是直接在路由器本身上。 [...] 由于AppRouter扩展了Backbone.Router,您还可以定义一个routes 属性,其回调必须存在于AppRouter上。

+1

谢谢@Emile Bergeron!它正在导航并显示我的帖子列表。问题在于使用appRoutes而不是路由以及我调用这些路由的方式。 谢谢任何​​人提前! – moreirapontocom

0

移动这个

if (Backbone.history) 
    Backbone.history.start({ pushState: false }); 

if (Backbone.history.fragment === '') 
    API.listAllPosts(); 
else 
    API.listSinglePost(Backbone.history.fragment); 

在您的应用程序被启动或initialize:after事件处理程序内后点。

检查这个前面的问题:Marionette.js appRouter not firing on app start

+0

我试过但是......没有运气。 – moreirapontocom

+0

你是否在链接的'href'中使用散列('#')? – vassiliskrikonis

+0

History.navigate()只适用于链接? 其实我没有使用链接。我有一个无序列表,每个li元素都有一个连接了点击事件的按钮。点击后,会调用一个函数,然后调用Backbone.History.navigate('proper-link-here')。 – moreirapontocom