Skip to content

Instantly share code, notes, and snippets.

@tony-0tis
Last active June 24, 2024 10:01
Show Gist options
  • Save tony-0tis/a965f9de8dcbb9894a914105e0ab2a58 to your computer and use it in GitHub Desktop.
Save tony-0tis/a965f9de8dcbb9894a914105e0ab2a58 to your computer and use it in GitHub Desktop.
Simple es6 eventEmitter

0tis-eventemitter

Simple es6 eventEmitter

Install

npm i -S gist:a965f9de8dcbb9894a914105e0ab2a58

How to use

import EventEmitter from '0tis-eventemitter';
class MyClass extends EventEmitter{
  constructor(){
    setInterval(this.init, 1);
  }
  init(){
    this.emit('init', 'My class initiated');
  }
}
const myClass = new MyClass();
myClass.on('init', msg=>console.log(msg));
class EventsEmitter {
constructor(){
this.events = {};
}
on(name, callback, context, once = false){
if(name == null) throw new Error('No first argument passed');
if(callback == null) throw new Error('No second argument passed');
if(typeof callback !== 'function') throw new Error('Second argument must be a function');
if(typeof context === 'boolean' && context === true && once === false){
[once, context] = [context, null];
}
this.events[name] = [...(this.events[name] || []), {callback, context, once}];
}
off(name, callback){
if(name == null) throw new Error('No first argument passed');
if(!this.events[name]) return;
if(callback){
if(callback == null) throw new Error('No second argument passed');
if(typeof callback !== 'function') throw new Error('Second argument must be a function');
this.events[name] = this.events[name].filter(event=>event.callback != callback);
}
else{
delete this.events[name];
}
}
emit(name, ...args){
if(name == null) throw new Error('No first argument passed');
(this.events[name] || []).forEach(event=>{
try{
event.callback.call(event.context, ...args);
if(event.once){
this.off(name, event.callback);
}
}
catch(e){
throw e;
}
});
}
//aliases
once(name, callback, context){
this.on(name, callback, context, true);
}
subscribe(name, callback, context){
this.on(name, callback, context);
}
unsubscribe(name, callback){
this.off(name, callback);
}
addListener(name, listener, context){
this.on(name, listener, context);
}
removeListener(name, listener){
this.off(name, listener);
}
removeListeners(name){
this.off(name);
}
dispatchEvent(name, ...args){
this.emit(name, ...args);
}
}
export default EventEmitter;
{
"version": "0.1.0",
"name": "0tis-eventemitter",
"main": "EventEmitter.mjs"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment