启动/停止木偶模块和路由

时间:2013-07-15 15:09:50

标签: backbone.js marionette

我们如何处理路径之间的启动/停止模块,而无需明确告知路由的控制器方法来启动/停止每个模块。

var AppRouterController = {
  index: function() {
    // Start only modules I need for this route here
    // in this case, HomeApp only
    App.module('HomeApp').start();
    // Stop all modules that should not be running for this route
    // The idea, being that not everyone has to come to the index route first
    // They could have been to many other routes with many different modules starting at each route before here
    App.module('Module1').stop();
    App.module('ModuleInfinity').stop();
    // ...
    // ...
    // This could get tedious, expensive, and there has to be a better way.
  },
  someOtherRouteMethod: function() {
    // Do it all over again
  }
}

我知道我在这里做错了,希望不是从根本上,但如果有更好的方法,请告诉我。模块管理将成为该项目的关键,因为它将主要在平板设备上运行。

1 个答案:

答案 0 :(得分:3)

你开始并停止每条路线中的每个模块似乎有些过分。 Marionette没有多少内置帮助你像这样处理你的模块。

如果您真的想要这样做,我建议您为您的路由编写一个包装器,它将启动模块列表并在启动/停止模块后运行。

这样的事情:

(function (App) {
  var listOfAllModules = ["HomeApp", "Module1", ...];
  window.moduleWrapper = function (neededModules, route) {
    return function () {
      _.each(_.without(listOfAllModules, neededModules), function (moduleName) {
        App.module(moduleName).stop();
      });
      _.each(neededModules, function (moduleName) {
        App.module(moduleName).start();
      });
      route.apply(this, arguments);
    }
  };
})(App);

然后,在您的路由器中,只需包装需要处理模块的路由。

var AppRouterController = {
  index: moduleWrapper(["HomeApp"], function() {
    // Only routing logic left...
  })
};