我希望我的复合材料能够自动渲染一个已经完成的集合。但是我也想让它为我取一个模型并给出该模型的复合访问权。
基本上我正在尝试使用以下客户端集合呈现用户详细信息。
CompositeView中
define([
"marionette",
"text!app/templates/user/view-clients/collection.html",
"app/collections/users/clients",
"app/views/user/view-clients/item",
'app/models/user'
],
function(Marionette, Template, Collection, Row, Model) {
"use strict"
return Backbone.Marionette.CompositeView.extend({
template: Template,
itemView: Row,
itemViewContainer: "#stage-user-clients",
collectionEvents: {
'sync': 'hideLoading'
},
initialize: function (options) {
this.showLoading()
this.model = new Model({_id: options.id})
this.model.fetch()
this.collection = new Collection()
this.collection.queryParams = {_id: options.id}
return this.collection.fetch()
},
showLoading: function() {
this.$el.addClass('loading')
},
hideLoading: function() {
this.$el.removeClass('loading')
}
})
})
ItemView控件
define(["marionette", "text!app/templates/user/view-clients/item.html"], function(Marionette, Template) {
"use strict"
return Backbone.Marionette.ItemView.extend({
template: Template,
tagName: "li"
})
})
我是否需要自己管理渲染方法或为模型创建单独的视图并手动将其绑定到复合模板中的id?
答案 0 :(得分:4)
您可能最好不要在视图中实现您的馆藏/模型。
var MyCompositeView = Backbone.Marionette.CompositeView.extend({
initialize: function() {
// The collection is already bound, so we take care only of the model
// Both will be rendered on model change, though
this.listenTo(this.model, 'change', this.render, this);
// If you want to rerender the model only, use this instead :
this.listenTo(this.model, 'change', function(){
this.$el.html(this.renderModel());
}, this);
}
...
});
var myCollection = new Collection({url: '/collection/'});
var myModel = new Model({url: '/model/', id: 1});
var myCompView = new MyCompositeView({model: myModel, collection: myCollection});
myModel.fetch();
myCollection.fetch({reset: true});
这大概就是它的样子。如果有疑问,请查看骨干的来源。