一个backbone实例
1 (function($){ 2 // 每个新增的item 3 var Item = Backbone.Model.extend({ 4 defaults: { 5 part1: 'hello', 6 part2: 'world' 7 } 8 }); 9 10 var List = Backbone.Collection.extend({ 11 model: Item 12 }); 13 // 每个item html渲染 14 var ItemView = Backbone.View.extend({ 15 tagName: 'li', // name of (orphan) root tag in this.el 16 initialize: function(){ 17 _.bindAll(this, 'render'); // every function that uses 'this' as the current object should be in here 18 return this.render(); 19 }, 20 render: function(){ 21 $(this.el).html('<span>'+this.model.get('part1')+' '+this.model.get('part2')+'</span>'); 22 return this; // for chainable calls, like .render().el 23 } 24 }); 25 // 最终的view操作 26 var ListView = Backbone.View.extend({ 27 el: $('body'), // el attaches to existing element 28 events: { 29 'click button#add': 'addItem' 30 }, 31 initialize: function(){ 32 _.bindAll(this, 'render', 'addItem', 'appendItem'); // every function that uses 'this' as the current object should be in here 33 34 this.collection = new List(); 35 // 36 this.collection.bind('add', this.appendItem); // collection event binder 37 38 this.counter = 0; 39 return this.render(); 40 }, 41 render: function(){ 42 var self = this; 43 $(this.el).append("<button id='add'>Add list item</button>"); 44 $(this.el).append("<ul></ul>"); 45 // 插入每个item 46 _(this.collection.models).each(function(item){ // in case collection is not empty 47 self.appendItem(item); 48 }, this); 49 return this; 50 }, 51 addItem: function(){ 52 this.counter++; 53 // 创建modle实例 54 var item = new Item(); 55 // 更改属性 56 item.set({ 57 part2: item.get('part2') + this.counter // modify item defaults 58 }); 59 // 添加到collection 层,这个时候会触发add 60 // 也就是调用 this.collection.bind('add', this.appendItem); 61 this.collection.add(item); 62 // console.log(this.collection); 63 }, 64 appendItem: function(item){ 65 var itemView = new ItemView({ 66 model: item 67 }); 68 console.log('-----------------'); 69 $('ul', this.el).append(itemView.el); 70 // console.log(itemView.render()); 71 } 72 }); 73 74 var listView = new ListView(); 75 })(jQuery);