Last active
June 13, 2018 00:30
-
-
Save mattpodwysocki/fb90abb47ed40ce9f199 to your computer and use it in GitHub Desktop.
Example of an event aggregator using RxJS
This file contains 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
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