Is there an easy way to insert a new model element in the middle of the backbone.js Collection
and then update the View
collection to include the new element in the correct position?
I am working on a control to add / remove items from a list. Each list item has its own Model
and View
, and I have a View
for the entire collection.
Each element view has a Duplicate
button, which clones the model of the element and inserts it into the collection at the index position below the element that was clicked.
Inserting an item into the collection was simple, but I find it difficult to figure out how to update the collection view. I tried something like this:
ListView = Backbone.View.extend({ el: '#list-rows', initialize: function () { _.bindAll(this); this.collection = new Items(); this.collection.bind('add', this.addItem); this.render(); }, render: function () { this.collection.each(this.addItems); return this; }, addItem: function (item) { var itemView = new ItemView({ model: item }), rendered = itemView.render().el, index = this.collection.indexOf(item), rows = $('.item-row'); if (rows.length > 1) { $(rows[index - 1]).after(rendered); } else { this.$el.append(rendered); } } }
This implementation seems to work, but I get weird errors when I add a new item. I'm sure I can sort them, but ...
There a voice in my head tells me that there is a better way to do this. You need to manually determine where to insert the new ItemView
seems really hacked - shouldn't the collection view know how to re-collect?
Any suggestions?
source share