asking
asking

Reputation: 1445

Node emitter : how to properly design event listeners

I'm learning node:

Looking inside the EventEmitter, by default it executes callbacks by passing the emitter as this to the event listener, such that within your event listener function, this refers to the EventEmitter object.

I'm somewhat confused by this sentiment, how can an object register itself as a listener and keep a reference to its own properties?

Consider this problemo:

Meeting.prototype.recordStatement = function(name, statement) {
    this.minutes.push(name + " said " + statement);
};

It's pretty standard to use a pattern like this to create instance methods for custom objects, but this won't fly as a listener for an EventEmitter: If I attach the recordStatement instance method of a meeting to, say, statements events emitted by, say, a person/emitter, I lose access to the meeting instance properties within the scope of the recordStatement listener, so with respect to the above example, on statement event from the person, this.minutes is undefined.

I suppose I can use an intermediate object here, which would hold a reference to the meeting instance, but, seems like a lot of wiring.

How should I design for this? Thanks!

Upvotes: 0

Views: 417

Answers (1)

mscdex
mscdex

Reputation: 106696

Wrap the function call in a closure:

var self = this;
emitter.on('statement', function(name, statement) {
  self.recordStatement(name, statement);
});

Or use .bind() (can be slower than using a closure):

emitter.on('statement', this.recordStatement.bind(this));

Upvotes: 1

Related Questions