2013-07-15 35 views
2

我们如何处理路由之间的启动/停止模块,而不必明确告诉路由的控制器方法来启动/停止每个模块。启动/停止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 
    } 
} 

我知道我在这里做错了什么,希望不是根本,但请让我知道是否有更好的方法。由于它将主要在平板设备上运行,所以模块管理将成为该项目的关键。

回答

3

好像你是启动和停止每条路线中的每个模块矫枉过正。没有太多的内置到木偶,以帮助你像这样玩杂耍你的模块。

如果你真的想这样做,我建议是写你的路由的包装,采用模块的列表,开始和我功能启动/停止模块后运行。

事情是这样的:

(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... 
    }) 
}; 
+0

这是一个奇妙的答案。也许,我正在考虑如何错误地处理我的模块。我的印象是这样的,这只是有道理的。毕竟,为什么要在HomeApp中运行3次点击模块?如果这是最好的方法,我一定会使用这种方法。是否有充分的理由不考虑仅仅因为实际需要启动模块? – Jarrod

+2

根据我的经验,有选择地启动模块对于几个不同的事情是有用的。 1.你有单独的脚本不属于你的主要应用程序,但你需要在一些页面上。一个很好的例子就像一个使用d3.js的图形库,您只需要该应用程序特定部分的代码和周围的模块。 2.您的模块负责大部分不相关的启动代码。例如,像一个现场演示页面,在开始时会产生大量假数据。 –