Routes and controllers in Marionette.js

2019-09-03 18:25发布

Im new the Marionette.js. Im currently implementing routes and controllers. In my App.js, I have:

    App.appRouter = new Router({
        controller:new AppController()
    });

I want AppController to initialise other controllers. So I have a GenericController which looks after everything when the hash change is "generic", NewsController which looks after everything when hash changes to "news" etc. I don't want to have all the route functions in one giant controller file. So my AppController looks like:

define(['App', 'backbone', 'marionette',
        "app/models/generic", "app/views/GenericList",
        'app/utils/useful_func', 'app/utils/pageslider',
        'constants',
        'app/controllers/GenericController'
        ],
    function (App, Backbone, Marionette,
        model, GenericList,
        Useful, PageSlider,
        constants,
        GenericController) {

    return Backbone.Marionette.Controller.extend({

        initialize:function (options) {

            genericController = new GenericController();

        },

    });

});

GenericController looks like:

define(['App', 'backbone', 'marionette'],
    function (App, Backbone, Marionette) {

    return Backbone.Marionette.Controller.extend({

        initialize:function (options) {

        },

        getGeneric: function(){
                console.log('in getGeneric');
        },

    });
});

The Router looks like:

    appRoutes: {
        "generic": "getGeneric",
        ...

However, I end up with the error:

Method 'getGenericItem' was not found on the controller 

Because its just looking in AppController and not GenericController for the router functions.

If i move getGenericItem() to the main AppController, it works fine. How can I get it to look in GenericController for router functions?

1条回答
Explosion°爆炸
2楼-- · 2019-09-03 18:33

Marionette docs:

It is recommended that you divide your controller objects into smaller pieces of related functionality and have multiple routers / controllers, instead of just one giant router and controller.

So do this:

var AppController =  Backbone.Marionette.Controller.extend({
  initialize:function (options) {
  },    
  customAction: function() {
    console.log('in customAction');
  }
});

var GenericController = Backbone.Marionette.Controller.extend({
  initialize:function (options) {    
  },    
  getGeneric: function(){
    console.log('in getGeneric');
  }    
});

App.appRouter = new Marionette.AppRouter({
  controller:new AppController(),        
  appRoutes: {
    "custom": "customAction"
  }
});

App.genericRouter = new Marionette.AppRouter({
  controller: new GenericController(),
  appRoutes: {
    "generic": "getGeneric"
  }
});

Here's a jsbin, but it doesn't work however.

查看更多
登录 后发表回答