2012-03-07 9 views
3

私のBackbone.jsアプリケーションでは、コレクションの既存のアイテムの間に新しいアイテムを挿入できる必要があります。これまで私がWeb上で見つけた例はすべて、新しいアイテムをコレクションの最後に追加する必要があると思われています。それは私の目的にはうまくいかないので、新しいアイテムが追加されたときにコレクション全体を再レンダリングすることにしました。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

すべてをレンダリングしているので、を実行します。は、古いレンダリングされた入力を消去する必要があります。理にかなって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

を変更された

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

。これは私が使用していたjQueryのアプローチよりも優れた解決策です。それはビューのスコープです。ありがとう! –