根据我的经验,UI模型非常有帮助。我们在我们的应用中为每个“页面”维护一个ContextModel
。真正好的是,我们保证“页面”被初始化为一个完整的ContextModel
,所以上下文最初只创建一个地方。
我们的AppView
总是处理在触发特定路由时为页面创建初始上下文。路由处理程序将设置上下文的缺省值,并从路由的值中解析出事物。
一旦页面本身已经初始化,它只需要担心对ContextModel
的更改,并且有处理程序可以进行必要的更新,然后更新路径。
这里是直接从我们AppView
拉到一个例子:
onSomeRoute : function (project, category, pivot, tab, item) {
// Setup page context with defaults.
var options = {
category : 'traits',
tab : 'population',
item : null
};
// Figure out what the allowed categories and tabs are from this
// environment by checking against all schema items.
[snipped]
// Resolve the `category` and the `pivot`. Try and match the pivot's
// slug, else choose the first pivot in the category.
if (_(categories).contains(category)) options.category = category;
[snipped]
if (pivots) options.pivot = pivots.find({ slug : pivot }) || pivots.first();
// Resolve the `tab` and `item`. Only allow valid tabs, and then try
// to match the item's slug as well, or choose the first one.
var tabs = ['population', 'sources', 'engagement', 'retention'];
if (_(tabs).contains(tab)) options.tab = tab;
[snipped]
// Now that we've applied some defaults, make sure the path is
// updated to reflect what the interface is showing.
[snipped]
this.loadPage('some-page', options);
}
然后在有问题的PageView
我们有几个变化处理程序:
// When category changes, try to match the current pivot against pivots
// in the category, else choose the first pivot from the category.
onCategoryChange : function (context, category) {
var schema = this.context.get('environment').get(category);
if (!schema.contains(this.context.get('pivot')))
this.context.set('pivot', schema.first());
this.router.update({
category : category
});
},
// When the pivot changes, create a new set of segments for the context.
onPivotChange : function (context, pivot) {
Segmenter.segment(context, function (segments) {
context.get('segments').reset(segments).each(function (segment) {
segment.evaluate();
});
});
this.router.update({
pivot : pivot.get('slug')
});
},
请注意,所有的变化处理的保持根据上下文中的更改更新页面的URL。 (我们在路由器上写了一些自定义的方法,以使我们真的很容易。)但是他们也做了我们需要为页面发生的任何其他逻辑。
希望有一些可以帮助您给出想法。一般来说,存储在URL中的任何状态都在我们的PageContext
中,然后为了方便起见,还存储了来自该状态的其他一些事情。
我使用Flat backbone.js模型创建了一个treeview。这很容易,可能你可以谈谈你的场景,以便我可以提供直接的解决方案:)顺便说一句,问题取决于你作为模型和视图休息只是编程(你会使用递归内部渲染方法来构建视觉效果) – Deeptechtons 2012-07-23 04:46:51