0

myFn performs an async task and calls the callback on success

SearchController.prototype.show = function (query) {

    this.searchService.myFn(arg1, this.myCallback); //I want to maintain this `this`
};

SearchController.prototype.myCallback = function (err, result) {
    if(err) {
        this.onError(err);
        return;
    }

    this.onSuccess(result);
}

SearchController.prototype.onSuccess = function() {...)
SearchController.prototype.onError = function() {...)

Clearly the meaning of this is lost in the callback. How can I maintain this to be the this from the invocation of myFn?

Ben Aston
  • 53,718
  • 65
  • 205
  • 331

1 Answers1

0

It should be the responsibility of the myFn function to accept a context as parameter and then use it, or rewrite the method signature and wrap your call in an anonymous function that use call Function.prototype.call:

SearchController.prototype.show = function (query)
{
    var __this = this;
    this.searchService.myFn(function (){ __this.myCallback.call(__this, arg1); });
};

Here is how I would like to see myFn:

SearchController.prototype.myFn = function (arg, callback, context)
{
    // Do work.. when finished:

    callback.call(context, arg);
};

If you're having multiple args you want to apply, then use Function.prototype.apply.

Martin Andersson
  • 18,072
  • 9
  • 87
  • 115