1

我有一个 jquery 插件,我用它来包装我所有的 ajax 调用。它旨在对输入/输出数据进行一些通用的前/后处理。

(function ($) {
    $.ajaxCall = function () {

        var myCall = this;
        myCall.settings = {};

        myCall.ExecuteService = function (caller) {
            var ajax = $.ajax({
                type: 'POST',
                url: '../myWebservice',
                dataType: "json",
                context: caller,
                success: myCall.settings.onSuccess
            });
        };
    };
} (jQuery));

我的问题是当我尝试将 onSuccess 事件修改为不仅仅是传入函数时。我有以下使用插件的代码。

this.foo = 'fooStr';
function myOnSuccess(result) {
    alert(this.foo);
}

var newCall = new $.ajaxCall();
newCall.settings.onSuccess = myOnSuccess;
newCall.ExecuteService(this);

function myProto() {
    this.foo = 'otherFooStr';
}

myProto.prototype.success = function(result){
    alert(this.foo);
}

myProto.prototype.makeCall = function(){
    var newCall = new $.ajaxCall();
    newCall.settings.onSuccess = this.success;
    newCall.ExecuteService(this);
}

var proto = new myProto();
proto.makeCall();

这将显示“fooStr”和“otherFooStr”,并且似乎工作正常。但是,如果我尝试修改我的插件以在成功回调中做更多事情,我就会遇到上下文问题。

myCall.ExecuteService = function (caller) {
    var ajax = $.ajax({
        type: 'POST',
        url: '../myWebservice',
        dataType: "json",
        context: caller,
    });
    ajax.success(function(result,status,xhr){
        //*Do some processing to find condition*
        if (condition) {
        //myCall.settings.onSuccess(result); //shows 'undefined' & 'undefined'
        //eval(myCall.settings.onSuccess)(result); //shows 'fooStr' & 'fooStr'
        //this.eval(myCall.settings.onSuccess)(result); //shows 'fooStr' & throws an object exception
        }
    });
};

成功回调的上下文是正确的,但是一旦调用 onSuccess 函数,它似乎就会丢失它。我会以正确的方式解决这个问题吗?

4

1 回答 1

1

您需要使用call()将正确的上下文传递给onSuccess函数,例如

myCall.settings.onSuccess.call(<your context, e.g. this>, result)

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call

于 2012-05-08T11:37:07.073 回答