Last active
August 11, 2022 16:35
-
-
Save mayashavin/a8d4184ace17b6f146480a83f88bfbea to your computer and use it in GitHub Desktop.
Emitter Class Implementation
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
function Emitter(){ | |
var events = new Map(); | |
return { | |
subscribe: function(event_name, callback){ | |
//If events has event_name, then get the event Subscription and push to it. | |
//Else create new event, subscription and add to events. | |
var isEventExisted = events.has(event_name), index = 0; | |
if (isEventExisted){ | |
var subscriptions = events.get(event_name); | |
index = subscriptions.push(callback) - 1; | |
} | |
else{ | |
events.add(event_name, [callback]); | |
} | |
//Return an object with reference to this | |
return { | |
release: function(){ | |
var status = true; | |
if (index > -1){ | |
var subscriptions = events.get(event_name); | |
if (subscriptions){ | |
subscriptions.splice(index, 1); | |
} | |
return status; | |
} | |
return !status; | |
} | |
}; | |
}, | |
emit: function(event_name, ...params){ | |
var isExisted = events.has(event_name); | |
if (isExisted){ | |
var subscriptions = events.get(event_name); | |
if (subscriptions){ | |
for(var i = 0; i < subscriptions.length; i++){ | |
var subscription = subscriptions[i]; | |
if (subscription instanceof Function){ | |
//Trigger outside of loop | |
(function(func, args){ | |
setTimeout(function(){ | |
//... to turn it back to arguments, instead of array | |
func(...args); | |
}); | |
})(subscription, params); | |
} | |
} | |
} | |
} | |
return isExisted; | |
} | |
} | |
} |
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
var emitter = new Emitter(); | |
var subscriber1 = emitter.subscribe('event_1', function(name){console.log(name);}); | |
var subscriber2 = emitter.subscribe('event_1', function(name, id){console.log(`${name} ${id}`);}); | |
var subscriber3 = emitter.subscribe('event_1', function(name, id, gender){console.log(`${name} ${id} - gender: ${3}`);}); | |
emitter.emit('event_1', "Maya", "32", "female"); | |
var subscriber12 = emitter.subscribe('event_12', function(name){console.log(name + 'he');}); | |
subscriber2.release(); | |
emitter.emit('event_1', "Natan", "30", "male"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment