Skip to content

Instantly share code, notes, and snippets.

@rvisharma
Last active August 12, 2018 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rvisharma/2c53623e9ebcf3cf0616629606e8577c to your computer and use it in GitHub Desktop.
Save rvisharma/2c53623e9ebcf3cf0616629606e8577c to your computer and use it in GitHub Desktop.
Tiny implementation of PubSub
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')
*/
@rvisharma
Copy link
Author

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))}}();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment