moreirapontocom moreirapontocom -4 years ago 100
Javascript Question

Backbone Marionette is not firing routes

I'm creating a simple application using Backbone and Marionette. It's just to fetch a list of Wordpress posts (using an API) and display it.
It's a very simple app so it's not modularized.

I have the following (it's all placed in the same file):

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

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

// Is not firing anything from here...
MyBlog.Router = Marionette.AppRouter.extend({
appRoutes: {
'': 'listPosts',
':post_name': 'listSingle'
listPosts: function() {
listSingle: function(model) {
console.log('router, single');
// 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

As Derick Bailey, Marionette's creator, said about using triggers on naviagate:

it encourages bad app design and it is strongly recommended you don’t

What I'm missing here?

Answer Source

You start the Backbone history before creating the router instance.

Just move that to after the router is created.

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

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

The other thing is that the callbacks should be defined inside of a controller or you should change appRoutes to routes.

The major difference between appRoutes and routes is that we provide callbacks on a controller instead of directly on the router itself. [...] As the AppRouter extends Backbone.Router, you can also define a routes attribute whose callbacks must be present on the AppRouter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download