observable-lc v1.0.3
Subscribe/publish pattern implementation
My implementation of subscribe/publish pattern written in JavaScript.
How to use
If object is supposed to use subscribe/publish it has to extends (it needs to have Observable methods in its prototype chain) Observable class. Example:
const Observable = require('publish-subscribe-lc');
class Outer extends Observable {
}Instance of Observable can subscribe to events published by other objects which are instances of Observable. Those objects needs to be fields of Outer object:
const Observable = require('publish-subscribe-lc');
class Outer extends Observable {
constructor () {
super();
this.inner = new Inner();
this.inner.subscribe('test', function (data) {
console.log(data.text);
});
}
}
class Inner extends Observable {
constructor () {
super();
this.timeout = setTimeout(function () {
this.publish('test', {
text: 'test'
});u
}.bind(this), 500);
}
}
const outer = new Outer();Expected output:
test#API
Observable.prototype.subscribe(event:
string, callback:function) - Object A (instance ofObservable) will now watch on InnerObject (instance ofObservable) publishingevent. Whenevereventis published by InnerObject,callbackis called (withthisvalue pointing to Object A)Observable.prototype.subscribeOnce(event:
string, callback:function) - Works exactly as methodInnerObject.prototype.subscribe, with difference that Object A will now listen only once for specifiedevent. Further publishingeventby InnerObject will not trigger specifiedcallbackfunctionObservable.prototype.unsubscribe(event:
string) - Removes Object A (which is listening on InnerObject on publishingevent) from InnerObject subscribers set. Ifeventis specified, only Object A listening foreventwill be removed from InnerObject subscribers set. Ifeventis evaluated tofalse, all members of subscribers set with Object A subscriber will be removedObservable.prototype.publish(event:
string, data:Object|any) - Publisheseventwith specifieddataObject. If nodatais specified, empty object is passed