我有一组需要共享相同集合的模块.
在模块启动之前,集合需要准备就绪.
我不确定如何以最干净的方式解决这个问题,我意识到这可能因项目而异,但这里有一些想法.
这是我想到的第一件事,只需在我调用"App.start()"之前加载集合.
然后我可以让它在全球范围内访问(不确定我喜欢这个.).
如果我构建应用程序使其具有主模块,则负责启动所有子模块.
然后我可以在启动任何子模块之前预加载所有重要数据,并确保它已准备就绪.
然后可以通过主模块API访问它.
我不知道这是不是很糟糕的设计,我对木偶的经验是有限的.
Atm我选择在"App.start()"之前加载集合,这让我觉得我也在预加载我的模板.
我引入了一个名为"CollectionManager"的"静态"对象,它充当我的集合的代理/访问点.并将在全球范围内提供.
// Templates that should be ready on start up
var arrTemplatesPaths = [...];
// Collections that i need to be ready and shared between modules.
var arrSharedCollections = [
{id:"groups", collection: GroupCollection}
];
// Preloading the vital data.
$.when.apply(null, [
Templates.fetch(arrTemplatesPaths),
CollectionManager.fetch(arrSharedCollections)
])
.then(function(){
App.start();
})
Run Code Online (Sandbox Code Playgroud)
然后需要访问集合的模块可以只调用CollectionManager.get(id)
var collection = CollectionManager.get("groups"); //@return Backbone.Collection
Run Code Online (Sandbox Code Playgroud)
这提供了一些结构,但我不确定我喜欢这么多.
所以在Marionette doc中挖了一点后,我注意到了Marionette.RequestResponse.
这提供了一种从模块内部请求数据的简洁方法,为我的方法创建了一个抽象级别,以一种烦人的方式耦合了一些东西.
所以我已将此行添加到应用程序中:
App.reqres.addHandler("getCollection", function (id) {
return CollectionManager.get(id);
})
Run Code Online (Sandbox Code Playgroud)
然后从模块中我以这种方式访问集合:
var collection = App.request("getCollection", "groups")
Run Code Online (Sandbox Code Playgroud)
我喜欢这种方式,然后直接从模块中访问CollectionManager.
关于在显示视图之前或之后加载集合/模型的主题,我发现最好的方法是在 Marionette 控制器中获取模型/集合,然后显示视图,在获取模型/集合后传递该模型/集合。看起来像这样:
控制器(或路由器)
showUser: function(id) {
var userModel = new UserModel({id: id});
userModel.fetch().then(function() {
mainRegion.show(new UserView({model: userModel}));
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
637 次 |
| 最近记录: |