1

I am trying to resolve a 'this problem' in a Node server. If I don't replace the following worker.stuff with worker.stuff.bind(worker) it doesn't work.

Is there a way to add the bind in the Worker Class itself? Using it every time I call the function is boring.

Here is the server:

var app = require("express")()
    , Worker = require('./worker')
    , worker = new Worker();

app.get("/stuff", worker.stuff);

worker.on('done', function () {
    console.log('done')
});

app.listen(3000);

Here is the worker:

function Worker(options) {}

require('util').inherits(Worker, require('events').EventEmitter);

Worker.prototype.stuff = function (req, res) {
    this.emit('done');
    res.send();
}

module.exports = Worker;
Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109
yves amsellem
  • 7,106
  • 5
  • 44
  • 68

1 Answers1

2

Here's the best I can think of:

function Worker(options) {
    var self = this;

    this.stuff = function (req, res) {
        self.emit('done');
        res.send();
    }
}

require('util').inherits(Worker, require('events').EventEmitter);

module.exports = Worker;

Define all your methods inside the constructor and refer to the closured self instead of this.

I'd probably bite the bullet and use bind as necessary.

Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109