Skip to content

Instantly share code, notes, and snippets.

@itsmunim
Created August 13, 2018 08:29
Show Gist options
  • Select an option

  • Save itsmunim/1f17de58af20739e16f1b71bdfeffd46 to your computer and use it in GitHub Desktop.

Select an option

Save itsmunim/1f17de58af20739e16f1b71bdfeffd46 to your computer and use it in GitHub Desktop.
// 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