Last active
August 29, 2015 14:14
-
-
Save appkr/8da5d01fc61b9883975b to your computer and use it in GitHub Desktop.
JavaScript Event Target// source http://jsbin.com/kipame
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
var EventTarget = function() { | |
Object.defineProperty(this, "__listeners", { | |
value: {} | |
}); | |
}; | |
Object.defineProperties(EventTarget.prototype, { | |
addListener: { | |
value: function(type, listener) { | |
if (typeof this.__listeners[type] === "undefined") { | |
this.__listeners[type] = []; | |
} | |
this.__listeners[type].push(listener); | |
}, | |
enumerable: true | |
}, | |
__fire: { | |
value: function(evtObj) { | |
if (typeof evtObj.type === "undefined") { | |
throw new Error("Event object needs type"); | |
} | |
if (typeof evtObj.target === "undefined") { | |
evtObj.target = this; | |
} | |
var listeners = this.__listeners[evtObj.type]; | |
if (typeof listeners === "undefined") { | |
return; | |
} | |
for (var i = 0, len = listeners.length; i < len; i++) { | |
listeners[i].call(this, evtObj); | |
} | |
} | |
}, | |
removeListener: { | |
value: function(type, listener) { | |
var listeners = this.__listeners[type]; | |
if (typeof listeners == "undefined") { | |
return; | |
} | |
for (var i = 0, len = listeners.length; i < len; i++) { | |
if (listeners[i] === listener) { | |
listeners.splice(i, 1); | |
break; | |
} | |
} | |
}, | |
enumerable: true | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment