Last active
August 12, 2018 13:53
-
-
Save rvisharma/2c53623e9ebcf3cf0616629606e8577c to your computer and use it in GitHub Desktop.
Tiny implementation of PubSub
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 ps = (function(){ | |
let events = {} | |
let on = (eventName,cb) => { | |
events[eventName] = (events[eventName] || []).concat(cb); | |
return () => events[eventName] = events[eventName].filter(each => each !== cb ); | |
} | |
let pub = (eventName, data) => { | |
(events[eventName] || []).forEach(cb => cb(data)); | |
} | |
return {pub,on}; | |
})() | |
/** Run in console | |
let handler1 = ps.on('asd',(data)=> console.log(`I am sub 1 - You passed ${data}`)) | |
let handler2 = ps.on('new',(data)=> console.log(`I am sub 2 - You passed ${data}`)) | |
ps.pub('asd','asd') | |
ps.pub('new','new') | |
console.log('unsubscribing handler for event: asd'); | |
handler1(); // <= Unsubscribing | |
ps.pub('asd','asd') | |
ps.pub('new','asd') | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uglified version fits in a tweet!
let ps=function(){let t={};return{pub:(n,c)=>{(t[n]||[]).forEach(t=>t(c))},on:(n,c)=>(t[n]=(t[n]||[]).concat(c),()=>t[n]=t[n].filter(t=>t!==c))}}();