true-pubsub

1.1.1 • Public • Published

True PubSub minimalistic library

The simpliest possible minimalistic PubSub library without any dependencies at all (no jQuery or other libs), dependent only on ES5 support.

The interface is described below.

Why do I need it?

PubSub mediator allows you to build system of loosely-coupled modules knowing nothing about each other. Not always this is appropriate, but sometimes is very useful. Such approach also helps to make modules with many dependencies testable by allowing them to interact only with the mediator (pubsub in case), so the tests can be easily written and the test case conditions can be easily reproduced.

Example

Say you're receiving data from the server an want two parts of the application (validator and logger for instance) to be notified once the data is received. You write (don't be confused with imaginary get call):

Loader.get('/data', function(data) {
    validator.check(data);
    logger.log(data);
});

This forces the Loader module to know about all data consumers, that sounds not very bad until there're dozens of them. Even worse that there's no really safe (in means of regression testing) and handy (in means of not knowing about the Loader internals) way to add another one consumer; you're obliged to add another method's call to the callback body.

One way to break the Loader's dependency on data consumers is to make those parts decoupled (or loosely coupled) through the PubSub instance. PubSub works like a mediator between any other parts of the system. All parts willing to emit events may call emit method and each interested in specific topic part subscribes for the messages about it. Once the message is published the pubsub instance translates it to every listener. Thus the Loader together with another modules should know only about pubsub interface, not about each other.

The Loader may look like this:

var pubsub = new require('true-pubsub');
 
Loader.get('/data', function(data) {
    pubsub.emit('data loaded', data);
});

and each consumer should have the same instance of PubSub plugged in and listen to the messages:

function Validator(pubsub) {
    pubsub.on('data loaded', this.check.bind(this));
}
var validator = new Validator(pubsub); // here should be the same instance!
 
function Logger(pubsub) {
    pubsub.on('data loaded', this.log.bind(this));
}
var logger = new Logger(pubsub);

In the above code we assume that both Validator and Logger classes have already defined methods those are intended for receiving data. Each of them will be called by pubsub once the message data loaded is generated by anybody; and each of the listeners will be supplied with the arguments passed by the emitter (data in this case). Hence the only thing you have to do to add another consumer is to give it access to the common pubsub instance and subscribe for the required topic.

Interface

on(event, callback)

Subscribes for the specified event. The callback must be a function that will be called once the event occurs. Arguments passed to the emit method will be passed as is to the callback. For example:

var pubsub = new PubSub;
 
pubsub.on('load', function (data) {
    console.log(data);
});

off(event, callback)

Unsubscribes the callback from the event. Provided callback has to be the same function as passed to on in order to be removed from the listeners list (as removeEventListener works).

var pubsub = new PubSub;
 
var handler = function (data) {
    console.log(data);
};
 
pubsub.on('load', handler); // adds handler to the listeners list
pubsub.off('load', handler); // removes it

once(event, callback)

Subscribes only for the first emitted event. Works like the unsubscription right after event occurrence, but without the need of unsubscribing by hand.

var fn = function (data) {
    console.log(data);
};
 
pubsub.once('load', fn);

is equivalent to

var fn = function (data) {
    console.log(data);
};
 
pubsub.on('load', function (data) {
    fn(data);
    pubsub.off('load', fn);
});

but by far more compact and clear.

emit(event, ...)

Emtis the specified event (must be a string) passing to every listener all spare arguments.

For instance, the following code:

var pubsub = new PubSub;
 
pubsub.on('test', function (a, b) {
    console.log('listener 1', a, b);
});
 
pubsub.on('test', function (a) {
    console.log('listener 2', a);
});
 
pubsub.emit('test', 1, 5);

will produce two messages in console:

listener 1, 1, 5
listener 2, 1

Testing

Run sequentially npm install and npm test or mocha in project's directory. Yor need mocha to be installed on your system globally.

TODO

  • Throw clear errors in unexpected cases
  • Think out a way to distinguish methods of different instances of one class passed as arguments. There's no need of doing that. If the method is passed to the on as is, it should be called in undefined context (which doesn't make any sence), but once it's binded to it's master object (using bind or apply) it becomes another function and the implicit comparison made inside of Array.prototype.indexOf evaluates them as different objects.
  • Find an appropriate type of exporting in different environments (node, require etc.)

License

Copyright (c) 2016 Oleg Gromov

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Dependents (1)

Package Sidebar

Install

npm i true-pubsub

Weekly Downloads

2

Version

1.1.1

License

MIT

Last publish

Collaborators

  • oleggromov