ciso
ciso

Reputation: 3050

Do node.js event emitters have to be bound to a custom object to use them effectively?

In node.js why do some examples of event emitters look simple like this:

EventEmitter = require("events").EventEmitter;
ee1 = new EventEmitter;

and then ee1 is used to emit and listen to events.

Yet other examples look like this:

EventEmitter = require("events").EventEmitter;
util = require("util");

MyFunc = function ()
   EventEmitter.call(this);
}
util.inherit(MyFunc, EventEmitter);

ee2 = new MyFunc();

and then ee2 is used to emit and listen to events.

Can you use ee1 to handle all events (emitting them wherever you want, for example in your custom object.). What is the reason to bind the event emitter prototype to your own custom objects/functions?

Upvotes: 1

Views: 796

Answers (2)

maček
maček

Reputation: 77796

There's nothing inherently wrong with doing it that way, but if you plan on going down the path of ee1, I suggest you look into Event Aggregator Pattern. With a little careful planning, you should be able to avoid some of the gotchas with a single event bus.

Personally, I've always preferred the ee2 way of doing things. I think it keeps things a little more organized (encapsulated).

Upvotes: 1

Henry Merriam
Henry Merriam

Reputation: 824

The idea is that your object is an EventEmitter. Using your names given, this lets you do something like:

ee2.on('some-event', ...);

while also using your object normally:

ee2.myOwnFunction();

Upvotes: 0

Related Questions