Reputation: 105449
I want to be able to see the value inside callback function which was available when an event was bound. If function is defined when the event is bound then inside the function I can see the value through closure:
var number = 777;
$('span').click(function() {
alert(number); //alerts 777 - available through closure
});
But if the function is defined previously when the 'number' variable was unavailable, the trick won't work. The function number_alerter can't see the 'number' variable if the function is bound to the event in this way:
$('span').click(number_alerter);
It seems that the only solution is to define the function with the 'number' argument and pass the 'number' varible to the function:
//function defined somewhere earlier
function number_alerter(e, number) {
alert(number);
}
...
//current scope
var number = 777;
$('span').on('click', function(e) {
return number_alerter(e, number);
});
My question is whether there is another way to pass this varible to the 'number_alerter' function? Maybe it's also possible through closure?
EDIT: Here is the real case when the above described might be needed. I have two functions:
array_sort(array, compare_function)
compare_values(value1, value2, case_insensitive)
The function array_sort passes to compare_values function only two values, while 3rd case insensitive parameter should be also passed when using the function array_sort. The only way I know how to do that is to wrap compare_values function into another function:
var my_array = [];
var case_insensitive = true;
var wrapper = function(value1, value2) {
compare_values(value1, value2, case_insensitive)
}
array_sort(my_array, wrapper);
Is there any other way I can do that?
Upvotes: 0
Views: 82
Reputation: 122908
You can use number_alerter
to return the callback function, and use a closure. Like this
function number_alerter(num) {
return function(){alert(num);};
}
// different scope
var number = 777;
$('span').on('click', number_alerter(number));
See jsFiddle
Upvotes: 1
Reputation: 5676
Your problem has to be elsewhere. As far as you describe it, the following
var number=777;
var alerter=function(){
alert(number);
};
$("span").click(alerter);
works just fine. Cf. the JSFiddle And, yes, if you need to have access to a defined state (e.g. you define a click-counter for every span) of a variable, it would be done best it with closures.
Edit: Oh, I see
$('span').click(
(function() {
return number_alerter})());
That's not the way to do it. you have to pass the function name at this point.
Upvotes: 0