Skip to content

Instantly share code, notes, and snippets.

@aymanalzarrad
Last active April 17, 2018 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aymanalzarrad/91726e64402b4f543f6eaa3968c8f62f to your computer and use it in GitHub Desktop.
Save aymanalzarrad/91726e64402b4f543f6eaa3968c8f62f to your computer and use it in GitHub Desktop.
Simple events emitter in JavaScript
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