Last active
May 22, 2018 16:52
-
-
Save mayashavin/fcba63f80ec82731f41aa150fcbb8d88 to your computer and use it in GitHub Desktop.
Write Emitter Class
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
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); | |
} | |
} | |
} | |
} |
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
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