1.0.3 • Published 6 years ago

observable-lc v1.0.3

Weekly downloads
1
License
ISC
Repository
-
Last release
6 years ago

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 of Observable) will now watch on InnerObject (instance of Observable) publishing event. Whenever event is published by InnerObject, callback is called (with this value pointing to Object A)

  • Observable.prototype.subscribeOnce(event: string, callback: function) - Works exactly as method InnerObject.prototype.subscribe, with difference that Object A will now listen only once for specified event. Further publishing event by InnerObject will not trigger specified callback function

  • Observable.prototype.unsubscribe(event: string) - Removes Object A (which is listening on InnerObject on publishing event) from InnerObject subscribers set. If event is specified, only Object A listening for event will be removed from InnerObject subscribers set. If event is evaluated to false, all members of subscribers set with Object A subscriber will be removed

  • Observable.prototype.publish(event: string, data: Object|any) - Publishes event with specified data Object. If no data is specified, empty object is passed

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago