backbone入门小例子
最近听了个backbone的分享,为了避免听不懂,就先做了个小例子
例子很简单,效果如下
基本视图模板:
1 <script type="tex/template" id="template" > 2 <span><%=val%></span><span class="swap" style="margin:10px;cursor:pointer;">swap</span><span class="delete" style="margin:10px;cursor:pointer;">delete</span> 3 </script>
构建基本数据模型和集合:
1 var Man=Backbone.Model.extend({ 2 defaults:{ 3 name:'张三', 4 age:'1' 5 }, 6 }); 7 var ManList = Backbone.Collection.extend({ 8 model:Man 9 })
基本的视图模型
1 var ItemView = Backbone.View.extend({ 2 tagName:'li', 3 /*为视图注册事件*/ 4 events:{ 5 "click span.swap":"swap", 6 "click span.delete":"remove" 7 }, 8 initialize:function(){ 9 /*为视图和模型绑定事件*/ 10 _.bindAll(this, 'swap','render','remove','unrender'); 11 this.model.bind('change',this.render); 12 this.model.bind('remove',this.unrender); 13 }, 14 render:function(){ 15 var val = this.model.get('name')+""+this.model.get('age'); 16 var html = _.template($("#template" ).html(), {val:val}); 17 $(this.el).html(html); 18 return this; 19 }, 20 unrender:function(){ 21 $(this.el).remove(); 22 }, 23 swap:function(){ 24 var swaped = { 25 name:this.model.get('age'), 26 age:this.model.get('name') 27 } 28 this.model.set(swaped); 29 }, 30 remove:function(){ 31 this.model.destroy(); 32 } 33 })
主视图模型
1 var ListView = Backbone.View.extend({ 2 el:$("body"), 3 events:{ 4 "click button#add":"addItem" 5 }, 6 initialize:function(){ 7 /*为主视图和集合绑定事件*/ 8 _.bindAll(this, 'render', 'addItem', 'appendItem'); 9 this.collection = new ManList(); 10 this.collection.bind('add', this.appendItem); 11 /*初始化主视图*/ 12 this.render(); 13 /*声明主视图的属性*/ 14 this.age = 1; 15 }, 16 addItem:function(){ 17 this.collection.add(new Man({age:this.age++})) 18 }, 19 appendItem:function(item){ 20 var itemView = new ItemView({ 21 model: item 22 }); 23 24 $(this.el).find('ul').append(itemView.render().el); 25 }, 26 render:function(){ 27 var self = this; 28 $(this.el).append('<button id="add">add item</button>'); 29 $(this.el).append("<ul></ul>"); 30 31 } 32 })
初始化视图
var listView = new ListView();