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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With