Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save antonioaguilar/50a91cff483139e8ad62ae59c469e16e to your computer and use it in GitHub Desktop.
Save antonioaguilar/50a91cff483139e8ad62ae59c469e16e to your computer and use it in GitHub Desktop.
Pub Sub pattern with RxJS
// Reference from: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/howdoi/eventemitter.md
var hasOwnProp = {}.hasOwnProperty;
function createName (name) {
return '$' + name;
}
function Emitter() {
this.subjects = {};
}
Emitter.prototype.emit = function (name, data) {
var fnName = createName(name);
this.subjects[fnName] || (this.subjects[fnName] = new Rx.Subject());
this.subjects[fnName].onNext(data);
};
Emitter.prototype.listen = function (name, handler) {
var fnName = createName(name);
this.subjects[fnName] || (this.subjects[fnName] = new Rx.Subject());
return this.subjects[fnName].subscribe(handler);
};
Emitter.prototype.dispose = function () {
var subjects = this.subjects;
for (var prop in subjects) {
if (hasOwnProp.call(subjects, prop)) {
subjects[prop].dispose();
}
}
this.subjects = {};
};
var emitter = new Emitter();
var subcription = emitter.listen('data', function (data) {
console.log('data: ' + data);
});
emitter.emit('data', 'foo');
// => data: foo
// Destroy the subscription
subscription.dispose();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment