相信每个接触了解过backbone的人都知道todo,网上的关于它的分析教程也都分析乱了。但是,知识只有自己学习领悟才是自己的,话不多说,正文开始。

在分析todo的源码之前,首先我们要知道todo具有哪些功能。todo类似于备忘录一样,其界面如下图:

1.当我们在输入框完成输入item时,按下enter键,下方会出现输入的内容item,item是一个li。

2.在所有item的最上面是一个全选checkbox。

3.每一个item是一个checkbox,当勾选任一行item时,则该行的内容会被删除线划掉,同时最下面的item left-1,Clear completed item+1。

4.当鼠标移到item上时,item的末端会出现一个删除符号,点击删除符号,该item即被删除。

简短介绍完todo的基本功能后,开始源码之旅。

todo.js整体长这个样子,如下图:

一个model,一个collection,两个view。

model详见如下:

   var Todo = Backbone.Model.extend({
defaults: function() {
return {
title: "empty todo...",
order: Todos.nextOrder(),
done: false
};
},
toggle: function() {
this.save({done: !this.get("done")});
}
});

默认设置defaults,返回一个list;定义了一个toggle,该触发器会设置保存model的状态。

collection详见如下:

  var TodoList = Backbone.Collection.extend({
model: Todo,
localStorage: new Backbone.LocalStorage("todos-backbone"),
done: function() {
return this.where({done: true});
},
remaining: function() {
return this.where({done: false});
},
nextOrder: function() {
if (!this.length) return 1;
return this.last().get('order') + 1;
},
comparator: 'order'
});

指定集合TodoList的mode为Todo,存储方式为localStorage,同时定义了done,remaining,nextOrder三个函数,最后指定了todo的排列顺序。

TodoView详见如下:

  var TodoView = Backbone.View.extend({
tagName: "li",
template: _.template($('#item-template').html()),
events: {
"click .toggle" : "toggleDone",
"dblclick .view" : "edit",
"click a.destroy" : "clear",
"keypress .edit" : "updateOnEnter",
"blur .edit" : "close"
},
initialize: function() {
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'destroy', this.remove);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
this.$el.toggleClass('done', this.model.get('done'));
this.input = this.$('.edit');
return this;
},
toggleDone: function() {
this.model.toggle();
},
edit: function() {
this.$el.addClass("editing");
this.input.focus();
},
close: function() {
var value = this.input.val();
if (!value) {
this.clear();
} else {
this.model.save({title: value});
this.$el.removeClass("editing");
}
},
updateOnEnter: function(e) {
if (e.keyCode == 13) this.close();
},
clear: function() {
this.model.destroy();
}
});

AppView详见如下:

  var AppView = Backbone.View.extend({
el: $("#todoapp"),
statsTemplate: _.template($('#stats-template').html()),
events: {
"keypress #new-todo": "createOnEnter",
"click #clear-completed": "clearCompleted",
"click #toggle-all": "toggleAllComplete"
},
initialize: function() {
this.input = this.$("#new-todo");
this.allCheckbox = this.$("#toggle-all")[0];
this.listenTo(Todos, 'add', this.addOne);
this.listenTo(Todos, 'reset', this.addAll);
this.listenTo(Todos, 'all', this.render);
this.footer = this.$('footer');
this.main = $('#main');
Todos.fetch();
},
render: function() {
var done = Todos.done().length;
var remaining = Todos.remaining().length;
if (Todos.length) {
this.main.show();
this.footer.show();
this.footer.html(this.statsTemplate({done: done, remaining: remaining}));
} else {
this.main.hide();
this.footer.hide();
}
this.allCheckbox.checked = !remaining;
},
addOne: function(todo) {
var view = new TodoView({model: todo});
this.$("#todo-list").append(view.render().el);
},
addAll: function() {
Todos.each(this.addOne, this);
},
createOnEnter: function(e) {
if (e.keyCode != 13) return;
if (!this.input.val()) return;
Todos.create({title: this.input.val()});
this.input.val('');
},
clearCompleted: function() {
_.invoke(Todos.done(), 'destroy');
return false;
},
toggleAllComplete: function () {
var done = this.allCheckbox.checked;
Todos.each(function (todo) { todo.save({'done': done}); });
}
});

Backbone.js之Todo源码浅析的更多相关文章

  1. 【深入浅出jQuery】源码浅析--整体架构

    最近一直在研读 jQuery 源码,初看源码一头雾水毫无头绪,真正静下心来细看写的真是精妙,让你感叹代码之美. 其结构明晰,高内聚.低耦合,兼具优秀的性能与便利的扩展性,在浏览器的兼容性(功能缺陷.渐 ...

  2. 【深入浅出jQuery】源码浅析2--奇技淫巧

    最近一直在研读 jQuery 源码,初看源码一头雾水毫无头绪,真正静下心来细看写的真是精妙,让你感叹代码之美. 其结构明晰,高内聚.低耦合,兼具优秀的性能与便利的扩展性,在浏览器的兼容性(功能缺陷.渐 ...

  3. 【深入浅出jQuery】源码浅析2--使用技巧

    最近一直在研读 jQuery 源码,初看源码一头雾水毫无头绪,真正静下心来细看写的真是精妙,让你感叹代码之美. 其结构明晰,高内聚.低耦合,兼具优秀的性能与便利的扩展性,在浏览器的兼容性(功能缺陷.渐 ...

  4. Android源码浅析(五)——关于定制系统,如何给你的Android应用系统签名

    Android源码浅析(五)--关于定制系统,如何给你的Android应用系统签名 今天来点简单的我相信很多定制系统的同学都会有一些特定功能的需求,比如 修改系统时间 静默安装 执行某shell命令 ...

  5. String 源码浅析————终结篇

    写在前面 说说这几天看源码的感受吧,其实 jdk 中的源码设计是最值得进阶学习的地方.我们在对 api 较为熟悉之后,完全可以去尝试阅读一些 jdk 源码,打开 jdk 源码后,如果你英文能力稍微过得 ...

  6. redux 源码浅析

    redux 源码浅析 redux 版本号: "redux": "4.0.5" redux 作为一个十分常用的状态容器库, 大家都应该见识过, 他很小巧, 只有 ...

  7. Struts2源码浅析-ConfigurationProvider

    ConfigurationProvider接口 主要完成struts配置文件 加载 注册过程 ConfigurationProvider接口定义 public interface Configurat ...

  8. (转)【深入浅出jQuery】源码浅析2--奇技淫巧

    [深入浅出jQuery]源码浅析2--奇技淫巧 http://www.cnblogs.com/coco1s/p/5303041.html

  9. HashSet其实就那么一回事儿之源码浅析

    上篇文章<HashMap其实就那么一回事儿之源码浅析>介绍了hashMap,  本次将带大家看看HashSet, HashSet其实就是基于HashMap实现, 因此,熟悉了HashMap ...

随机推荐

  1. javascript 无刷新上传图片之原理

    刚开始我认为可以像ajax 那样获取到数据然后通过ajax 发送请求,后来发现浏览器为了客户端的安全默认并没有给javascript 这个权限.这个方法当然是行不同了.我看了好像开源的上传图片原理,当 ...

  2. hdu-5720 Wool(区间并+扫描线)

    题目链接: Wool Time Limit: 8000/4000 MS (Java/Others)     Memory Limit: 262144/262144 K (Java/Others) Pr ...

  3. 「LuoguP1799」 数列_NOI导刊2010提高(06)

    题目描述 虽然msh长大了,但她还是很喜欢找点游戏自娱自乐.有一天,她在纸上写了一串数字:1,1,2,5,4.接着她擦掉了一个l,结果发现剩下1,2,4都在自己所在的位置上,即1在第1位,2在第2位, ...

  4. node安装升级npm

    安装npm npm上有很多优秀的nodejs包,来解决常见的一些问题,比如用node-mysql,就可以方便通过nodejs链接到mysql,进行数据库的操作 在开发过程往往会需要用到其他的包,使用n ...

  5. B. Mishka and trip

    time limit per test 1 second memory limit per test 256 megabytes input standard input output standar ...

  6. Asset Catalog Help (一)---About Asset Catalogs

    About Asset Catalogs Use asset catalogs to simplify management of images that are used by your app a ...

  7. Start Developing Mac Apps -- Design Patterns 设计模式

    Design Patterns A design pattern solves a common software engineering problem. Patterns are abstract ...

  8. linux以字符为单位进行读写操作

    1 所用函数 fgetc(FILE *fp):成功返回所读入的字符 失败为-1 fputc(int c,FILE *fp):第一个参数表示需要输出的字符 第二个参数表示输出的文件.成功返回输出的字符 ...

  9. (水题)洛谷 - P2089 - 烤鸡

    https://www.luogu.org/problemnew/show/P2089 非常暴力的dfs,不知道不剪枝会怎么样,但是其实最多也就 $3^{10}$ ,大不到哪里去.还有一个细节就是大于 ...

  10. BestCoder Round #74 (div.1) 1002Shortest Path(hdoj5636)

    哈哈哈哈,我就知道这道题目再扔给我,我还是不会,就是这么菜,哈哈哈 一开始官方题解就没搞懂-然后就看了一下别人的代码,水水过就算了.今天拿到-GG: 题意: 一开始,有一张原图,有一条长度为n的链. ...