We are using jQuery in our application for making AJAX calls. How do I inovke a method in a particular context using jQuery? In dojo we used to do it using dojo.hitch().
Is there something similar in jQuery? Below is the sample code that we are using. I need to execute the success handler in the context of SampleMethod. The below code should
give me exception since resultSetHandler is not available in the window context. Could you please let me know.
We are using jQuery version 1.3.2
function SampleMethod(){
this.invokeProcedure=function(procedurePath){
$.ajax({
type: "GET",
url: procedurePath,
dataType: "json",
success: resultSetHandler,
error: errorHandler
});
}
this.resultSetHandler=function(args){
//Handle the result
}
this.errorHandler=function(args){
//Handle the result
}
}
var sampleObj=new SampleMethod();
sampleObj.invokeProcedure('url');
Just preserve
thisand wrap them in functions:(Probably should pass the “success” function argument forward to “resultSetHandler” too.)
edit — the above will handle this sort of issue in the general case, but @Blaster correctly points out in a comment that the jQuery
$.ajaxmechanism provides a simpler solution. Acontextproperty can be set in the parameter object you pass in, and the value will be used as the context for the callbacks. That is, adding:to the
$.ajaxparameter object would make things work as you originally wrote it.