6

我将如何在实现单例设计模式的模块上继承 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'

4

3 回答 3

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"
于 2012-11-20T04:12:33.653 回答
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();

然后,您可以使用以下命令访问任何模块中的事件发射器

模块 A:

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

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

模块 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
});
于 2013-02-07T05:31:59.307 回答
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
 });

于 2015-07-14T13:30:52.917 回答