Search code examples
javascriptajaxprototypejs

Prototype and Ajax.Request scope


I'm having trouble getting the correct scope within prototype's Ajax.Request class. What I'm trying to do is write a simple API which wraps ajax requests:

API = Class.create({

  initialize:function(api_token)
  {
    this.api_token = api_token;
    this.request_uri = new Template('/api/#{api_token}/#{resource}.json');
    this.status = 0;
    this.last_result = null;
  },

  some_api_call:function()
  {
    var result = this._request('resource', {'id':1});
    // and so on...
  },

  _request:function(resource, params)
  {
    var uri = this.request_uri.evaluate({"api_token":this.api_token,"resource":resource});
    new Ajax.Request(uri,
    {
      contentType:'application/json',
      method:'get',
      parameters:params,
      onSuccess:function(r)
      {
        alert(this);
        this.last_result = r.responseJSON;
        this.status = r.status;
      }
    });    
    return this.last_result;
  }

});

When I'm in the onSuccess() method I expected +this+ to refer to the parent object, but it is giving me DOMWindow. I can't seem to get that response data into the API class at all. I figure it is something stupid (binding?), but I just can't seem to think this one out today.

Thanks


Solution

  • Okay. I missed the bigger problem. I was requesting asynchronously so it was setting the result, just not immediately. To be fair, it was also a binding issue. Here is the proper request:

    _request:function(resource, params)
    {
      var uri = this.request_uri.evaluate({"api_token":this.api_token,"resource":resource});
      new Ajax.Request(uri,
      {
        asynchronous: false,
        contentType:'application/json',
        method:'get',
        parameters:params,
        onSuccess:function(r)
        {
          this.last_result = r.responseJSON;
          this.status = r.status;
        }.bind(this)
      });    
    
      alert(this.status);
    
      return this.last_result;
    }