Playerwtf
Playerwtf

Reputation: 311

pubsub design pattern for nodejs

I'm looking for a simple pubsub implementation I can use in nodejs or a simliar way. I only need it on the server side so no fancy faye needed.

I want to have following ability:

Module A publishes event 'X' Module B subscribes to event 'X' without knowing anything about module A(except maybe what params are sent)

I tested out this simple implementation https://github.com/federico-lox/pubsub.js/blob/master/src/pubsub.js which really does its job

The current problem I have with a simple pubsub implementation is that I cannot simply subscribe to events.

If Module A publishes an Event but Module B was nowhere required it will never receive the event from module A. A soon as Module A requires Module B before publishing an event it works of course. But this is rather unpleasant.

So in short form: I'm looking for a design pattern which pairs well with nodejs and allows me to write modules very independently (loose coupling) that can communicate over events. What approaching are you guys recommend?

I also looked at nodejs eventemitter but couldn't find a good use of it (maybe I just can't see it?)

Update: I looked a little bit further into eventemitter and came up with this:

emitter.js

var events = require('events');
var emitter = new events.EventEmitter;

module.exports = emitter;

moduleA.js

var emitter = require('./emitter.js');
require('./moduleB.js'); // this shows off my problem

emitter.emit('moduleA');

moduleB.js

var emitter = require('./emitter.js');

emitter.on('moduleA', function () {
    console.log('reacted to event from moduleA');
});

This shows of my "problem" but I'm not sure if there is a way around. Maybe my approach is completely wrong but on browser side this should work because all code is preloaded on pageload

Upvotes: 2

Views: 3846

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146014

Here's a simple template for basic event plumbing use node's core events module.

//modA.js
var events = require('events');
var emitter = new events.EventEmitter;

function funcA() {
  console.log('[email protected] executing');
  emitter.emit('funcA');
}

module.exports = {
  funcA: funcA,
  emitter: emitter
};

//modB.js
var events = require('events');
var emitter = new events.EventEmitter;

function funcB() {
  console.log('modB.funcB executing');
  emitter.emit('funcB');
}

module.exports = {
  funcB: funcB,
  emitter: emitter
};

//glue.js
var modA = require('./modA');
var modB = require('./modB');
modA.emitter.on('funcA', modB.funcB);
modA.funcA();

node glue.js
[email protected] executing
modB.funcB executing

Upvotes: 7

Related Questions