Skip to content

Instantly share code, notes, and snippets.

@juanmaguitar
Last active October 8, 2017 16:05
Show Gist options
  • Select an option

  • Save juanmaguitar/485a762a07159eba6913b759dd1bce3c to your computer and use it in GitHub Desktop.

Select an option

Save juanmaguitar/485a762a07159eba6913b759dd1bce3c to your computer and use it in GitHub Desktop.
Publish/Subscribe Implementation
EventEmitter = {
_events: {},
publish: function (event, data) {
if (!this._events[event]) return; // no one is listening to this event
this._events[event].forEach( callback => callback(data) )
},
subscribe: function (event, callback) {
if (!this._events[event]) this._events[event] = []; // new event
this._events[event].push(callback);
}
}
const buyer = { __proto__: EventEmitter }
const seller = { __proto__: EventEmitter }
buyer.subscribe('house:price', price => console.log(`NEW PRICE: ${price.value}`) )
seller.publish('house:price', { value: 100 }) // NEW PRICE: 100
seller.publish('house:price', { value: 200 }) // NEW PRICE: 200
seller.publish('house:price', { value: 50 }) // NEW PRICE: 50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment