Backbone Demo
by simucal
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.1.7/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.3/backbone-min.js"></script>
JavaScript
(function($) {
Backbone.sync = function(method, model, success, error) {
success();
}
var Item = Backbone.Model.extend({
defaults: {
part1: 'hello',
part2: 'world'
}
});
var List = Backbone.Collection.extend({
model: Item
});
var ItemView = Backbone.View.extend({
tagName: 'li',
events: {
'click span.swap': 'swap',
'click span.delete': 'remove'
},
initialize: function() {
_.bindAll(this, 'render', 'unrender', 'swap', 'remove');
this.model.bind('change', this.render);
this.model.bind('remove', this.unrender);
},
render: function() {
$(this.el).html('<span>'+this.model.get('part1')+' '+this.model.get('part2')+'</span>'+
'<span class="swap" style="color: blue; cursor: pointer">Swap</span>'+
'<span class="delete" style="color: red; cursor: pointer">Delete</span>');
return this;
},
unrender: function() {
$(this.el).remove();
},
swap: function() {
var swapped = {
part1: this.model.get('part2'),
part2: this.model.get('part1')
};
this.model.set(swapped);
},
remove: function() {
this.model.destroy();
}
});
var ListView = Backbone.View.extend({
el: $('body'),
events: {
'click button#add': 'addItem',
},
initialize: function() {
_.bindAll(this, 'render', 'addItem', 'appendItem');
this.collection = new List();
this.collection.bind('add', this.appendItem);
this.counter = 0;
this.render();
},
render: function() {
$(this.el).append('<button...