2012-05-08 37 views
1

我有一个jquery插件,我用它来包装我所有的ajax调用。它旨在对输入/输出数据进行一些通用的前/后处理。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函数被调用,它似乎就会丢失。我正在以正确的方式来解决这个问题吗?

+1

在第一眼,我认为你需要使用()调用,看到的是https:// developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call – fcalderan

+0

call()完美地工作,谢谢。如果你会这么好,以发布作为答案,请? – John

回答