如何为jQuery回调函数绑定"this"?

6

我正在尝试在jQuery中设置一个回调函数,以正确地绑定“this”到调用对象。具体来说,这是我正在处理的代码。我正在使用类似以下方式的对象进行ajax调用:

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

然而,在Object.prototype.doAjaxCall中,this并不指向正确的对象。我之前使用过Prototype,知道在进行Ajax调用时需要绑定this,但在jQuery中似乎找不到正确的方法。请问有人能指点一下吗?

2个回答

2

使用jQuery ajaxcontext属性来绑定这个。例如:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接