Last active
September 11, 2017 12:48
-
-
Save rwaldron/5119592 to your computer and use it in GitHub Desktop.
Simple Event Emitter constructor that uses a WeakMap for event storage (keywords: event emitter weakmap) ps. github's gist search is bullshit
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
(function( exports ) { | |
var priv = new WeakMap(); | |
function Emitter() { | |
priv.set(this, { | |
events: {} | |
}); | |
} | |
Emitter.prototype.on = function( type, handler ) { | |
var events = priv.get(this).events; | |
if ( !events[ type ] ) { | |
events[ type ] = []; | |
} | |
events[ type ].push( handler ); | |
return this; | |
}; | |
Emitter.prototype.off = function( type, handler ) { | |
var events = priv.get(this).events[ type ]; | |
if ( events ) { | |
if ( !handler ) { | |
events.length = 0; | |
} else { | |
events.splice( events.indexOf(handler), 1 ); | |
} | |
} | |
return this; | |
} | |
Emitter.prototype.emit = function( type, data ) { | |
var event, events; | |
events = (priv.get(this).events[ type ] || []).slice(); | |
if ( events.length ) { | |
while ( event = events.shift() ) { | |
event.call( this, data ); | |
} | |
} | |
return this; | |
} | |
exports.Emitter = Emitter; | |
}(this)); | |
function Serial( path ) { | |
this.path = path; | |
} | |
function Device( path ) { | |
Emitter.call( this ); | |
this.serial = new Serial( path ); | |
} | |
Device.prototype = Object.create( Emitter.prototype ); | |
function handler( data ) { | |
console.log( "signal", data ); | |
} | |
var device = new Device(); | |
device.on( "signal", handler ); | |
device.on( "signal", function() { console.log( 1 ); }); | |
device.on( "signal", function() { console.log( 2 ); }); | |
device.on( "signal", function() { console.log( 3 ); }); | |
// Will trigger 4 events. | |
device.emit( "signal", { a: "alpha", b: "beta" }); | |
device.off( "signal", handler ); | |
// Will trigger 3 events. | |
device.emit( "signal", { a: "alpha", b: "beta" }); | |
console.log( device ); | |
// Device { | |
// serial: Serial { path = ... } | |
// } | |
// Note that the "device" instance does not have any data | |
// properties that were inherited by Emitter--only the inherited | |
// API from Emitter.prototype and it's own properties |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
very much influenced by this idea of a clean event emitter, I rewrote it as an npm module weakee. I just added "once" method. Thanks @rwaldron for sharing this!