我是backbonejs的初学者。我创建了一个消息 View 和一个消息 View 集合 喜欢
var MessageViewCollection = Backbone.View.extend({
initialize: function(options) {
this.options = options;
this.$el = $(options.el);
// this.render();
//this._addButton(this.options);
// this.model.on('change', this.render, this);
this.model.on('add', this.render, this);
this.model.on('remove', this.render, this);
// --> this.model is a collection : it has n models, which it fetches.
this.model.fetch({
success: function() {
console.log('Successfully fetched all messages');
},
error: function(err) {
console.log('Failed to fetch messages ' + err);
}
});
},
render: function() {
var self = this;
this.$el.html('');
// This button is getting rendered again ang again - can move the renderCollection.
this._addButton(this.options);
_.each(this.model.toArray(), function(message, i){
self.$el.append((new MessageView({model: message})).render().$el);
});
return this;
}
});
该 View 在开始时呈现。我发现当它获取时,它有n个模型。对于每个模型,它都会创建一个 MesageView
。但它似乎创建了 n*n 消息 View 。
最后只有 n 被追加到 DOM 中。
他们只有一个网络调用来获取这 n 个模型的集合。 这似乎浪费了客户端资源、内存、处理能力和电力。
我认为我正在监听“添加”到这个集合,这导致每次调用渲染,它都会添加到集合中。这是问题所在吗?
如何解决这个问题?
最佳答案
每次向集合添加内容时,都会再次运行渲染,从而迭代整个集合。
因此,您应该做的是为单个模型创建渲染函数。
this.listenTo(this.collection, 'add', this.renderMessage, this);
renderMessage: function(message) {
this.$el.append((new MessageView({model: message})).render().$el);
}
当然,为了避免混淆,您不应该将模型称为集合......
关于javascript - 当只需要 n 时,Collection Fetch 会生成 n*n 个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21849716/