Last active
April 17, 2018 07:05
-
-
Save aymanalzarrad/91726e64402b4f543f6eaa3968c8f62f to your computer and use it in GitHub Desktop.
Simple events emitter in JavaScript
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
export default class EventsEmitter{ | |
constructor(){ | |
this._events = {}; | |
} | |
on(event, callback, once){ | |
if( !(this._events[event] instanceof Array) ){ | |
this._events[event] = []; | |
} | |
this._addListener(event, { | |
once: Boolean(once), | |
callback: callback | |
}); | |
return this; | |
} | |
off(event, callback, once){ | |
if( !this._events[event] ){ | |
return null; | |
} | |
once = Boolean(once); | |
for(let index = 0; index < this._events[event].length; index++){ | |
if( (this._events[event][index].once === once) && (this._events[event][index].callback.toString() === callback.toString()) ){ | |
this._removeListener(event, index); | |
return true; | |
} | |
} | |
return false; | |
} | |
once(event, callback){ | |
return this.on(event, callback, true); | |
} | |
emit(event, ...params){ | |
if( !this._events[event] ){ | |
return; | |
} | |
for( let index = 0; index < this._events[event].length; index++ ){ | |
let listener = this._events[event][index]; | |
if( !listener ){ | |
continue; | |
} | |
if( typeof listener.callback === 'function' ){ | |
listener.callback(...params); | |
} | |
if( listener.once ){ | |
this._removeListener(event, index); | |
} | |
} | |
this._events[event] = this._events[event].filter((listener) => { | |
return listener !== null; | |
}) | |
} | |
_addListener(event, listener){ | |
this._events[event].push(listener); | |
} | |
_removeListener(event, index){ | |
return this._events[event][index] = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment