observable-lc
v1.0.3
Published
Publish/subscribe pattern JavaScript implementation
Downloads
1
Maintainers
Readme
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
. Wheneverevent
is published by InnerObject,callback
is called (withthis
value 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 publishingevent
by InnerObject will not trigger specifiedcallback
functionObservable.prototype.unsubscribe(event:
string
) - Removes Object A (which is listening on InnerObject on publishingevent
) from InnerObject subscribers set. Ifevent
is specified, only Object A listening forevent
will be removed from InnerObject subscribers set. Ifevent
is evaluated tofalse
, all members of subscribers set with Object A subscriber will be removedObservable.prototype.publish(event:
string
, data:Object|any
) - Publishesevent
with specifieddata
Object. If nodata
is specified, empty object is passed