Created
August 13, 2018 08:29
-
-
Save itsmunim/1f17de58af20739e16f1b71bdfeffd46 to your computer and use it in GitHub Desktop.
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
| // This is a simple sample of how an event pool like thing can work as delegator | |
| // between angular and react world; where both are co-existing. | |
| // The goal is to let react component know whenever something gets broadcasted | |
| // or emitted in angular $scope, without sharing/injecting angular specific code into it. | |
| // EventPool.js | |
| class EventPool { | |
| constructor() { | |
| this._eventsMap = {}; | |
| } | |
| on(evt, cb) { | |
| let eventsMap = this._eventsMap; | |
| let cbs = eventsMap[evt] || []; | |
| cbs.push(cb); | |
| eventsMap[evt] = cbs; | |
| return function () { | |
| delete eventsMap[evt]; | |
| } | |
| } | |
| notify(evt, data) { | |
| let cbs = this._eventPool[evt] || []; | |
| cbs.forEach(cb => cb(data)); | |
| } | |
| } | |
| const eventPool = new EventPool(); | |
| export default eventPool; | |
| // Inside some react component | |
| import eventPool from './EventPool.js'; | |
| ... | |
| eventPool.on('search', () => { updateQueryOrWhatever(); }) | |
| // Inside angular world where we use $scope.$on or $rootScope.$on | |
| // when the emitted or broadcasted event is coming from some other controller | |
| // or angular directive/component that we have no control upon at this moment. | |
| // Mostly delegation is happening. | |
| import eventPool from './EventPool.js'; | |
| ... | |
| $scope.$on('search', (data) => { | |
| eventPool.notify('search', data); | |
| }); | |
| // Or | |
| // Inside angular world where we will just utilize our simple event pool instead | |
| // of using $scope.$broadcast or $scope.$emit at all, if that's in an angular component | |
| // thats already being modified right now. | |
| import eventPool from './EventPool.js'; | |
| ... | |
| eventPool.notify('search', data); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment