【再探backbone 01】模型-Model

时间:2022-12-06 15:30:01

前言

点保存时候不注意发出来了,有需要的朋友将就看吧,还在更新......

几个月前学习了一下backbone,这段时间也用了下,感觉之前对backbone的学习很是基础,前几天有个园友问我如何将路由的#改为其他

我其实想说这个不能乱改,又怕不熟悉误人子弟,所以今天我们来一起重新学习下他,看看会不会带来不一样的感觉

我在博客园nuysoft的博客看到了backbone的分析,可惜没有写完,不失为一个遗憾,希望作者坚持下去,水平高得贡献出来哟(@nuysoft)

然后,网上backbone基础用法的学习文章很多,感觉就nuysoft的深入,只不过多是点一下有点可惜,再次希望作者坚持下去......

Web应用越来越关注前端,现在一个服务器端可能要对付五个前端,前端的业务逻辑复杂,各种问题层出不穷,现实对javascript程序的重用性、健壮性提出了更高的要求

要求提高了,但是并不会给你更多的时间,反而为了抢占移动市场份额而拉快开发速度,现在的前端不可谓不难

PS:如果你的公司是互联网公司且不重视前端的话,你可以来我们公司啊......

Backbone是一个基于MVC模式的架构,本身强依赖与underscore,所以上个星期我们初略的学习了下underscore,有了一个大概印象

非强制依赖于jquery/zepto,然后require是一个很好的基友,建议不要放过

backbone据我使用来看,有几个优点:

① 模板引擎避免js中嵌入过多html代码,这是一种结构数据分离的体现,但是他要归功于underscore了

然后他的优点我用的时候就没有了......

以上说法其实有点坑爹,我们为了减少backbone的size,所以对backbone做了删除,最后只用到了其中的view(事件处理),控制器我们自己实现了

所以,我应该还未学习到backbone的精华,好了,前面扯多了,我们正式开始学习吧,这里附上之前的学习博客:

http://www.cnblogs.com/yexiaochai/p/3219402.html

http://www.cnblogs.com/yexiaochai/p/3221081.html

例子参考:http://www.ibm.com/developerworks/cn/web/wa-backbonejs/

简单例子

我们今天首先做一个简单的例子,然后通过例子去读backbone的源码,明天再整体进行学习,这个例子当然就是我们伟大的官方例子了......

第一步,页面结构

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Backbone.js Todos</title>
<link rel="stylesheet" href="todos.css" />
</head>
<body>
<div id="todoapp">
<header>
<h1>
Todos</h1>
<input id="new-todo" type="text" placeholder="What needs to be done?">
</header>
<section id="main">
<input id="toggle-all" type="checkbox">
<label for="toggle-all">
Mark all as complete</label>
<ul id="todo-list">
</ul>
</section>
<footer>
<a id="clear-completed">Clear completed</a>
<div id="todo-count">
</div>
</footer>
</div>
<div id="instructions">
Double-click to edit a todo.
</div>
<div id="credits">
Created by
<br />
<a href="http://jgn.me/">J&eacute;r&ocirc;me Gravel-Niquet</a>.
<br />
Rewritten by: <a href="http://addyosmani.github.com/todomvc">TodoMVC</a>.
</div>
<script src="../../test/vendor/json2.js"></script>
<script src="../../test/vendor/jquery.js"></script>
<script src="../../test/vendor/underscore.js"></script>
<script src="../../backbone.js"></script>
<script src="../backbone.localStorage.js"></script>
<script src="todos.js"></script>
<!-- Templates -->
<script type="text/template" id="item-template">
<div class="view">
<input class="toggle" type="checkbox" <%= done ? 'checked="checked"' : '' %> />
<label><%- title %></label>
<a class="destroy"></a>
</div>
<input class="edit" type="text" value="<%- title %>" />
</script>
<script type="text/template" id="stats-template">
<% if (done) { %>
<a id="clear-completed">Clear <%= done %> completed <%= done == 1 ? 'item' : 'items' %></a>
<% } %>
<div class="todo-count"><b><%= remaining %></b> <%= remaining == 1 ? 'item' : 'items' %> left</div>
</script>
</body>
</html>

页面结构比较简单,其实就只有一个文本框,然后下面有一个用于显示的列表,当然页面中有我们用到的模板

【再探backbone 01】模型-Model

第二步,定义model

然后我们需要定义我们备忘录的model了

 // Our basic **Todo** model has `title`, `order`, and `done` attributes.
var Todo = Backbone.Model.extend({ // Default attributes for the todo item.
defaults: function () {
return {
title: "empty todo...",
order: Todos.nextOrder(),
done: false
};
},
// Toggle the `done` state of this todo item.
toggle: function () {
this.save({ done: !this.get("done") });
}
});

这里需要注意他这种写法,我们后面会详细说明,这里先简单来看看这个实例化的结果

【再探backbone 01】模型-Model

我们看到一个Model实例化后有以上属性,主要注意点是title与down,事实上我们可以使用model的get/set去操作这些属性,model的主要工作其实就是维护他的属性

model维护的属性可能还会与服务器端发生通信,通信时会用到save方法,我们这里不予关注

 // "name" attribute is set into the model
var team1 = new App.Models.Team({
name : "name1"
});
console.log(team1.get("name")); // prints "name1" // "name" attribute is set with a new value
team1.set({
name : "name2"
});
console.log(team1.get("name")); //prints "name2"

这里需要注意的一点是,数据变化时候会引发Model的change方法,如果在change方法中,绑定对dom的操作,那么model变化页面就会自动发生变化,这就是model这点小九九干的事情

代码内部具体干什么的我们暂时不管,继续往下看,有了model后就会有集合

第三步,集合

 var TodoList = Backbone.Collection.extend({
// Reference to this collection's model.
model: Todo,
// Save all of the todo items under the `"todos-backbone"` namespace.
localStorage: new Backbone.LocalStorage("todos-backbone"),
// Filter down the list of all todo items that are finished.
done: function () {
return this.where({ done: true });
},
// Filter down the list to only todo items that are still not finished.
remaining: function () {
return this.without.apply(this, this.done());
},
// We keep the Todos in sequential order, despite being saved by unordered
// GUID in the database. This generates the next order number for new items.
nextOrder: function () {
if (!this.length) return 1;
return this.last().get('order') + 1;
},
// Todos are sorted by their original insertion order.
comparator: 'order'
});

这里对集合与之前定义的Model做了一个映射关系,他这个集合有何作用已经如何发生变化的我们后面详细说明

这里我只能说,这个集合时保存Model的列表,并在内部定义了一些操作model的方法

【再探backbone 01】模型-Model

集合与model息息相关,事实上每个model内部都有一个collection的映射对象,一旦发生映射,那么model变化collection内部也会发生变化,这里的细节我们后面点说

第四步,TodoView

 var TodoView = Backbone.View.extend({

   //... is a list tag.
tagName: "li", // Cache the template function for a single item.
template: _.template($('#item-template').html()), // The DOM events specific to an item.
events: {
"click .toggle": "toggleDone",
"dblclick .view": "edit",
"click a.destroy": "clear",
"keypress .edit": "updateOnEnter",
"blur .edit": "close"
}, // The TodoView listens for changes to its model, re-rendering. Since there's
// a one-to-one correspondence between a **Todo** and a **TodoView** in this
// app, we set a direct reference on the model for convenience.
initialize: function () {
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'destroy', this.remove);
}, // Re-render the titles of the todo item.
render: function () {
this.$el.html(this.template(this.model.toJSON()));
this.$el.toggleClass('done', this.model.get('done'));
this.input = this.$('.edit');
return this;
}, // Toggle the `"done"` state of the model.
toggleDone: function () {
this.model.toggle();
}, // Switch this view into `"editing"` mode, displaying the input field.
edit: function () {
this.$el.addClass("editing");
this.input.focus();
}, // Close the `"editing"` mode, saving changes to the todo.
close: function () {
var value = this.input.val();
if (!value) {
this.clear();
} else {
this.model.save({ title: value });
this.$el.removeClass("editing");
}
}, // If you hit `enter`, we're through editing the item.
updateOnEnter: function (e) {
if (e.keyCode == 13) this.close();
}, // Remove the item, destroy the model.
clear: function () {
this.model.destroy();
} });

熟悉backbone的朋友一定对这段代码尤其熟悉(因为我们只用到了view,model与control全部自己写的,所以我最熟悉的就是这个......)

上面的代码会形成一个view,view实例化时会执行initialize中的方法,需要显示则需要执行render方法(重写)

render结束后页面的交互全部放到了events里面,各位既然用到了backbone,就不要自己随意以on的形式绑定事件了

在view可以为el指定dom结构,新建的view形成的dom就会往里面装

总而言之,View的重点是模板引擎与事件绑定,这里的view不是入口方法,我们看下一个view

第五步,入口AppView

 var AppView = Backbone.View.extend({

   // Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML.
el: $("#todoapp"), // Our template for the line of statistics at the bottom of the app.
statsTemplate: _.template($('#stats-template').html()), // Delegated events for creating new items, and clearing completed ones.
events: {
"keypress #new-todo": "createOnEnter",
"click #clear-completed": "clearCompleted",
"click #toggle-all": "toggleAllComplete"
}, // At initialization we bind to the relevant events on the `Todos`
// collection, when items are added or changed. Kick things off by
// loading any preexisting todos that might be saved in *localStorage*.
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();
}, // Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change.
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;
}, // Add a single todo item to the list by creating a view for it, and
// appending its element to the `<ul>`.
addOne: function (todo) {
var view = new TodoView({ model: todo });
this.$("#todo-list").append(view.render().el);
}, // Add all items in the **Todos** collection at once.
addAll: function () {
Todos.each(this.addOne, this);
}, // If you hit return in the main input field, create new **Todo** model,
// persisting it to *localStorage*.
createOnEnter: function (e) {
if (e.keyCode != 13) return;
if (!this.input.val()) return; Todos.create({ title: this.input.val() });
this.input.val('');
}, // Clear all done todo items, destroying their models.
clearCompleted: function () {
_.invoke(Todos.done(), 'destroy');
return false;
}, toggleAllComplete: function () {
var done = this.allCheckbox.checked;
Todos.each(function (todo) { todo.save({ 'done': done }); });
} });

很遗憾的是,这个代码没有用到路由相关的知识,至此就结束了,因为路由相关的知识是单页应用的一大重点,但是对我们学习来说够了

这里定义了AppView后便实例化了,我们这里来详细读读这个入口函数

① 初始化操作

   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();
},

首先这里做了初始化操作,在这里,我们可以开开心心定义一些后面会用到的dom,这里有一个比较有意思的方法:

this.$();//其实是this.root.find(),这个可以保证你找到正确的元素

在单页应用中,id的唯一性收到了吹残,所以获得元素的方式得到了便会,以上是一种,不明白以上方法的同学喜欢用:

this.$el.find();//$el事实上就是根元素

fetch方法用于初始化集合数据,意思是Todos.fetch();执行结束后,集合就被model给填充了(这里在localstorage中读取了数据)

Todos填充数据后,便会调用本身的render方法将数据以dom形式呈现在我们眼前

 this.listenTo(Todos, 'add', this.addOne);
this.listenTo(Todos, 'reset', this.addAll);
this.listenTo(Todos, 'all', this.render);

这里的的listenTo事实上是一种自定义事件的写法,fetch时候触发了其中的all事件,所以执行了render方法渲染页面

【再探backbone 01】模型-Model

【再探backbone 01】模型-Model

这里页面初始化完成了,当然,一开始我们列表其实是空的

② 增加操作

增加操作简单说一下即可,这里为new-todo(文本框)绑定了keypress事件,事件会触发createOnEnter函数

 createOnEnter: function (e) {
if (e.keyCode != 13) return;
if (!this.input.val()) return; Todos.create({ title: this.input.val() });
this.input.val('');
},

这里愉快的使用集合create方法创建了一个model,当然他触发自己绑定的add事件,于是执行了

 addOne: function (todo) {
var view = new TodoView({ model: todo });
this.$("#todo-list").append(view.render().el);
},

这个操作自然不是省油的灯,他本身也是绑定了change事件的,于是高高兴兴在页面中新增了一条数据:

 initialize: function () {
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'destroy', this.remove);
}, // Re-render the titles of the todo item.
render: function () {
this.$el.html(this.template(this.model.toJSON()));
this.$el.toggleClass('done', this.model.get('done'));
this.input = this.$('.edit');
return this;
},

至此整个逻辑基本结束,其它方面我这里暂时不涉及,这个模式比较好的是,我们就只需要关注model数据变化即可,页面上显示的东西就不管了

PS:说是不管,其实一开始就管完了,只是需要触发事件即可

至此,我们基本例子分析结束,我们下面带着这个例子去学习下backbone的源码,这里又不得不叹息,这里未使用路由(控制器)功能

实现继承-extend

我们无论定义Model还是View时候都是这样干的:

var Todo = Backbone.Model.extend({})
var TodoList = Backbone.Collection.extend({})
var TodoView = Backbone.View.extend({})

其实这个extend着实使人疑惑,因为在underscore学习时候,我们知道他是这样的:

 // 将一个或多个对象的属性(包含原型链中的属性), 复制到obj对象, 如果存在同名属性则覆盖
_.extend = function(obj) {
// each循环参数中的一个或多个对象
each(slice.call(arguments, 1), function(source) {
// 将对象中的全部属性复制或覆盖到obj对象
for(var prop in source) {
obj[prop] = source[prop];
}
});
return obj;
};

这个东西和上述实现差了一大截,于是进入源码一看,事实上我们看到的应该是inherits方法,但是1.0灭掉了inherits方法,只剩下了extend了

 var extend = function(protoProps, staticProps) {
var parent = this;
var child; // The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
} // Add static properties to the constructor function, if supplied.
_.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate; // Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) _.extend(child.prototype, protoProps); // Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype; return child;
}; // Set up inheritance for the model, collection, router, view and history.
Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;

这个家伙又是如何实现继承的,我们这里详细来看看,首先我们将这段代码分离出来:

 var hasOwnProperty = Object.prototype.hasOwnProperty;
var slice = Array.prototype.slice;
var nativeForEach = Array.prototype.forEach;
var _ = {}; var each = _.each = _.forEach = function (obj, iterator, context) {
if (obj == null)
return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker)
return;
}
} else {
for (var key in obj) {
if (_.has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker)
return;
}
}
}
} _.has = function (obj, key) {
return hasOwnProperty.call(obj, key);
}; _.extend = function (obj) {
each(slice.call(arguments, 1), function (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
});
return obj;
}; var extend = function (protoProps, staticProps) {
var parent = this;
var child;
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function () { return parent.apply(this, arguments); };
}
_.extend(child, parent, staticProps);
var Surrogate = function () { this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
if (protoProps) _.extend(child.prototype, protoProps);
child.__super__ = parent.prototype;
return child;
}; var P = function () {
this.a = 1;
this.b = 2;
}; P.prototype.aa = function () {
alert(this.a);
} P.extend = extend; var C = P.extend({
c: 3,
cc: function () {
alert(this.c);
}
}); var s = '';
 var c = new C;
c.cc();//
c.aa();//

【再探backbone 01】模型-Model

backbone实现的继承以最基础的继承,因为他只支持一层的继承,要再多可能这个做法就不好使了,原来inherits其实可以多层继承的......

反正,我们来读一读extend代码

① parent=this

这个代码其实是保留当前函数,比如View或者Model,后面的child会继承他的方法

② protoProps

protoProps实际上是原型方法,如果具有constactor属性,变直接继承之,否则重新定义一个函数,函数初始化(构造函数)时会调用parent的构造函数

PS:而这里parent会执行一些初始化操作,然后调用this.initialize.apply(this, arguments); 所以我们代码中的initialize一定会执行

③ 复制静态属性

然后使用将parent静态属性一一收入成自己的

_.extend(child, parent, staticProps);

④ 经典继承法

 var Surrogate = function () { this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
if (protoProps) _.extend(child.prototype, protoProps);
child.__super__ = parent.prototype;

然后使用此经典的方法实现继承,最终返回给我们child,注意其中的_.extend(child.prototype, protoProps);我们增加的属性全部给加到了原型链上了

至此,backbone的基本继承,我们阅读完毕,现在看到以下代码要清除发生了什么事才行

var TodoView = Backbone.View.extend({})

下面我们来看看backbone的事件机制

事件机制-Events

backbone事件一块就只放出了三个接口:bind、unbind、trigger

Events 是一个可以被mix到任意对象的模块,它拥有让对象绑定和触发自定义事件的能力。

事件在被绑定之前是不需要事先声明的,还可以携带参数。我们通过一个例子来看:

var object = {};
_.extend(object, Backbone.Events); object.bind("alert", function(msg) {
alert("Triggered " + msg);
}); object.trigger("alert", "www.csser.com");

bind用于注册事件,unbind注销事件,trigger触发事件,但是内部的事件一块远不止如此

PS:老夫突然发现我看的中文api是0.5.3的版本!!!fuck me!!! 1.1放出了这么多的接口,额......

【再探backbone 01】模型-Model

首先我们来看一看他Events的源码:

 var Events = Backbone.Events = {

   // Bind an event to a `callback` function. Passing `"all"` will bind
// the callback to all events fired.
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({callback: callback, context: context, ctx: context || this});
return this;
}, // Bind an event to only be triggered a single time. After the first time
// the callback is invoked, it will be removed.
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
var self = this;
var once = _.once(function() {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
}, // Remove one or many callbacks. If `context` is null, removes all
// callbacks with that function. If `callback` is null, removes all
// callbacks for the event. If `name` is null, removes all bound
// callbacks for all events.
off: function(name, callback, context) {
var retain, ev, events, names, i, l, j, k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
if (!name && !callback && !context) {
this._events = {};
return this;
} names = name ? [name] : _.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
if (events = this._events[name]) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
(context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length) delete this._events[name];
}
} return this;
}, // Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).
trigger: function(name) {
if (!this._events) return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args)) return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events) triggerEvents(events, args);
if (allEvents) triggerEvents(allEvents, arguments);
return this;
}, // Tell this object to stop listening to either specific events ... or
// to every object it's currently listening to.
stopListening: function(obj, name, callback) {
var listeners = this._listeners;
if (!listeners) return this;
var deleteListener = !name && !callback;
if (typeof name === 'object') callback = this;
if (obj) (listeners = {})[obj._listenerId] = obj;
for (var id in listeners) {
listeners[id].off(name, callback, this);
if (deleteListener) delete this._listeners[id];
}
return this;
} };

这里统一使用了eventApi这个函数:

 // Regular expression used to split event strings.
var eventSplitter = /\s+/; // Implement fancy features of the Events API such as multiple event
// names `"change blur"` and jQuery-style event maps `{change: action}`
// in terms of the existing API.
var eventsApi = function(obj, action, name, rest) {
if (!name) return true; // Handle event maps.
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
} // Handle space separated event names.
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0, l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
} return true;
};

① 第一个参数为一个对象,其实指向的是调用者,因为Events对象都是被作为 继承/扩展 者使用

② 第二个参数为你的具体操作(on/off/trigger)

③ name可算是这个对象注册的这个事件的唯一标识了,注册事件后后面会用他来读取

④ 最后是传入的回调函数,并且带有作用域

而上述调用点又在其它地方,我们这里将上述代码连起来:

① 首先一个对象继承了Events对象

var obj = {};
_.extend(obj, Backbone.Events)

【再探backbone 01】模型-Model

② 其次我们为他注册一个alert事件

obj.on('alert', function (msg) {
alert(msg);
});

此时会调用由Events继承而来的方法on,并且传入两个参数:alert与回调函数,而后会调用eventApi(私有方法)处理这个event对象

PS:此处传入的那么不是对象也没有任何复杂应用所以直接返回true了,像那么包含“:”,或者包含空格就会做特殊处理,我们这里暂时不管

③ 定义对象的events属性,该属性用于存储该对象保存的所有事件

 on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({callback: callback, context: context, ctx: context || this});
return this;
},

处理结束后,这里便会多出一个对象了:

【再探backbone 01】模型-Model

③ 触发事件,触发事件相对比较简单,可以选择传入参数

obj.trigger("alert", "an event");

触发事件,当然是调用的trigger方法:

 trigger: function(name) {
if (!this._events) return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args)) return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events) triggerEvents(events, args);
if (allEvents) triggerEvents(allEvents, arguments);
return this;
},

这里会通过name在events属性中获取当前对象,调用triggerEvents局部函数调用之,这里有两点需要注意:

1 这里的args是除,name以外传入的参数
2 这里会触发name为all的事件,无论如何都会触发,各位这里要回想起来前面集合的listenerTo方法哦
 var triggerEvents = function(events, args) {
var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
switch (args.length) {
case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
}
};

然后这里做了下简单的处理,高高兴兴将我们定义的事件执行了,于是backbone事件机制的第一段讲解也结束了,较详细的讲解后面点再来

在此我们可以看到,backbone内部的事件机制,其实与javascript事件绑定那块没什么联系,只不过是自己内部的实现而已,这里最后补充一点:

 var listenMethods = { listenTo: 'on', listenToOnce: 'once' };

 // Inversion-of-control versions of `on` and `once`. Tell *this* object to
// listen to an event in another object ... keeping track of what it's
// listening to.
_.each(listenMethods, function (implementation, method) {
Events[method] = function (obj, name, callback) {
var listeners = this._listeners || (this._listeners = {});
var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
listeners[id] = obj;
if (typeof name === 'object') callback = this;
obj[implementation](name, callback, this);
return this;
};
});

页面上调用的listenTo其实就是on方法

模型-Model

构造函数

Model在服务器端来说很是关键,记得前几年老夫还在搞.net最先干的事情就是建造实体,不知道现在怎么样了......

首先看看其继承源码:

 var Model = Backbone.Model = function (attributes, options) {
var defaults;
var attrs = attributes || {};
options || (options = {});
this.cid = _.uniqueId('c');
this.attributes = {};
_.extend(this, _.pick(options, modelOptions));
if (options.parse) attrs = this.parse(attrs, options) || {};
if (defaults = _.result(this, 'defaults')) {
attrs = _.defaults({}, attrs, defaults);
}
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
};

构造函数中本身没有干太多事情:

① 首先为该model定义了唯一的cid(其中的uniqueId方法内部维护着一个id,这个闭包知识点,各位自己去看吧)

② 初始化model默认的属性,比如collection就是必须拥有的,如果定义了的话就直接搞给对象

③ parse是为了兼容不是json数据时候需要做的处理,我们这里直接忽略不要json的场景

④ 获取defaults对象(如果是函数需要返回对象)

⑤ 调用原型链中的set方法,将默认的属性搞到对象中去,set干的事情比较多,我们后面点说

反正他产生的结果就是对象默认会多一些属性值

然后开始调用underscore的exentd扩展对象的原型链了(尼玛,backbone确实强依赖underscore啊,压根搞不掉)

扩展原型链

下面开始扩展Model原型链了,其实这样读下来,backbone的代码是很有调理的,很好读,我们这里捡几个重要的说(我不知道哪个重要只能挑我知道的)

① changed

changed属性记录了每次调用set方法时, 被改变数据的key集合

② validationError

set model 时候会执行validate方法,如果验证失败便会将结果返回该变量

③ idAttribute

每个模型的唯一标识属性(默认为"id", 通过修改idAttribute可自定义id属性名)

如果在设置数据时包含了id属性, 则id将会覆盖模型的id,id用于在Collection集合中查找和标识模型, 与后台接口通信时也会以id作为一条记录的标识

var Meal = Backbone.Model.extend({
idAttribute: "_id"
}); var cake = new Meal({ _id: 1, name: "Cake" });
alert("Cake id: " + cake.id);

这里就将标识符搞到了_id属性上,但是一般不建议这么干,真心不太好......

④ initialize

这个方法比较关键,本身没有意义,用于子对象复写,会在实例化时候执行

⑤ get

返回相关属性的值

set(key, value, options)

这个方法很关键,我们这里来详细说下

 set: function (key, val, options) {
var attr, attrs, unset, changes, silent, changing, prev, current;
if (key == null) return this; // Handle both `"key", value` and `{key: value}` -style arguments.
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
} options || (options = {}); // Run validation.
if (!this._validate(attrs, options)) return false; // Extract attributes and options.
unset = options.unset;
silent = options.silent;
changes = [];
changing = this._changing;
this._changing = true; if (!changing) {
this._previousAttributes = _.clone(this.attributes);
this.changed = {};
}
current = this.attributes, prev = this._previousAttributes; // Check for changes of `id`.
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; // For each `set` attribute, update or delete the current value.
for (attr in attrs) {
val = attrs[attr];
if (!_.isEqual(current[attr], val)) changes.push(attr);
if (!_.isEqual(prev[attr], val)) {
this.changed[attr] = val;
} else {
delete this.changed[attr];
}
unset ? delete current[attr] : current[attr] = val;
} // Trigger all relevant attribute changes.
if (!silent) {
if (changes.length) this._pending = true;
for (var i = 0, l = changes.length; i < l; i++) {
this.trigger('change:' + changes[i], this, current[changes[i]], options);
}
} // You might be wondering why there's a `while` loop here. Changes can
// be recursively nested within `"change"` events.
if (changing) return this;
if (!silent) {
while (this._pending) {
this._pending = false;
this.trigger('change', this, options);
}
}
this._pending = false;
this._changing = false;
return this;
},
model.set(attributes, [options]) 

这里第一个参数可以为对象或者字符串,最简单的情况当然是:

var m = new Model();
m.set('name', '叶小钗');

这样会开开心心执行个对象就结束,当然也可以这样:

m.set({'name': '叶小钗'});

于是,第二个参数的意义就不大了......

{silent: true}的情况下不会触发change事件

1 首先,做了简单的参数检查,将对象放入了attrs变量

2 其次,执行了一次验证操作,如果验证不成立,这里会直接退出去

3 然后,操作传入的options(必须是对象)

这里我有点不太理解:

如果options设置了unset属性,则将attrs的所有值设置为undefined

如果options没有指定silent属性, 则直接设置changes属性中当前数据为已改变状态

4 进行操作前_previousAttributes会保存改变前的属性值,这里有个changing值得注意,他用于检测一次set触发时执行才change方法是否结束,没有结束的话便不能执行

5 遍历时候如果要设置的属性与当前值不等,则将该key值压入changes数组,如果与之前的不等,则在changed对象中赋值(changed记录了每次set时候改变的键值)

如果被相等的话,就将他移除changed对象,如果设置了unset属性,则需要删除当前属性否则就赋值

PS:尼玛,这里在干什么,我没搞明白,先放放吧

6 下面如果没有设置silent,的话会将上面设置的changes中的数据提出来,并触发相关事件(比如触发changename事件,但是我们并未定义)

然后触发整个model的change事件,这个我们应该会绑定,最后做一点结尾处理就跳出来了,我的结论就我没太看懂......后面再看看吧

⑦ unset

删除属性

return this.set(attr, void 0, _.extend({}, options, { unset: true }));

看着unset,我突然好像知道set下面干了写什么事情了......原来他删除与添加都写到了一起了

⑧  fetch

据说是由服务器端获取数据,然后使用set方法初始化model数据,

 fetch: function (options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function (resp) {
if (!model.set(model.parse(resp, options), options)) return false;
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
从服务器重置模型状态。这对模型尚未填充数据,或者服务器端已有最新状态的情况很有用处。 如果服务器端状态与当前属性不同,则触发 "change" 事件。 
选项的散列表参数接受 success 和 error 回调函数, 回调函数中可以传入 (model,response) 作为参数。

这里具体使用了sync事件由服务器端获取数据,这个sync实际上封装了ajax操作,会使用model设置的url,键值为id,所以此处我们就不关注了

⑨ _validate

 _validate: function (attrs, options) {
if (!options.validate || !this.validate) return true;
attrs = _.extend({}, this.attributes, attrs);
var error = this.validationError = this.validate(attrs, options) || null;
if (!error) return true;
this.trigger('invalid', this, error, _.extend(options || {}, { validationError: error }));
return false;
}

用于验证属性的函数,如果为属性定义了validate验证方法,这里就会被调用,如果调用失败还会触发一个事件,Model一块我们暂时就结束了,详细的下面点分析

PS:肚子有点饿,战斗力不行了

结语

下次我们继续学习集合