2009-05-21 66 views
3

我無法在原型的Ajax.Request類中獲取正確的作用域。我正在試圖做的是寫一個簡單的API,它包裝的Ajax請求:原型和Ajax.Request範圍

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; 
    } 

}); 

當我在我預期的onSuccess()方法是+這+來指代父對象,但它給我DOMWindow。我似乎無法將該響應數據放入API類中。我認爲這是愚蠢的(綁定?),但我似乎今天似乎無法想到這一個。

謝謝

回答

8

好的。我錯過了更大的問題。我在異步請求,所以它設置結果,只是不立即。公平地說,這也是一個有約束力的問題。這裏是正確的要求:

_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; 
} 
0

你的解決方案不應該工作?

您需要使用局部變量的嵌套函數上面,然後將它們轉換成「這個」範圍:

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