Last active
August 29, 2015 14:14
-
-
Save kevincennis/98b0451ed0631db2f472 to your computer and use it in GitHub Desktop.
EventEmitter
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 EventEmitter = (function() { | |
var cache = new WeakMap(); | |
function EventEmitter() { | |
cache.set( this, {} ); | |
} | |
EventEmitter.prototype = { | |
on: function( evt, fn ) { | |
var hash = cache.get( this ); | |
( hash[ evt ] || ( hash[ evt ] = [] ) ).push( fn ); | |
return this; | |
}, | |
emit: function( evt ) { | |
var args = Array.prototype.slice.call( arguments, 1 ), | |
events = cache.get( this )[ evt ], | |
len, i; | |
if ( events ) { | |
for ( i = 0, len = events.length; i < len; ++i ) { | |
events[ i ].apply( this, args ); | |
} | |
} | |
return this; | |
}, | |
off: function( evt, fn ) { | |
var hash = cache.get( this ), | |
events = hash[ evt ], | |
keep, len, i; | |
if ( !evt ) { | |
cache.set( this, {} ); | |
} | |
else if ( events && !fn ) { | |
delete hash[ evt ]; | |
} | |
else if ( events ) { | |
keep = []; | |
for ( i = 0, len = events.length; i < len; ++i ) { | |
if ( events[ i ] !== fn ) { | |
keep.push( events[ i ] ); | |
} | |
} | |
hash[ evt ] = keep; | |
} | |
return this; | |
} | |
}; | |
return EventEmitter; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment