2009-08-07 40 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(); 
}); 
相关问题