Skip to content

Instantly share code, notes, and snippets.

@mayashavin
Last active May 22, 2018 16:52
Show Gist options
  • Save mayashavin/fcba63f80ec82731f41aa150fcbb8d88 to your computer and use it in GitHub Desktop.
Save mayashavin/fcba63f80ec82731f41aa150fcbb8d88 to your computer and use it in GitHub Desktop.
Write Emitter Class
class Emitter{
constructor(){
this.events = new Map();
}
subscribe(event, callback){
if (!event || !callback || !(callback instanceof Function)) return;
let index = 0, events = this.events;
if (events.has(event)){
let callbacks = events.get(event);
index = callbacks.push(callback) - 1;
}
else{
events.set(event, [callback]);
}
return {
release(){
let callbacks = events.get(event), status = false;
if (callbacks){
callbacks.splice(index, 1);
status = !status;
}
return status;
}
}
}
emit(event, ...params){
let hasEvent = this.events.has(event);
if (!hasEvent) return new Error(`Event ${event} is not subscribed`);
let callbacks = this.events.get(event);
if (callbacks.length > 0){
for(let i = 0; i < callbacks.length; i++){
(function(callback, params){
setTimeout(function(){
callback.call(this, ...params);
});
})(callbacks[i], params);
}
}
}
}
let EmitterTest = {
run(){
let emitter = new Emitter(),
subscriber1 = emitter.subscribe('showName', function(name){console.log(name);}),
subscriber2 = emitter.subscribe('showName', function(name, id){console.log(`${name} ${id}`);}),
subscriber3 = emitter.subscribe('showName', function(name, id, gender){console.log(`${name} ${id} - gender: ${3}`);});
emitter.emit('showName', "Maya", "32", "female");
let subscriber4 = emitter.subscribe('showNameWithHE', function(name){console.log(name + 'he');});
emitter.emit('showNameWithHE', "Maya", "32", "female");
subscriber4.release();
emitter.emit('showName', "Natan", "30", "male");
emitter.emit('showNameWithHE', "Maya", "32", "female");
}
}
EmitterTest.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment