问题 如何将 subview 生命周期职责从MyView
移至Marionette
? (见下面的代码)
这里的问题是 items
数组是在服务器上动态形成的,我不想在 MyView
中遍历它们。我需要 Marionette.CollectionView
吗?
代码:
我有 my-view.hbs
模板:
{{#each items}}
<button class="button">name</button>
<div name="target"/> <!-- each target div should contain a subview -->
{{/each}}
以及渲染它的 View :
var MyView = Marionette.LayoutView.extend({
template: Templates['my-view.hbs'],
render: function() {
var items = [ //actually they come from server
{name: 'car'},
{name: 'bike'},
{name: 'skiboard'},
];
this.$el.html(
this.template({ items: items })
);
this.renderSubViews();
return this;
},
/**
* It creates, renders and append subViews manually.
* TODO: move responsibilities to Marionette
*/
renderSubViews: function() {
var self = this;
self.subViews = [];
self.$('div[name=target]').each(function(index, subViewContainer) {
var subView = new SubView();
self.subViews.add(subView);
subView.render();
$(subViewContainer).append(subView.$el);
});
}
});
最佳答案
如果简短,是的,您需要Composite 或Collection View 。 此外,我建议您使用 Collection 而不是普通对象,它将帮助您更轻松地在数据(模型)和您的 View 之间进行通信:
var ItemModel = Backbone.Model.extend({
defaults: {
name: 'unnamed'
}
}),
ItemsCollection = Backbone.Collection.extend({
model: ItemModel
}),
MyChildView = Marionette.ItemView.extend({
template: Templates['my-view.hbs']
}),
MyView = Marionette.CollectionView.extend({
childView: MyChildView,
collection: new ItemsCollection([
{name: 'car'},
{name: 'bike'},
{name: 'skiboard'}
])
});
你的模板也会更简单:
<button class="button">name</button>
<div name="target"/>
关于javascript - 如何将 subview 生命周期责任移至 Marionette,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30053246/