学习源码--Backbone
在看叶小钗的博客。。跟着他的范例做。。看到有一个小的设计模式吧。。先上代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="contactapp"> <header> <h1> 通讯录 </h1> </header> <section id="main"> <ul id="contact-list"> </ul> </section> <div class="create"> <label> 姓名:<input type="text" id="name"/> </label> <label> 电话:<input type="text" id="phone"/> </label> <input type="button" value="保存" id="add"/> </div> </div> </body> <script src="../libs/jquery-1.9.1.js"></script> <script src="../libs/underscore.js"></script> <script src="../libs/backbone.js"></script> <script src="../libs/Backbone.localStorage.js"></script> <script> (function($){ var Contact = Backbone.Model.extend({ initialize: function(){ this.bind('error', function(model,error){ alert(error); }) }, validate: function(attr){ if(attr.name.length == ''){ return '姓名格式错误'; } } }); var ContactList = Backbone.Collection.extend({ model: Contact, localStorage: new Store('contacts') }); var list = new ContactList(); var ContactView = Backbone.View.extend({ tagName : 'li', template: _.template('<div><%=name%>:<%=phone%></div>'), events:{ 'click li': 'test' }, initialize: function(){ _.bindAll(this,'render','remove'); this.model.bind('change',this.render); this.model.bind('destroy',this.remove); }, render: function(){ var html = this.template(this.model.toJSON()); $(this.el).html(html); return this; }, remove: function(){ $(this.el).remove(); }, test: function(){ alert(this); var s=''; } }); var AppView = Backbone.View.extend({ el:$('body'), events:{ 'click #add':'save' }, initialize: function(){ this.name = this.$('#name'); this.phone = this.$('#phone'); this.list = this.$('#contact-list'); _.bindAll(this,'render','add','loadList','save'); //集合绑定主视图事件 list.bind('add',this.add); list.bind('refresh', this.loadList); //同步服务器。暂时没什么用 // list.fetch(); }, add: function(model){ var view = new ContactView({model : model}); //初始化基础视图后,添加到主视图 this.list.append(view.render().el); }, //重新读取所有的基础视图组合成主视图 loadList: function(){ list.each(this.add); }, save: function(){ var name = this.name.val(); var phone = this.phone.val(); //向集合中创建并添加一个模型,同时保存到服务器 list.create({name:name,phone:phone}); //清空输入框值 this.name.val(''); this.phone.val(''); } }); app = new AppView(); })(jQuery) </script> </html>
一直以为一个模型一个集合一个视图就能很好的玩出花样。。想法太LOW。。
上面的这个实例,拥有双视图、、用双视图来实现删除效果、、相当好的设计模式。。
一个主视图,中间挂载一个小视图。来实现Model和View的互动、。靠JS自身维持住需要的对象。。学习了、

浙公网安备 33010602011771号