乐帝当年学习backbone时。最開始是看官网todoMVC的实现。后来了解到requireJS便于管理JS代码。就对官网代码做了requireJS管理。但此时乐帝感觉此时的todoMVC仍然不够简明,为了加深对MVC架构的理解。乐帝对原有appview代码进行了重构,将相关显示模块单独提取出自称view。实现view原子化。乐帝已经将这个项目上传(下载地址)。
增加requireJS的文件夹结构:
这里主要用到templates用于放置view相应的模板。views则相应backbone中view文件。假设说backbone是前端MVC,那么model是对数据建立模型。collection则是对model统一管理,view则起到控制器的作用,用于填充数据到模板,并渲染模板到显示。model、collection起到M作用。view起到C的作用,模板则起到V的作用。
然后我们看一下todoMVC的效果图:
从终于效果图。我们能够分析出,要对原有appview中解耦出原子view。就须要推断出哪些是原子view。原子view须要具备两点:
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();
}
}, // 实现总体显示前端编程提高之旅(六)----backbone实现todoMVC
原文:http://www.cnblogs.com/mengfanrong/p/5161432.html