NodeJS - 单身+事件

Pas*_*nes 6 events singleton node.js

如何在实现单例设计模式的模块上继承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;
Run Code Online (Sandbox Code Playgroud)

这会导致错误: TypeError: Object #<Object> has no method 'emit'

num*_*407 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());
  }
};
Run Code Online (Sandbox Code Playgroud)

它将被用作:

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"
Run Code Online (Sandbox Code Playgroud)


Joh*_*nor 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();
Run Code Online (Sandbox Code Playgroud)

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

模块A:

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

emitter.emit('myCustomEvent', arg1, arg2, ....)
Run Code Online (Sandbox Code Playgroud)

模块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
});
Run Code Online (Sandbox Code Playgroud)