locked
Using this. in Promise callbacks

    Question

  • I come from an object oriented world, but I'm trying to make a go of javascript.  I've created a class using WinJS.Class.define.  One of the methods makes a call to a webservice.  I'm using WinJS.xhr to make the call.

     

    In promise returned by the xhr call I'd like to access some member variables of my class.  So something like this:

    WinJS.xhr({ url: flickrURL }).then(
    function (response)
    {
         var test = this.classMember;
         var functionResult = this.someFunction();
    },
    function (response)
    {
         ....
    });

    The problem is "this" is not my class but some other object.  Is there any way to do this?

     

    Thank you,

    Ricky

    Wednesday, November 09, 2011 12:35 AM

Answers

  • The trick here is to cache a reference to your object before doing the asynchronous callback:

     

    var that = this;
    
    WinJS.xhr(options).then(function(response) {
        that.someFunction(response);
    }
    
    

    Cheers,

    -Jeff

    Wednesday, November 09, 2011 5:04 PM

All replies

  • The trick here is to cache a reference to your object before doing the asynchronous callback:

     

    var that = this;
    
    WinJS.xhr(options).then(function(response) {
        that.someFunction(response);
    }
    
    

    Cheers,

    -Jeff

    Wednesday, November 09, 2011 5:04 PM
  • Thank you!!!!

    Wednesday, November 09, 2011 8:54 PM