有没有办法让 CompositeView 中包含的 ItemView 仅在单击按钮时呈现? 我希望对集合进行更改以更新复合 View 的 dom,但每个单独的 ItemView 在需要之前不应呈现。
如果我的描述有点含糊,请原谅我,但我对 Backbone 和 Marionette 的了解非常有限。
最佳答案
正如您所知,Marionette 渴望获取您的复合(或集合) View 的 subview 并生成它们。这就是为什么复合 View render
方法中包含 _renderChildren
进程。一旦调用,实际上就没有办法有选择地渲染 subview 。
但是有一个后门可以绕过渲染整个集合。这就像使用空集合初始化
复合 View 一样简单,如下所示
//Define MyCollection` and MyCompositieView and then...
var myCollection = new MyCollection(); // Construct an empty collection
var myCompositeView = new MyCompositeView({ collection: myCollection });
“空”复合 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 内有一个模型数组,但在该 View 集合之外。我通常只是连接一个 $.getJSON
(或任何其他 AJAX 方法)来获取数据并将其存储在 View 对象的属性中。假设您在初始化时执行此操作:
initialize: function() {
var that = this,
dataUrl = "some/url";
$.getJSON(dataUrl, function(data) {
that.myModels = data;
});
},
并且,在您的综合 View 中,您可能会发生一个事件,例如单击综合 View 的某个元素:
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 确保渲染使用此模型填充的 subview 。
执行此操作的方式有多种,并且您不必在 View 中连接事件。但我想我证明了如何让方法独立渲染。如果您提供更多信息,我可以为您提供更多想法。
关于javascript - 点击事件时渲染 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27727414/