Created
September 23, 2014 05:45
-
-
Save synzhang/efc727ff03fef90f0537 to your computer and use it in GitHub Desktop.
EventTarget
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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