Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Last active June 13, 2018 00:30
Show Gist options
  • Save mattpodwysocki/fb90abb47ed40ce9f199 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/fb90abb47ed40ce9f199 to your computer and use it in GitHub Desktop.
Example of an event aggregator using RxJS
var Rx = require('rx');
function EventAggregator() {
this._subject = new Rx.Subject(); // Can be ReplaySubject too
}
EventAggregator.prototype.publish = function (type, data) {
this._subject.onNext( { type: type, data: data });
};
EventAggregator.prototype.listen = function (type) {
return this._subject.filter(function (x) { x.type === type }).pluck('data').share();
};
EventAggregator.prototype.dispose = function () {
this._subject.dispose();
};
// Usage
var e = new EventAggregator();
var subscription = e.listen('foo').subscribe(
function (x) {
console.log(x);
});
e.publish('foo', 'bar');
// => 'bar'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment