众所周知,Marionette 渴望获取您的复合(或集合)视图的子视图并生成它们。这就是为什么包含在复合视图render 方法中的是_renderChildren 进程。一旦被调用,就真的没有办法选择性地渲染子视图了。
但是有一个后门可以绕过渲染整个集合。这是一个简单的 initializing 你的 Composite View 与一个空集合,像这样
//Define MyCollection` and MyCompositieView and then...
var myCollection = new MyCollection(); // Construct an empty collection
var myCompositeView = new MyCompositeView({ collection: myCollection });
一个“空”的 Composite View 会正常渲染它自己的模板,直接跳过_renderChildren。
然后您可以连接一个事件来调用myCompositeView.collection.add(model)。您会注意到 Marionette 在您的收藏中侦听 add 事件,
_initialEvents: function() {
if (this.collection) {
this.listenTo(this.collection, 'add', this._onCollectionAdd);
// Other _initialEvents methods...
}
},
而_onCollectionAdd负责渲染添加的模型:
_onCollectionAdd: function(child) {
this.destroyEmptyView();
var ChildView = this.getChildView(child);
var index = this.collection.indexOf(child);
this.addChild(child, ChildView, index); // The rendering happens here
},
把它们放在一起
要完成这项工作,您必须在 CompositeView 内但在该视图的集合之外有一个模型数组。我通常只是连接$.getJSON(或任何其他 AJAX 方法)来获取数据并将其存储在 View 对象的属性中。假设你在初始化时这样做:
initialize: function() {
var that = this,
dataUrl = "some/url";
$.getJSON(dataUrl, function(data) {
that.myModels = data;
});
},
而且,在您的复合视图中,您可能会有一个事件,比如点击复合视图的元素:
events: {
'click button': 'addChild'
}
addChild: function (event) {
// functionality to identify which child to add to the collection
this.collection.add(this.myModels[j]); // Where 'j' is the index the model you want lives in.
});
当addChild 被调用时,集合会添加正确的模型,Mariontte 会确保渲染一个填充了该模型的子视图。
如何做到这一点有多种变化,您不必在视图中连接事件。但我想我证明了如何让方法独立呈现。如果您提供更多信息,我可以为您提供更多想法。