标签:
nodejs有eventEmitter 类,想到backbone 有个event模块 可以对对象做事件绑定和触发,是backbone的核心模块。
backbone event模块
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; },
在当前的bancbone.event 的实例上添加_events 属性,所有通过backbone.events 订阅的时间 都在这个属性上查到。
_events={ name:[{callback:function(){}, context: Object, ctx: Object}], name:[{callback:function(){}, context: Object, ctx: Object}] }
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; }
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); return; } };
标签:
原文地址:http://www.cnblogs.com/breakdown/p/4281354.html