Created
November 18, 2013 21:27
-
-
Save brandon-lockaby/7535618 to your computer and use it in GitHub Desktop.
Let's make a new EventEmitter
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
var EventEmitter = function() { | |
this._events = {}; | |
}; | |
EventEmitter.prototype.on = function(evtn, fn) { | |
if(!this._events.hasOwnProperty(evtn)) this._events[evtn] = []; | |
this._events[evtn].push(fn); | |
}; | |
EventEmitter.prototype.off = function(evtn, fn) { | |
if(!this._events.hasOwnProperty(evtn)) return; | |
var idx = this._events[evtn].indexOf(fn); | |
if(idx < 0) return; | |
this._events.splice(idx, 1); | |
}; | |
EventEmitter.prototype.emit = function(evtn) { | |
if(!this._events.hasOwnProperty(evtn)) return; | |
var fns = this._events[evtn].slice(0); | |
if(fns.length < 1) return; | |
var args = Array.prototype.slice.call(arguments, 1); | |
for(var i = 0; i < fns.length; i++) fns[i].apply(this, args); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment