Skip to content

Instantly share code, notes, and snippets.

@synzhang
Created September 23, 2014 05:45
Show Gist options
  • Save synzhang/efc727ff03fef90f0537 to your computer and use it in GitHub Desktop.
Save synzhang/efc727ff03fef90f0537 to your computer and use it in GitHub Desktop.
EventTarget
/**
* @desc EventTarget
* @see 《JavaScript高级程序设计(第3版)》 p616
*/
function EventTarget(){
this.handlers = {};
}
EventTarget.prototype = {
constructor: EventTarget,
addHandler: function(type, handler){
if (typeof this.handlers[type] == "undefined"){
this.handlers[type] = [];
}
this.handlers[type].push(handler);
},
fire: function(event){
if (!event.target){
event.target = this;
}
if (this.handlers[event.type] instanceof Array){
var handlers = this.handlers[event.type];
for (var i=0, len=handlers.length; i < len; i++){
handlers[i](event);
}
}
},
removeHandler: function(type, handler){
if (this.handlers[type] instanceof Array){
var handlers = this.handlers[type];
for (var i=0, len=handlers.length; i < len; i++){
if (handlers[i] === handler){
break;
}
}
handlers.splice(i, 1);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment