2009-08-07 85 views
6

我想在jQuery中設置一個回調,將「this」正確地綁定到調用對象。具體來說,這是我正在使用的代碼。我在這樣的對象做一個Ajax調用:如何爲jQuery回調綁定「this」?

Object.prototype.doAjaxCall = function(url) 
    { 
     $.get(url, null, this.handleAjaxResponse); 
    } 

然而,在Object.prototype.doAjaxCallthis不指向正確的事。我之前曾經使用過Prototype,並且我知道在進行Ajax調用時需要將它綁定,但我似乎無法找到在jQuery中執行此操作的正確方法。有人能指引我朝着正確的方向嗎?

回答

1

更健壯的本地綁定函數應該是ECMAScript 3.1的一部分。與此同時...

Object.prototype.doAjaxCall = function(url) { 
    var bind = function(context, method) { 
     return function() { 
      return method.apply(context, arguments); 
     }; 
    }; 

    $.get(url, null, bind(this, this.handleAjaxResponse)); 
}; 
2

使用jQuery ajaxcontext屬性綁定此。例如:

$.ajax({ 
    context: this, 
    url: url, 
    type: 'GET' 
}).done(function(data, textStatus, jqXHR) { 
    this.handleAjaxResponse(); 
});