[英]Render view on click event
有沒有一種方法可以讓CompositeView中包含的ItemView僅在單擊按鈕時渲染? 我希望更改集合以更新復合視圖的dom,但是每個單獨的ItemView都必須在需要之前呈現。
如果我的描述含糊不清,請原諒我,但我對骨干和木偶的了解非常有限。
如您所知,Marionette渴望獲取您的Composite(或Collection)View的子視圖並生成它們。 因此,Composite View 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 });
“空”合成視圖將正常呈現其自己的模板,只需跳過_renderChildren
。
然后,您可以myCompositeView.collection.add(model)
一個事件以調用myCompositeView.collection.add(model)
。 您會注意到,木偶在您的收藏夾上監聽了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確保呈現使用此模型填充的子視圖。
執行此操作的方式各不相同,您不必在視圖中關聯任何事件。 但是我想我證明了如何使方法獨立呈現。 如果您提供更多信息,我可以給您更多的想法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.