Overview

HTTPS SSH

Bus is a module for communication between modules in any JavaScript application. It is similar to the mediator pattern.

Installation

The module is available on the Bitbucket repository:

$ npm install bitbucket:tprimke/bus#v0.2

It is strongly advised to install some tagged version.

Synchronous handlers

At first, the Bus module should be loaded:

var Bus = require('bus');

Now, some synchronous handlers can be added:

Bus.on('hello', () => "world");

let [type, result] = Bus.send('hello');
// type === 'value'
// result === 'world'

When we don't expect any results (feedback) from messages, result can be also ignored:

Bus.send('hello');

We can also request a promise of the result:

Bus.send.promise('hello')
   .then( (val) => {
     let [type, result] = val;
   })
   .catch( (err) => {
     // ooops
   });

One advantage of using promises is the fact, that if handler throws an error, it can be handled in the catch part.

Naming messages

By a convention, messages are plain strings. Any strings can be used

Removing handlers

Any handler can be removed:

let handler = () => { ... };
Bus.on('msg', handler);
Bus.clear(handler);

The Bus.clear function takes any number of arguments. They are handlers, which should be removed.

It is also possible to remove all the handlers at once:

Bus.clear();

It can be useful for testing purposes.

Asynchronous handlers

Sometimes a feedback from a message is expected, but the feedback is asynchronous. In such situations, it would be pointless to use synchronous handlers. We have to use asynchronous one:

Bus.on.promise('msg', () => {
  // ...

  // return 1;
  // return new Promise( (resolve, reject) => { ... } );
});

Such a handler can return either a synchronous value (useful in mocks), or a promise.

Of course, an asynchronous handler should be used only with promises:

Bus.send.promise('msg')
   .then( (result) => { ... } )
   .catch( (err) => { ... } );

Calling asynchronous handler in the synchronous way throws an error.

Synchronous and asynchronous handlers

For each message, you have to make a clear decision: should the message be handled synchronously, or asynchronously? The decision is made by using either Bus.on or Bus.on.promise. Once the decision is made, it cannot be taken back.