3
在我的Backbone.js应用程序中,我需要能够在集合中的现有项目之间插入新项目。我在网上发现的例子似乎都假定新的项目应该被追加到一个集合的末尾。这不适合我的目的,所以我选择在添加新项目时重新渲染整个集合。Backbone.js集合视图呈现重复项目
但是,原始项目不会从视图中删除;相反,将重复的一组项目追加到列表的末尾。我可以通过使用jQuery在渲染之前清除项目来解决这个问题,但这似乎是错误的。
这就是我现在所拥有的:
Item = Backbone.Model.extend({
price: null,
});
Items = Backbone.Collection.extend({
model: Item,
initialize: function() {
this.add(new Item({ price: '$0.50' }));
this.add(new Item({ price: '$0.60' }));
this.add(new Item({ price: '$0.70' }));
}
});
ItemView = Backbone.View.extend({
tagName: 'li',
initialize: function() {
this.model.bind('change', this.render, this);
},
render: function() {
var item_template = _.template($('#item-template').html(), { item: this.model });
this.$el.html(item_template);
return this;
},
events: {
"click .copy-item": "copyItem",
},
copyItem: function (event) {
var index = itemlistview.collection.indexOf(this.model);
itemlistview.collection.add(new Item, { at: index + 1 });
},
});
ItemListView = Backbone.View.extend({
el: '#item-rows',
initialize: function() {
_.bindAll(this);
this.collection = new Items();
this.collection.bind('add', this.render);
this.render();
},
render: function() {
// It works if I uncomment the line below
//$('.item-row').remove();
var self = this;
this.collection.each(function (item) {
self.$el.append(new ItemView({ model: item }).render().el);
});
return this;
},
});
var itemlistview = new ItemListView;
而且这里有一个jsFiddle演示该问题。
有没有更好的方法来处理这个问题?
这是有道理的。这是我使用的jQuery方法的更好的解决方案 - 它的作用域是视图。谢谢! – 2012-03-07 18:03:59