Backbone.js 是前端 MV* 框架的先驱之一。它极其克制——不提供双向绑定,不接管 DOM,只给你 Model、Collection、View、Router 四块积木,剩下的自由发挥。正因如此,读它的源码收益很高:代码量不大,却把数据模型、事件系统、路由分发、服务端同步这几件事讲得清清楚楚。
下面以 0.9.2 版本为例,按文件顺序梳理它的整体结构与关键实现。
整个库包裹在一个立即执行函数里,通过 .call(this) 把外层 this 传进来:
// Backbone.js 0.9.2
// (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc.
// Backbone may be freely distributed under the MIT license.
// https://backbonejs.org
(function() {
// 创建一个全局对象:浏览器中是 window,Node.js 中是 global
var root = this;
// 保存 Backbone 被覆盖之前的值,供 noConflict 恢复
var previousBackbone = root.Backbone;
// 把 Array.prototype 的 slice / splice 缓存为局部变量,避免每次查找原型链
var slice = Array.prototype.slice;
var splice = Array.prototype.splice;
var Backbone;
if (typeof exports !== 'undefined') {
Backbone = exports; // CommonJS 环境直接挂到 exports
} else {
Backbone = root.Backbone = {}; // 浏览器环境挂到全局
}
Backbone.VERSION = '0.9.2';
// Underscore 是硬依赖:服务端用 require 导入,浏览器端取全局
var _ = root._;
if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
// DOM 库:jQuery / Zepto / ender 任选其一,语法保持一致
// 定义为局部变量,因此不会污染框架外部的同名库
var $ = root.jQuery || root.Zepto || root.ender;
// 允许在 Backbone 加载之后再手动指定 DOM 库
Backbone.setDomLibrary = function(lib) { $ = lib; };
// 让出 Backbone 全局名,返回对象本身以便改名使用
Backbone.noConflict = function() {
root.Backbone = previousBackbone;
return this;
};
// 兼容不支持 REST 的服务端:以 POST 发送,附带 _method 参数
Backbone.emulateHTTP = false;
// 兼容不支持 application/json 的服务端:改为表单编码,数据放进 model 参数
Backbone.emulateJSON = false;
}).call(this);
几个值得学习的设计细节:
slice / splice 被提到闭包顶部缓存,后续大量用于把 arguments 转成真数组,属于典型的性能与可读性折中。$ 定义成局部变量而不是直接用全局 jQuery,既支持 Zepto 这类 API 兼容的替代品,也避免和页面上的其他库冲突。noConflict 的模式和 jQuery 如出一辙:先存旧值,再按需归还。Backbone 的所有模块都 mixin 了 Events,因此 Model、View、Router 天生就能派发和监听自定义事件。它的实现有一个很有意思的选择:回调列表不用数组,而是用带 next 指针的链表。
var eventSplitter = /\s+/;
var Events = Backbone.Events = {
// 绑定事件:events 允许用空白字符分隔多个事件名
// callback 必填;context 决定回调中的 this
on: function(events, callback, context) {
var calls, event, node, tail, list;
if (!callback) return this;
events = events.split(eventSplitter);
calls = this._callbacks || (this._callbacks = {});
while (event = events.shift()) {
// list 指向该事件的回调链表,tail 指向链尾哨兵
list = calls[event];
// 复用旧链尾节点,再创建新的链尾哨兵
node = list ? list.tail : {};
node.next = tail = {};
node.context = context;
node.callback = callback;
// 头插,使链表顺序与绑定顺序一致
calls[event] = { tail: tail, next: list ? list.next : node };
}
return this;
},
用链表而非数组的理由很实际:绑定和解绑在中途插入/删除节点是 O(1) 操作,而数组的 splice 需要搬移元素;同时 tail 哨兵让遍历时判断"是否已到末尾"变得非常直接——node = node.next 直到等于 tail 即止。
off 支持四种粒度的过滤:不传参数清空全部;只传 events 移除指定事件的所有回调;只传 callback 或 context 则跨事件按函数或上下文过滤;三者都传则精确匹配。
off: function(events, callback, context) {
var event, calls, node, tail, cb, ctx;
if (!(calls = this._callbacks)) return;
// 没有任何过滤条件:直接删除整个 _callbacks
if (!(events || callback || context)) {
delete this._callbacks;
return this;
}
events = events ? events.split(eventSplitter) : _.keys(calls);
while (event = events.shift()) {
node = calls[event];
delete calls[event];
if (!node || !(callback || context)) continue; // 整个事件被移除
tail = node.tail;
// 遍历链表,把不符合过滤条件的回调重新绑定回去
while ((node = node.next) !== tail) {
cb = node.callback;
ctx = node.context;
if ((callback && cb !== callback) || (context && ctx !== context)) {
this.on(event, cb, ctx);
}
}
}
return this;
},
trigger 有一个特殊约定:事件名 all 会在任何事件触发时都被调用,回调的第一个参数是实际事件名。这让它成为实现"全局日志""统一埋点"的天然钩子——Backbone 内部也正是靠 all 让 Collection 感知 Model 的变化。
另外,bind / unbind 只是 on / off 的别名,用于兼容早期版本。
构造函数做了四件事:合并默认值、建立索引字段、初始化变更追踪、调用 initialize。
var Model = Backbone.Model = function(attributes, options) {
var defaults;
attributes || (attributes = {});
// 若服务端数据格式与 set 期望不同,可通过 parse 转换
if (options && options.parse) attributes = this.parse(attributes);
if (defaults = getValue(this, 'defaults')) {
// attributes 中的同名键覆盖 defaults
attributes = _.extend({}, defaults, attributes);
}
if (options && options.collection) this.collection = options.collection;
this.attributes = {}; // 真正的数据存放处
this._escapedAttributes = {}; // escape() 的结果缓存
this.cid = _.uniqueId('c'); // 客户端唯一 ID,即使还没有服务端 id
// 变更追踪:changed 记录本轮变化,_silent 暂存 silent 变化,_pending 标记待通知
this.changed = {};
this._silent = {};
this._pending = {};
// 首次赋值使用 silent,避免初始化时触发 change 事件
this.set(attributes, { silent: true });
this.changed = {};
this._silent = {};
this._pending = {};
// 上一状态快照,供 previous / previousAttributes 使用
this._previousAttributes = _.clone(this.attributes);
this.initialize.apply(this, arguments);
};
set 是整个 Model 的核心,它承担了差异比对、事件抑制、id 同步等职责:
set: function(key, value, options) {
var attrs, attr, val;
// 支持 set({a:1}) 与 set('a', 1) 两种调用形式
if (_.isObject(key) || key == null) { attrs = key; options = value; }
else { attrs = {}; attrs[key] = value; }
options || (options = {});
if (!attrs) return this;
if (attrs instanceof Model) attrs = attrs.attributes;
// unset 模式:把值全部置为 undefined,实现"只删除不赋值"
if (options.unset) for (attr in attrs) attrs[attr] = void 0;
if (!this._validate(attrs, options)) return false;
// 自定义了 idAttribute 时,也要保证 this.id 能取到值
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
var changes = options.changes = {};
var now = this.attributes;
var escaped = this._escapedAttributes;
var prev = this._previousAttributes || {};
for (attr in attrs) {
val = attrs[attr];
if (!_.isEqual(now[attr], val) || (options.unset && _.has(now, attr))) {
delete escaped[attr]; // 数据变了,escape 缓存必须失效
// silent 时不触发事件,但要记账,等下次 change 一起通知
(options.silent ? this._silent : changes)[attr] = true;
}
options.unset ? delete now[attr] : now[attr] = val;
if (!_.isEqual(prev[attr], val) || (_.has(now, attr) != _.has(prev, attr))) {
this.changed[attr] = val;
if (!options.silent) this._pending[attr] = true;
} else {
delete this.changed[attr];
delete this._pending[attr];
}
}
if (!options.silent) this.change(options);
return this;
},
change 负责派发两级事件:先逐个触发 change:属性名,再触发统一的 change。它还用 _pending 做了循环处理——监听 change 的回调里如果又改了数据,会再走一轮,直到没有待通知项为止。
与服务器交互的四个方法结构高度一致:fetch(GET)、save(create 用 POST,update 用 PUT)、destroy(DELETE)。它们都遵循同一套模式:
success:先 parse 再 set,若校验失败则不调用用户回调;Backbone.wrapError 统一包装 error:有自定义错误处理就调用,没有就触发 error 事件;(this.sync || Backbone.sync)。save 里的 wait 选项尤其值得体会:设置后,本地数据不会立刻生效,而是先校验、再发请求,服务端确认成功才落定;请求失败则数据保持在修改前的状态。这是一种朴素的乐观锁思路。
Collection 内部维护两份哈希索引——_byId 和 _byCid,让按 id 查找成为 O(1):
add: function(models, options) {
var i, index, length, model, cid, id, cids = {}, ids = {}, dups = [];
options || (options = {});
models = _.isArray(models) ? models.slice() : [models];
// 第一轮:数据对象转模型实例,同时剔除重复项
for (i = 0, length = models.length; i < length; i++) {
if (!(model = models[i] = this._prepareModel(models[i], options))) {
throw new Error("Can't add an invalid model to a collection");
}
cid = model.cid;
id = model.id;
// 在本次入参中重复,或集合中已存在,都记入 dups
if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) {
dups.push(i);
continue;
}
cids[cid] = ids[id] = model;
}
i = dups.length;
while (i--) models.splice(dups[i], 1);
// 第二轮:监听模型的 all 事件,建立索引
for (i = 0, length = models.length; i < length; i++) {
(model = models[i]).on('all', this._onModelEvent, this);
this._byCid[model.cid] = model;
if (model.id != null) this._byId[model.id] = model;
}
this.length += length;
index = options.at != null ? options.at : this.models.length;
splice.apply(this.models, [index, 0].concat(models));
if (this.comparator) this.sort({ silent: true });
if (options.silent) return this;
for (i = 0, length = this.models.length; i < length; i++) {
if (!cids[(model = this.models[i]).cid]) continue;
options.index = i;
model.trigger('add', model, this, options);
}
return this;
},
_onModelEvent 是集合与模型之间的桥梁:模型触发任何事件,集合都会转发同名事件;模型被 destroy 时集合自动移除它;模型的 id 发生变化时,集合同步更新 _byId 索引。
_onModelEvent: function(event, model, collection, options) {
if ((event == 'add' || event == 'remove') && collection != this) return;
if (event == 'destroy') this.remove(model, options);
if (model && event === 'change:' + model.idAttribute) {
delete this._byId[model.previous(model.idAttribute)];
this._byId[model.id] = model;
}
this.trigger.apply(this, arguments);
}
另一个高频技巧出现在文件末尾:Backbone 把 Underscore 的三四十个集合方法批量代理到 Collection 原型上,于是可以直接写 collection.map()、collection.filter():
var methods = ['forEach', 'each', 'map', 'reduce', 'find', 'filter', 'select',
'reject', 'every', 'some', 'include', 'invoke', 'max', 'min',
'sortBy', 'toArray', 'size', 'first', 'rest', 'last',
'without', 'indexOf', 'shuffle', 'isEmpty', 'groupBy' /* ... */];
_.each(methods, function(method) {
Collection.prototype[method] = function() {
// 传入的集合固定为 this.models,其余参数原样透传
return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
};
});
Router 负责把"路由规则"绑定到"方法",History 负责监听 URL 变化并做匹配。Router 的路由声明支持两种动态片段:
var namedParam = /:\w+/g; // 'topic/:id' 匹配 'topic/1228',回调收到 '1228'
var splatParam = /\*\w+/g; // 'topic*id' 匹配任意后缀
var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g;
_routeToRegExp: function(route) {
// 先转义正则元字符,再把 :param 换成捕获组,*param 换成非贪婪捕获组
route = route.replace(escapeRegExp, '\\$&')
.replace(namedParam, '([^/]+)')
.replace(splatParam, '(.*?)');
return new RegExp('^' + route + '$');
},
_extractParameters: function(route, fragment) {
// 'teams/:type/:id' 匹配 'teams/35/1228' 后得到 ['35', '1228']
return route.exec(fragment).slice(1);
}
_bindRoutes 里那段看似多余的"倒序再倒序",其实是为了兼顾两种添加方式:构造函数里通过 options.routes 批量传入的规则要保持声明顺序,而运行时手动调用 route() 添加的规则应该优先匹配(因为 History.route 用 unshift 头插)。
History 是一个单例,首次创建 Router 时自动生成。它的 start() 针对浏览器能力做了三级降级:
popstate:监听 popstate,可用 pushState 做无刷新导航;popstate 但支持 onhashchange:监听 hashchange;setInterval 轮询 URL(默认 50ms)。var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) &&
(!docMode || docMode <= 7));
if (oldIE) {
this.iframe = $('<iframe src="javascript:0" tabindex="-1" />')
.hide().appendTo('body')[0].contentWindow;
this.navigate(fragment);
}
if (this._hasPushState) {
$(window).bind('popstate', this.checkUrl);
} else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
$(window).bind('hashchange', this.checkUrl);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}
start() 还处理了 URL 形式互转的场景:用 pushState 地址访问但浏览器不支持时,自动重写为 hash 形式;反之则用 replaceState 把 hash 地址升级为 pushState 形式。这类细节是很多"看起来简单"的库真正复杂的地方。
View 的设计哲学是"以 el 为边界"。每个视图持有一个根元素 el(以及包装后的 $el),所有查找和事件绑定都被限制在这棵子树内:
var View = Backbone.View = function(options) {
this.cid = _.uniqueId('view');
this._configure(options || {});
this._ensureElement(); // 确定或创建 el
this.initialize.apply(this, arguments);
this.delegateEvents(); // 绑定 events 中声明的事件
};
delegateEvents 用事件委托把声明式配置变成真实监听,并统一加上命名空间便于批量解绑:
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
delegateEvents: function(events) {
if (!(events || (events = getValue(this, 'events')))) return;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
if (!method) throw new Error('Method "' + events[key] + '" does not exist');
var match = key.match(delegateEventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, this); // 保证回调中的 this 指向视图
eventName += '.delegateEvents' + this.cid;
if (selector === '') this.$el.bind(eventName, method);
else this.$el.delegate(selector, eventName, method);
}
}
用 delegate 而非直接绑定,意味着动态插入的子元素也能自动获得事件——这在列表渲染场景里省掉了大量重复绑定代码。命名空间 .delegateEvents + cid 则让 undelegateEvents() 一行搞定所有解绑。
_ensureElement 体现了另一个实用技巧:如果没有传入 el,就用 tagName、id、className、attributes 在内存中创建一个游离元素。视图可以先在内存里完成组装,最后一次性插入文档,减少重排。
所有网络请求都收口到 Backbone.sync,这是 Backbone 最值得学习的架构决策之一——想换协议、换序列化方式,只需要覆盖这一个方法。
var methodMap = {
'create': 'POST',
'update': 'PUT',
'delete': 'DELETE',
'read': 'GET'
};
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
options || (options = {});
var params = { type: type, dataType: 'json' };
if (!options.url) {
params.url = getValue(model, 'url') || urlError();
}
if (!options.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
// 兼容不支持 JSON 编码的老服务端
if (Backbone.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.data = params.data ? { model: params.data } : {};
}
// 兼容不支持 REST 的环境:PUT/DELETE 降级为 POST + _method
if (Backbone.emulateHTTP) {
if (type === 'PUT' || type === 'DELETE') {
if (Backbone.emulateJSON) params.data._method = type;
params.type = 'POST';
params.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
};
}
}
if (params.type !== 'GET' && !Backbone.emulateJSON) {
params.processData = false; // 不转换数据,可能是 JSON 映射
}
return $.ajax(_.extend(params, options));
};
最后那句 _.extend(params, options) 意味着调用方传入的任何 $.ajax 配置都会覆盖默认值——扩展点留得干净利落。
Backbone 没有依赖任何原生 class,而是自己实现了一套 extend:
var ctor = function() {};
var inherits = function(parent, protoProps, staticProps) {
var child;
// protoProps 中若声明了 constructor,则用它作为子类构造函数
if (protoProps && protoProps.hasOwnProperty('constructor')) {
child = protoProps.constructor;
} else {
child = function() { parent.apply(this, arguments); };
}
_.extend(child, parent); // 继承静态属性
ctor.prototype = parent.prototype; // 用空函数切断原型链上的副作用
child.prototype = new ctor(); // 避免执行父类构造函数体
if (protoProps) _.extend(child.prototype, protoProps);
if (staticProps) _.extend(child, staticProps);
child.prototype.constructor = child; // 补回被覆盖的 constructor
child.__super__ = parent.prototype; // 方便调用父类实现
return child;
};
Model.extend = Collection.extend = Router.extend = View.extend = extend;
这里的关键技巧是那个空的 ctor:直接写 child.prototype = new parent() 会执行父类构造函数体,可能带来副作用或参数错误;用一个共享的空函数做中转,就只继承原型而不触发构造逻辑。
另外两个短小但无处不在的工具函数:
// 取属性值,若为函数则执行后返回——让 defaults、url 等既能是值也能是函数
var getValue = function(object, prop) {
if (!(object && object[prop])) return null;
return _.isFunction(object[prop]) ? object[prop]() : object[prop];
};
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
Backbone 0.9.2 不到两千行,却示范了几个至今仍然有效的架构原则:
change 自行更新;Collection 通过 all 感知成员变化。sync,所有 DOM 操作限定在视图的 el 子树内。pushState → hash → iframe 轮询 的三级降级,是那个多浏览器并存年代的务实答案。今天的主流框架已经用响应式数据绑定取代了手动 render(),但 Backbone 留下的这套分层思路——数据、集合、视图、路由各司其职,靠事件通信——依然值得一读再读。