JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.1/backbone-min.js"></script>
JavaScript
$.fn.extend({
insertAt: function(index, element) {
// Get the length of the child node collection
var lastIndex = this.children().size();
console.log('element:',element);
// 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;
console.log('this.buildItemView(item):',this.buildItemView(item));
console.log('$view:',$view);
// Insert the view at the same index in the list
console.log('this.$el:',this.$el);
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':...