Last active
July 19, 2019 04:46
-
-
Save ArjanJ/9cfd316f7659bd53b49ee9d24975508f to your computer and use it in GitHub Desktop.
Event Emitter Class 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
/* | |
* Create an event emitter that goes like this | |
* emitter = new Emitter(); | |
* | |
* Allows you to subscribe to some event | |
* sub1 = emitter.subscribe('function_name', callback1); | |
* (you can have multiple callbacks to the same event) | |
* sub2 = emitter.subscribe('function_name', callback2); | |
* | |
* You can emit the event you want with this api | |
* (you can receive 'n' number of arguments) | |
* sub1.emit('function_name', foo, bar); | |
* | |
* And allows you to release the subscription like this | |
* (but you should be able to still emit from sub2) | |
* sub1.release(); | |
*/ | |
class Emitter { | |
// Keeps track of subscriptions as <name: string, callbacks: []>. | |
subscriptions = new Map(); | |
constuctor() {} | |
/** | |
* Creates a new subscription or adds the callback to an | |
* existing subscription. | |
*/ | |
subscribe = (functionName, callback) => { | |
const subscription = this.subscriptions.get(functionName); | |
if (subscription) { | |
subscription.push(callback); | |
} else { | |
subscriptions.set(functionName, [callback]); | |
} | |
return this; | |
}; | |
/** | |
* When subscription.emit() is called, all of the callbacks | |
* are executed for that subscription. | |
*/ | |
emit = (functionName, ...rest) => { | |
const subscription = this.subscriptions.get(functionName); | |
if (subscription) { | |
subscription.forEach(cb => cb(...rest)); | |
} | |
}; | |
/** | |
* subscription.release() removes the callback for | |
* that event and updates the subscription. | |
*/ | |
release = (functionName, callback) => { | |
const subscription = this.subscriptions.get(functionName); | |
if (subscription) { | |
const updatedSubscription = subscription.filter(cb => cb !== callback); | |
subscriptions.set(functionName, updatedSubscription); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment