乐帝当年学习backbone时。最開始是看官网todoMVC的实现。后来了解到requireJS便于管理JS代码。就对官网代码作了requireJS管理。但此时乐帝感受此时的todoMVC仍然不够简明,为了加深对MVC架构的理解。乐帝对原有appview代码进行了重构,将相关显示模块单独提取出自称view。实现view原子化。乐帝已经将这个项目上传(下载地址)。javascript
增长requireJS的文件夹结构:html
这里主要用到templates用于放置view相应的模板。views则相应backbone中view文件。假设说backbone是前端MVC,那么model是对数据创建模型。collection则是对model统一管理,view则起到控制器的做用,用于填充数据到模板,并渲染模板到显示。model、collection起到M做用。view起到C的做用,模板则起到V的做用。前端
而后咱们看一下todoMVC的效果图:java
从终于效果图。咱们可以分析出,要对原有appview中解耦出原子view。就需要推断出哪些是原子view。原子view需要具有两点:jquery
define([ 'jquery', 'underscore', 'backbone', 'text!templates/toggleAll.html' ], function($, _, Backbone, toggleTemplate) { var ToggleAllView = Backbone.View.extend({ toggleTemplate: _.template(toggleTemplate), events: { "click #toggle-all": "toggleAllComplete" }, initialize: function() { this.listenTo(this.collection, "all", this.render); //除了todoview与todomodel一一相应 // 其它相关操做都会监听collection }, render: function() { this.$el.html(this.toggleTemplate()); var done = this.collection.done().length; var remaining = this.collection.remaining().length; this.allCheckbox = this.$("#toggle-all")[0]; this.allCheckbox.checked = !remaining; return this; }, toggleAllComplete: function() { var done = this.allCheckbox.checked; this.collection.each(function(todo) { todo.save({ done: done }); }); //这里经过推断单选框是否选中。改动所有modeldone属性 } }); return ToggleAllView; });
initialize: function() { this.listenTo(this.model, "change", this.render); this.listenTo(this.model, "destroy", this.remove); //当模型被删除,视图对应被移除 }
initialize: function() { this.listenTo(this.collection, "all", this.render); //除了todoview与todomodel一一相应 // 其它相关操做都会监听collection }
initialize: function() { // 初始化加入各类视图,新建视图并加入到父视图指定位置 this.footer = this.$el.find('footer'); this.main = $('#main'); this.todoCollection = new todos; inputview = new InputView({ collection: this.todoCollection }); $("#todoapp").prepend(inputview.render().el); //加入输入框 var toggleAllview = new ToggleAllView({ collection: this.todoCollection }); this.main.prepend(toggleAllview.render().el); //取得数据后,再初始化 this.allCheckbox = this.$("#toggle-all")[0]; this.listenTo(this.todoCollection, "add", this.addOne); this.listenTo(this.todoCollection, "reset", this.addAll); this.listenTo(this.todoCollection, "all", this.render); // 需要数据的视图。在获取数据后定义 this.todoCollection.fetch(); // 状态视图 statusview = new StatusView({ collection: this.todoCollection }); this.footer.append(statusview.render().el); //取得数据后,再初始化 }, render: function() { // 由于设置了all监听所有collection的操做。故加入一个项就会被渲染一次,这保证了有修改都会获得渲染到页面 var done = this.todoCollection.done().length; var remaining = this.todoCollection.remaining().length; this.allCheckbox = this.$("#toggle-all")[0]; if (this.todoCollection.length) { //渲染时运行显示或隐藏的代码 this.main.show(); this.footer.show(); this.footer.html(); //假设collection为空的话,则清空footer } else { this.main.hide(); this.footer.hide(); } }, // 实现整体显示