1

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
  • For those like me don't understand this is because you can't change prototype after creation, you need a constructor to do that Commented Sep 19, 2016 at 10:43

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.