是否有比下面的方法更优雅的方法来将另一个 View 附加到区域?我想在单击按钮时附加尽可能多的聊天窗口,并在单击聊天窗口中的按钮时销毁它。
下面的要求跟踪每个元素的索引:
var AppLayoutView = Backbone.Marionette.LayoutView.extend({
template: "#layout-view-template",
regions: {
wrapperChat : '#wrapper-chat'
}
appendView: function ( incremennt, newView ){
this.$el.append( '<div id="view'+increment+'" >' ) ;
this.regionManager.addRegion( 'view'+increment , '#view'+increment )
this['view'+increment].show ( newView ) ;
}
});
// ChatView
var ChatView = Marionette.ItemView.extend({
template: "#chat-template"
});
// Layout
var LayoutView = new AppLayoutView();
LayoutView.render();
// Append View
LayoutView.wrapper.appendView(++index, new ChatView());
最佳答案
区域旨在显示单个 View 。 Marionette 对重复 View 的抽象是 CollectionView
,它为每个 Model 呈现一个 ItemView
在 Collection .
您从集合中添加或删除模型; Marionette 会为您处理 View 更新。
如果您的 ChatView
已有模型,请使用它。如果没有,您可以添加一个简单的模型来抽象 index
变量。
// Collection for the Chat models.
// If you already have Chat Collection/Models, use that.
// If not, create a simple Collection and Models to hold view state, e.g.:
var chats = new Backbone.Collection();
// CollectionView "subclass"
var ChatCollectionView = Marionette.CollectionView.extend({
itemView: ChatView
})
// Add a single ChatCollectionView to your region
var chatsView = new ChatCollectionView({ collection: chats });
LayoutView.getRegion('wrapperChat').show();
// To add a ChatView, add a Model to the Collection
var nextChatId = 0;
chart.addChat(new Backbone.Model({ id: nextChatId++ }));
// To remove a chat, remove its model
chart.remove(0);
关于javascript - 在 Marionette 中将多个 View 附加到某个区域的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33700169/