Loading...

dev-extensions@lists.mozilla.org

[Prev] Thread [Next]  |  [Prev] Date [Next]

Problem with "this" in XMLHttpRequest's onreadstatechange whitedavidp Tue Apr 03 15:01:02 2012

I am pretty stumped here...

I have created the following object/prototype for dealing with XMLHttpRequest's onreadystatechange:

function XMLHttpRequestCompleteListener(_request, _onCompleteCallback, _callbackData)
{
  this.request = _request;
  this.onCompleteCallback = _onCompleteCallback;
  this.callbackData = _callbackData;
}

XMLHttpRequestCompleteListener.prototype =
{
  onreadystatechange: function()
  {
    dump("\nStarting onreadystatechange: " + this.request.readyState);

    try
    {
      if(this.request.readyState == 4)
      {
        this.onCompleteCallback(this.request, this.callbackData);
      }
    }
    catch(e)
    {
      // do nothing - this can happen if the process gets aborted when
      // the user closes the address book
    }

    dump("\nEnding onreadystatechange");
  }
}

I am trying to use it thus:

var callbackData = {};
callbackData.phase = 1;
var listener = new XMLHttpRequestCompleteListener(request, methodToCallback, callbackData);
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = listener.onreadystatechange;
request.send(null);

However, the reference to this in the line in onreadystatechange

dump("\nStarting onreadystatechange: " + this.request.readyState);

fails with -- Error: this.request has no properties

It is now clear to me that "this" is not correct as the method is being called without in some other context.

The question is: how can I ensure that the call is made in a context where "this" can be correct? Other suggestions to solving this problem are also welcome.

Thanks
_______________________________________________
dev-extensions mailing list
[EMAIL PROTECTED]
https://lists.mozilla.org/listinfo/dev-extensions