$.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:...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.