Backbone,Marionette,RequireJS应用程序启动

时间:2013-03-25 16:38:02

标签: backbone.js requirejs marionette startup bootstrapping

我正在使用Backbone,Marionette和RequireJS构建应用程序,如果可以通过任何方式改进/改进应用程序启动,我希望由一些经验丰富的人员运行。

文件夹结构:

index.html
js/
  collections/
  libs/
    backbone.js
    marionette.js
    require.js
    ...
  models/
  views/
  app.js
  init.js
  router.js

目前应用程序的引导程序如下:

index.html将requireJS入口点定义为:

<script data-main="js/init" src="js/libs/require.js"></script>

init.js执行RequireJS配置并执行:

require(['app'], function(App){
    App.start();
});

app.js中的应用模块:

App = new Backbone.Marionette.Application();

App.addInitializer(function (options) {
  // initialize the Router; will only setup the routes and corresponding callbacks; not history.start()
  App.router = new Router();
  // initialize Marionette regions
  App.addRegions({
    'header': '#header',
    'main': '#main',
    'footer': '#footer'
  });
});

App.on('start', function(options) {
  Backbone.history && Backbone.history.start() || console.error('No "Backbone.history" to .start()');
});

return App;

router.js中的路由器模块:

return Backbone.Router.extend({
    routes: {      
      'panel/:handle': 'showPanel',
    },

    showPanel: function (handle) {
      require(['app'], function (App) {
        App.main.show(new Panel_v({userHandle: handle}));
      });  
    }      
});

有没有办法让路由器模块不那么复杂?我通过这种方式解决了由App-&gt; Router-&gt; App。

形成的循环依赖问题

还有其他建议吗?

1 个答案:

答案 0 :(得分:6)

我最近来到这个解决方案,在main.js文件中加入App和Router:

App.js

define(['marionette'], function(Marionette) {
  var App;
  App = new Backbone.Marionette.Application();
  App.vars = {};
  App.addRegions({
    headerRegion: "#header-region",
    mainRegion: "#main-region",
    footerRegion: "#footer-region",
    dialogsRegion: "#dialogs"
  });
  App.vent.on("routing:started", function() {
    Backbone.history.start();
  });
  return App;
});

Router.js

    define(['marionette', 'app'], function(Marionette, App) {
      var appRouter, routerController;
      routerController = {
        showViaggi: function() {
          return require(['modules/viaggi/viaggi'], function(Viaggi) {
            App.Modules.viaggi = new Viaggi();
            return App.Modules.viaggi.start();
          });
        }
      };
      return appRouter = Backbone.Marionette.AppRouter.extend({
        appRoutes: {
          'viaggi': 'showViaggi'
        },
        controller: routerController
      });
    });

Main.js,我的初始脚本加载了Require.js

define(['app', 'routers/appRouter'], function(App,appRouter) {
  App.addInitializer(function() {
    App.Router = new appRouter;
    return App.vent.trigger("routing:started");
  });
  return App.start();
});