基于Backbone.history.fragment动态加载控制器文件

时间:2014-03-05 21:50:44

标签: backbone.js requirejs marionette

我正在构建一个包含50多个模块的应用程序。使用require函数动态加载控制器+路由器是个好主意吗?以下是来自app.js文件的sudo代码,我正在使用require.js和marionette

app.on("initialize:after", function(){
  if(Backbone.history){
    Backbone.history.start();

    /* For now I am considering the app with have only single 
    level routing, something like http://localhost#module and
    app will always call list method from controller */    

    var moduleName = Backbone.history.fragment;
    var controllerFile = "app/controller/" + moduleName + "controller";

    require([controllerFile], function() {
      app.trigger( moduleName + ':' + 'list');
    }
  }
})

我的控制器文件包含路由器,它会在初始化必要的模型后直接调用视图。我看到使用此方法需要函数的唯一风险可能在控制器文件满载之前被调用。我没有在代码中添加任何保护措施,当我理解这是一个好的方法时,我会这样做。

1 个答案:

答案 0 :(得分:0)

您的路由器应包含控制器。不是相反。

由于您有50个模块,我建议您查看Marionette.module及其addInitializer ()startWithParent,以便在需要加载时启动所有这些模块。

您可以同时使用requireJS和Marionette.module。