Last active
August 29, 2015 13:57
-
-
Save mingzhi22/9578615 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//Copyright (c) 2010 Nicholas C. Zakas. All rights reserved. | |
//MIT License | |
function EventTarget(){ | |
this._listeners = {}; | |
} | |
EventTarget.prototype = { | |
constructor: EventTarget, | |
addListener: function(type, listener){ | |
if (typeof this._listeners[type] == "undefined"){ | |
this._listeners[type] = []; | |
} | |
this._listeners[type].push(listener); | |
}, | |
fire: function(event){ | |
if (typeof event == "string"){ | |
event = { type: event }; | |
} | |
if (!event.target){ | |
event.target = this; | |
} | |
if (!event.type){ //falsy | |
throw new Error("Event object missing 'type' property."); | |
} | |
if (this._listeners[event.type] instanceof Array){ | |
var listeners = this._listeners[event.type]; | |
for (var i=0, len=listeners.length; i < len; i++){ | |
listeners[i].call(this, event); | |
} | |
} | |
}, | |
removeListener: function(type, listener){ | |
if (this._listeners[type] instanceof Array){ | |
var listeners = this._listeners[type]; | |
for (var i=0, len=listeners.length; i < len; i++){ | |
if (listeners[i] === listener){ | |
listeners.splice(i, 1); | |
break; | |
} | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment