How to add event ability to object instance in Nod

2020-04-20 21:15发布

It's ok to add event ability to a constructor:

function Stream() {
    events.EventEmitter.call(this);
}
util.inherits(Stream, events.EventEmitter);

But how to add event ability to an object instance? The following code doesn't work:

var foo = {x: 1, y: 2};
util.inherits(foo, event.EventEmitter);
events.EventEmitter.call(foo);

After running the above code, foo.on still be undefined. Is there a way to inherit or mix-in EventEmitter's content?

1条回答
Deceive 欺骗
2楼-- · 2020-04-20 21:52

You can use the npm module node.extend. It is a port of jQuery's $.extend and with it, you can do this:

var extend = require('node.extend'),
    events = require('events');
extend(foo, events.EventEmitter.prototype);

or, if you don't want to use another module, you can use this:

function extend(target) {
    var sources = Array.prototype.slice.call(arguments, 1);
    return sources.forEach(function (source) {
        Object.keys(source).forEach(function (key) {
            target[key] = source[key];
        });
    }), target;
}
var events = require('events');
var foo = {x: 1, y: 2};

extend(foo, events.EventEmitter.prototype);
查看更多
登录 后发表回答