backbonejs往簡單說,就是一前端MVC框架,適合用於單頁面、複雜的前端邏輯。html
直接上代碼,裏面都有相關注釋,重點是理解清楚view、collection、model這三者如何關聯調用。前端
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 5 <title>backbone實例01</title> 6 </head> 7 <body> 8 <input type="text" id="add"> 9 <ul id="man-list"> 10 </ul> 11 <script src="vendor/zepto.js"></script> 12 <script src="vendor/underscore.js"></script> 13 <script src="vendor/backbone.js"></script> 14 <script> 15 (function ($) { 16 //定義model 17 var People = Backbone.Model.extend({ 18 defaults: { 19 name: null 20 } 21 }); 22 23 //定義Collection 24 var Peoples = Backbone.Collection.extend({ 25 model: People,//關聯上了相關model 26 initialize: function(options) { 27 this.bind('add',options.view.show);//這裏事件監聽關鍵 28 } 29 }); 30 31 //定義view 32 var AppView = Backbone.View.extend({ 33 el: $("body"), 34 initialize: function() { 35 this.peoples = new Peoples({view: this});//關聯上集合 36 }, 37 events: { 38 'keypress #add': 'addMan' 39 }, 40 addMan: function(e) { 41 var key = e.which; 42 if(key !== 13) return; 43 var name = $(e.target).val(); 44 var people = new People({name:name}); 45 this.peoples.add(people);//添加model到集合,與此同時會觸發集合中的監聽方法 46 }, 47 show: function(model){//集合調用view中的方法,並能將集合中的model傳遞過來 48 var template = "<li>大家好,我是"+model.get('name')+",請多多關照!</li>"; 49 $('#man-list').append(template); 50 $('#add').val(''); 51 } 52 }); 53 54 new AppView(); 55 })(Zepto); 56 </script> 57 </body> 58 </html>
該例中,入口是Appview,其初始化時就關聯了一collection,在該collection中關聯上了model,並添加了‘add’監聽方法,該方法在往集合中添加model時出發,這裏在出發時會調用view中的相關方法渲染頁面。app
backbone實例02。。。。。進行中。。。。。框架