我在我的 Javascript 代码中使用了这个基本的事件系统,并试图为我的同事记录它。我不太确定这段代码中的“范围”和“上下文”有什么区别。谁能帮我理解为什么我什至都需要它们?
this.myClass.prototype.on = function (type, method, scope, context) {
var listeners, handlers, scope;
if ( !(listeners = this.listeners) ) {
listeners = this.listeners = {};
}
if ( !(handlers = listeners[type]) ) {
handlers = listeners[type] = [];
}
scope = (scope ? scope : window);
handlers.push({
method: method,
scope: scope,
context: (context ? context : scope)
});
}
this.myClass.prototype.trigger = function(type, data, context) {
var listeners, handlers, i, n, handler, scope;
if (!(listeners = this.listeners)) {
return;
}
if (!(handlers = listeners[type])){
return;
}
for (i = 0, n = handlers.length; i < n; i++){
handler = handlers[i];
if (context && context !== handler.context) continue;
if (handler.method.call(
handler.scope, this, type, data
)===false) {
return false;
}
}
return true;
}