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'

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"

I managed to pull this off using the following singleton event emitter class. arguments.callee._singletonInstance is the preferred way of doing singletons in javascript: http://code.google.com/p/jslibs/wiki/JavascriptTips#Singleton_pattern

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

var emitter = function() {
    if ( arguments.callee._singletonInstance )
        return arguments.callee._singletonInstance;
    arguments.callee._singletonInstance = this;  
    EventEmitter.call(this);
};

emitter.prototype.__proto__ = EventEmitter.prototype;

module.exports = new emitter();

You can then access the event emitter in any of your modules using the following

MODULE A:

var emitter = require('<path_to_your_emitter>');

emitter.emit('myCustomEvent', arg1, arg2, ....)

MODULE B:

var emitter = require('<path_to_your_emitter>');

emitter.on('myCustomEvent', function(arg1, arg2, ...) {
   . . . this will execute when the event is fired in module A
});

To make it easier, I have created a npm package : central-event

What you have to do is in the first module:

// Say Something
var emitter = require('central-event');
emitter.emit('talk', 'hello world');

Module B

// Say Something
var emitter = require('central-event');
emitter.on('talk', function(value){
  console.log(value);
  // This will pring hello world
 });