0
首次处理项目并使用Backbone/Marionette。将集合拆分为多个视图(主干/牵线木偶)
我将一些数据从一个API拉到一个集合中,我想将这些项目分组并将它们显示在一个选项卡式界面中,每个组进入其自己的选项卡。
以下是我的代码的蒸馏版本。我还创建了一个jsfiddle。
var MyModel = Backbone.Model.extend({/* attributes: type, name */});
var MyCollection = Backbone.Collection.extend({model: MyModel});
var MyView = Marionette.ItemView.extend({
tagName: 'li',
template: _.template("<%= name %>")
});
var MyCollectionView = Marionette.LayoutView.extend({
el: '#tabs-content',
template: _.template('<div id="A"></div><div id="B"></div><div id="C"></div>'),
regions: {
rA: '#A',
rB: '#B',
rC: '#C'
},
initialize: function() {
var SubView = Marionette.CollectionView.extend({
childView: MyView,
tagName: 'ul'
});
this.viewA = new SubView({collection: new Backbone.Collection()});
this.viewB = new SubView({collection: new Backbone.Collection()});
this.viewC = new SubView({collection: new Backbone.Collection()});
},
onBeforeRender: function() {
var grouped = this.collection.groupBy('type');
this.viewA.collection.reset(grouped.a);
this.viewB.collection.reset(grouped.b);
this.viewC.collection.reset(grouped.c);
},
onRender: function() {
this.regionManager.get('rA').show(this.viewA);
this.regionManager.get('rB').show(this.viewB);
this.regionManager.get('rC').show(this.viewC);
}
});
有一对夫妇的事情,关心我,我的解决方案:
- 在LayoutView对象手动创建子视图看起来凌乱;有没有更好的办法?
- 集合被复制到子视图,所以如果我有1000种型号,我现在已经在内存2000款
是否有更好的方法来管理呢?提前致谢。
感谢@knpsck的回应。好奇你的意思是“使用控制器”?你的意思是类似于一个战略课? - 感谢jsfiddle并指出attachHtml方法。还没有读过它呢。我已经可以想到其他地方使用它。 – jbarreiros 2014-10-29 17:53:23