Cool Bus

The Problem

// app.js

var EE2 = require('EventEmitter2').EventEmitter2;

var bus = new EE2();

var ModuleA = require('./moduleA');

var moduleA = new ModuleA(bus);

bus.on('beep', function() {
  console.log('app.js heard "beep"');
});

bus.emit('beep');
// moduleA.js

module.exports = ModuleA;

function ModuleA(bus) {
  bus.on('beep', function() {
    console.log('moduleA.js heard "beep"');
  }); 
  return this;
}

The Problem

$ node ./app.js
moduleA.js heard "beep"
app.js heard "beep"
$ 

A Better Way

// app.js

var coolbus = require('coolbus'),
    ModuleA = require('moduleA');

var bus = coolbus.bus('aBus');

bus.on('beep', function() {
  console.log('app.js heard "beep"');
});

bus.emit('beep');
// moduleA.js

var coolbus = require('coolbus');

var bus = coolbus.bus('aBus');

module.exports = ModuleA;

function ModuleA() {
  bus.on('beep', function() {
    console.log('moduleA.js heard "beep"');
  });
  return this;
}

A Better Way

$ node ./app.js
moduleA.js heard "beep"
app.js heard "beep"
$ 

So What?

// Working with an app with a bunch of modules...

/app.js
/config.js
/controllers/
  /controller1.js
  /controller2.js
/routes/
  /routes.js
/models/
  /model1.js
  /model2.js

// you'll have to pass the event bus at each require()

So What?

// With coolbus, you just require the module in each script and
// you get access to ALL the event busses

var coolbus = require('coolbus');

console.log(coolbus.list());
/*
[
  'appBus',
  'routeBus',
  'modelBus'
]
*/

var appBus = coolbus.bus('appBus');

appBus.on('beep', function() {
  console.log('the app beeped!');
});

Cool Bus

By ben-bradley

Cool Bus

A walk-through of the coolbus module

  • 1,242