Last active
October 8, 2017 16:05
-
-
Save juanmaguitar/485a762a07159eba6913b759dd1bce3c to your computer and use it in GitHub Desktop.
Publish/Subscribe Implementation
This file contains hidden or 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
| 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