JS scope failure
I have a little problem: slideHelpers.total = 4
for (i=1;i <= slideHelpers.total; i++) {
$('<a href="#">' + i + '</a>').bind('click', function(){ alert('go to the ' + i + ' slide')}).appendTo('.slideaccess')
}
the warning throws 5, which is boolean because when the click triggers function is actually 5. But I would like to have the same i as in the tag <a>
. What's the best way to handle this?
I could put me in a tag <a>
in the () tag, but I'm sure there is an easier way.
a source to share
for (i=1;i <= slideHelpers.total; i++) {
$('<a href="#">' + i + '</a>').bind('click',
(function(i){
// Capture i in closure
return function(){
alert('go to the ' + i + ' slide')
};
})(i)
).appendTo('.slideaccess')
}
Optimized:
var ary = [], i = 0, n = slideHelpers.total,
open = '<a class="index" href="#">',
close = '</a>';
// Fill array with numbers: 1,2,3,4,5...
while (++i < n) ary[i] = i + 1;
$('.slideaccess').append(
open + ary.join(close + open) + close
).delegate('a.index', 'click', function() {
var index = $.text(this);
alert('go to the ' + index + ' slide');
});
a source to share
You can use an additional function that returns your function:
for (i=1;i <= slideHelpers.total; i++) {
$('<a href="#">' + i + '</a>').bind('click',
(function(i) {
return function() {
alert('go to the ' + i + ' slide');
};
})(i)
).appendTo('.slideaccess');
}
With this additional function, the inner one i
in yours alert
refers to the argument of i
that function, not the i
outer scope.
a source to share
You need to create a new scope, otherwise each function will refer to the same ones i
. In JavaScript, variables are bound to functions.
var make_alert_message = function make_alert_message(num) {
return function () {
alert('go to the ' + num + ' slide');
};
}
for (var i = 1; i <= slideHelpers.total; i++) {
$('<a href="#">' + i + '</a>').bind(
'click', make_alert_message(i)
).appendTo('.slideaccess')
}
a source to share
Your code example i
has basically a global variable. By the time the code is executed alert()
, the i
for loop has the maximum value. The standard way to fix this problem in JavaScript is to create a new function that has a scope to "hold" the variable around. Take, for example, this code that returns your event handling function:
(function(i) { // using i as an argument here 'scopes' it
var something = i; // also within this function scope.
// inside here, both i and something will only ever reference the "local scope"
return function() {
alert(i);
};
})(i); // and here we are calling that function with i = 1,2,3,...
a source to share