0

I'm using classes in node.js but in this example, this.done is undefined. Any ideas on how to easily fix that? I'd like to avoid going back to callback hell or learning to use promises right now.

MyClass.prototype.method1 = function(done) {
  this.method1Done = done;
  mysql.query([...], this._method1QueryCallback);
}

MyClass.prototype._method1QueryCallback = function(err, rows) {
  [...]
  this.done(err, rows)
}
Rivenfall
  • 1,189
  • 10
  • 15

1 Answers1

1

You need to bind a particular this context to the method before you can use it as a callback, or the caller will provide its own this (which may not be what you expect).

The simplest way is to:

mysql.query([...], this._method1QueryCallback.bind(this))

Assuming you know this is the correct scope when you call mysql.query.

That does make it difficult to later unbind the callback, which can be a problem if you are setting up an event handler. In that case, you can do something like:

this._method1QueryCallback = this._method1QueryCallback.bind(this);

somewhere in your constructor, or just prior to passing the callback.

ssube
  • 47,010
  • 7
  • 103
  • 140
  • 1
    `this._method1QueryCallback` is undefined because it's not defined on the prototype. It's defined directly as a property of `MyClass` – maček Feb 27 '15 at 17:54
  • I edited my question to add .prototype thanks – Rivenfall Feb 27 '15 at 17:55
  • @maček that was my mistake, although the OP apparently edited immediately after your comment, and now it is on the prototype as well. – ssube Feb 27 '15 at 17:55
  • @Rivenfall any of my input was based on the mistake in your original question. I'm aware that bind can solve your "problem" in this case. – maček Feb 27 '15 at 19:19