2012-03-07 52 views
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演示該問題。

有沒有更好的方法來處理這個問題?

回答

4

正如你在重新渲染整個事情,你需要清除舊渲染的輸入。

http://jsfiddle.net/Zk9NX/8/

改變的ItemListView

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() { 
     var self = this; 
     this.$el.empty() 
     this.collection.each(function (item) { 
     self.$el.append(new ItemView({ model: item }).render().el); 
     }); 
     return this; 
    }, 
}); 
+0

這是有道理的。這是我使用的jQuery方法的更好的解決方案 - 它的作用域是視圖。謝謝! – 2012-03-07 18:03:59