2014-11-16 77 views
0

Im new the Marionette.js。我目前正在實施路線和控制器。在我的App.js中,我有:Marionette.js中的路線和控制器

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

我想讓AppController初始化其他控制器。所以我有一個GenericController,它在散列更改爲「通用」時查看所有內容,NewsController在散列更改爲「新聞」時查看所有內容。我不想在一個巨型控制器文件中擁有所有的路由功能。所以我AppController的樣子:

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樣子:

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

    return Backbone.Marionette.Controller.extend({ 

     initialize:function (options) { 

     }, 

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

    }); 
}); 

路由器看起來像:

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

然而,我最終錯誤:

Method 'getGenericItem' was not found on the controller 

因爲它只是看起來ng在AppController中,而不是GenericController用於路由器功能。

如果我將getGenericItem()移動到主AppController,它工作正常。我怎樣才能讓它在GenericController中尋找路由器功能?

回答

0

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.

所以做到這一點:

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" 
    } 
}); 

這裏有一個jsbin,但它不工作,但是。

+0

NewsController怎麼樣?我如何有多個孩子控制器? – Mark

+0

@Mark,看我的編輯PLZ。 – user3995789