问题
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:
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.
来源:https://stackoverflow.com/questions/26960126/routes-and-controllers-in-marionette-js