Suppose I have this as an option to a jQuery widget:
function oneFunc()
{
var myVar;
//there is some widget calling
$.widget("ui.combobox", $.ui.autocomplete, {
options: {
source: function (request, response){////doing something with myVar, request and response}
}
});
}
Now I want to separate out the function (request, response)
using callback
So, I want something like this:
function oneFunc()
{
var myVar;
//there is some widget calling
$.widget("ui.combobox", $.ui.autocomplete, {
options: {
source: myCallBack
});
}
function myCallBack(request, response){
//I can get request and response here by default but not myVar
//doing something with myVar, request and response
}
So, I can't access myVar. I have to pass it there. but how to do that?
EDIT:
I don't want to use global variables
request
, response
are default values that I can get in myCallBack anyway.
Better if anonymous function can be avoided.
You can do this by using
Function.apply
orFunction.call
The above outputs
As you have delegated the
this
keyword to the callback method allowing it to access any variables declared in the original method.Live example: http://jsfiddle.net/hFsCA/
Note the
apply
line can also be replaced with (Thanks @AlessandroVendruscolo)Not that it makes too much difference - but for completeness!
So wrapping that back into your (now updated) example:
If you want to access
myVar
inside your separated callback function, I would make it explicit in the declaration:This makes it easier to keep track of when you see it in your code later on. Then, you write a proxy function like this:
If you want a more complex scope or
myVar
needs to be changed in both scopes, you need an object:Then, inside the callback:
I don't if jQuery is internally using any anonymous function or not. But I solved it by this:
Other experienced people can comment on this, I guess.