Tim
Tim

Reputation: 2285

node.js event emitters binding to mulitple instances

If I have a class that listens to event emitters, is it wrong practice to bind on every instance?

function MyClass() {

    emitter.on('ready', function() {
    // do something
    });

}

myclass = new MyClass();

If I call emitter.on() multiple times, it warns me.

(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.

Are event emitters meant to be bound only once per module, outside of class instances?

If this is wrong, then how do I access the class instance when events are triggered?

Thanks

Upvotes: 2

Views: 1792

Answers (1)

Raynos
Raynos

Reputation: 169551

The warning is that your attaching 11 event listeneres to the ready event on a single event emitter.

Generally when you listen to the same event multiple times on a single event emitter, it's likely that's a bug. For example say you have an http event emitter, if your listening on the request event 11 times that's probably a bug, you only want to listen and handle request once.

This is a debugging tool. You can get around this by doing

emitter.setMaxListeners(500); // or whatever you think is a sensible limit

Upvotes: 3

Related Questions