如何在实现单例设计模式的模块上继承events.EventEmitter方法?
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;
这会导致错误:TypeError: Object #<Object> has no method 'emit'
答案 0 :(得分:7)
我在你的问题中没有看到单身模式。你的意思是这样的吗?
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());
}
};
它将被用作:
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"
答案 1 :(得分:5)
我设法使用以下单例事件发射器类来关闭它。 arguments.callee._singletonInstance是在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();
然后,您可以使用以下
访问任何模块中的事件发射器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
});
答案 2 :(得分:2)
为了方便起见,我创建了一个npm包:central-event
您需要做的是在第一个模块中:
// Say Something
var emitter = require('central-event');
emitter.emit('talk', 'hello world');
模块B
// Say Something
var emitter = require('central-event');
emitter.on('talk', function(value){
console.log(value);
// This will pring hello world
});