Is there a straightforward way to insert a new model item into the middle of a backbone.js Collection
and then update the collection's View
to include the new item in the correct position?
I'm working on a control to add/delete items from a list. Each list item has its own Model
and View
, and I have a View
for the entire collection as well.
Each item view has a Duplicate
button that clones the item's model and inserts it into the collection at the index position below the item that was clicked.
Inserting the item into the collection was straightforward, but I'm having trouble figuring out how to update the collection view. I've been trying 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 is sort of working, but I'm getting strange bugs when I add a new item. I'm sure I can sort those out, but ...
There's a voice in my head keeps telling me that there's a better way to do this. Having to manually figure out where to insert a new ItemView
seems really hacky--shouldn't the collection view know how to rerender the collection already?
Any suggestions?