This question already has an answer here:
I want to something similar to this.
function AjaxService()
{
this.Remove = function (id, call_back)
{
myWebService.Remove(id, CallBack)
}
function CallBack(res) {
call_back(res);
}
}
so my calling program will be like this
var xx = new AjaxService();
xx.Remove(1,success);
function success(res)
{
}
Also if I want to add more parameters to success function how will I achive it. Say If i have success function like this
var xx = new AjaxService();
//how to call back success function with these parameters
//xx.Remove(1,success(22,33));
function success(res,val1, val2)
{
}
Help will be appretiated.
Regards Parminder
one way to do this:
So you can use it like this:
I usually have the callback execute using a
setTimeout
. This way, your callback will execute when it gets the time to do so. Your code will continue to execute meanwhile, e.g:Your callback will execute after alert#2.
Of course, in case of your application, it will happen so automatically since the ajax callback itself is asynchronous. So in your application, you had better not do this.
Cheers!
jrh
Use a closure and a function factory:
What you're passing here is not the
generateSuccess
function but the anonymous function returned bygenerateSuccess
that looks like the callback expected byRemove
.val1
andval2
are passed intogenerateSuccess
and captured by a closure in the returned anonymous function.To be more clear, this is what's happening:
Or if you prefer to do it inline:
not as readable but saves you from naming the factory function. If you're not doing this in a loop then Xinus's solution would also be fine and simpler than my inline version. But be aware that in a loop you need the double closure mechanism to disconnect the variable passed into the callback function from the variable in the current scope.
You can pass it as anonymous function pointer