$.fn.extend({
insertAt: function(index, element) {
// Get the length of the child node collection
var lastIndex = this.children().size();
// If the index of the new item is before the end then insert
if(index < lastIndex) {
this.children().eq(index).before(element);
} else { // else append
this.append(element);
}
return this;
}
});
var ListItem = Backbone.Model;
var ListCollection = Backbone.Collection.extend({
model: ListItem,
comparator: function(item) {
return item.get('name').toLowerCase();
}
});
var ListItemView = Backbone.View.extend({
tagName: 'LI',
render: function() {
this.$el.html(this.model.get('name'));
return this;
}
});
var ListView = Backbone.View.extend({
tagName: 'OL',
initialize: function() {
this.listenTo(this.collection, 'add', this.addItem);
},
render: function() {
var self = this;
var items = [];
this.collection.each(function(item) {
items.push(self.buildItemView(item).render().el);
});
this.$el.html(items);
return this;
},
addItem: function(item) {
console.log('item: ', item);
// Get the index of the newly added item
var index = this.collection.indexOf(item);
console.log('index: ', index);
// Build a view for the item
var $view = this.buildItemView(item).render().$el;
// Insert the view at the same index in the list
this.$el.insertAt(index, $view.hide().fadeIn(1000));
},
buildItemView: function(item) {
return new ListItemView({model: item});
}
});
var FormView = Backbone.View.extend({
tagName: 'FORM',
events: {
'submit': 'submitForm'
},
render: function() {
this.$input = $('<input>', {type: 'text', value: 'Hulk'});
this.$el.append(this.$input);
this.$el.append($('<input>', {type: 'submit', value: 'Add'}));
return this;
},
submitForm: function(ev) {
ev.preventDefault();
var name = this.$el.find('input[type=text]').val();
this.collection.add({name: name});
this.$input.val('').focus();
}
});
var list = new ListCollection([
{name: 'Captain America'},
{name: 'Iron Man'}
]);
var listView = new ListView({collection: list});
var form = new FormView({collection: list});
$(document.body).append('<h1>Characters</h1>');
$(document.body).append(form.render().el);
$(document.body).append(listView.render().el);
External resources loaded into this fiddle: