Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS - Singleton + Events

How would I inherit events.EventEmitter methods on a module implementing the singleton design pattern?

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

var Singleton = {};
util.inherits(Singleton, EventEmitter);

Singleton.createClient = function(options) {
    this.url = options.url || null;

    if(this.url === null) {
        this.emit('error', 'Invalid url');
    } else {
        this.emit('created', true);
    }
}

module.exports = Singleton;

This results in the error: TypeError: Object #<Object> has no method 'emit'

like image 758
Pastor Bones Avatar asked Nov 20 '12 03:11

Pastor Bones


1 Answers

I don't see the singleton pattern in your question. You mean something like this?

var util = require("util")
  , EventEmitter = process.EventEmitter
  , instance;

function Singleton() {
  EventEmitter.call(this);
}

util.inherits(Singleton, EventEmitter);

module.exports = {
  // call it getInstance, createClient, whatever you're doing
  getInstance: function() {
    return instance || (instance = new Singleton());
  }
};

It would be used like:

var Singleton = require('./singleton')
  , a = Singleton.getInstance()
  , b = Singleton.getInstance();

console.log(a === b) // yep, that's true

a.on('foo', function(x) { console.log('foo', x); });

Singleton.getInstance().emit('foo', 'bar'); // prints "foo bar"
like image 65
numbers1311407 Avatar answered Oct 27 '22 14:10

numbers1311407