Variation of the classical infamous looping dilemma
Just about everyone has ran into this specific issue:
function addLinks () {
for (var i=0, link; i<5; i++) {
link = document.createElement("a");
link.innerHTML = "Link " + i;
link.onclick = function () {
alert(i);
};
document.body.appendChild(link);
}
}
window.onload = addLinks;
The value of i
after the loop is cached. A closure can be used to create a "live" reference:
function addLinks () {
for (var i=0, link; i<5; i++) {
link = document.createElement("a");
link.innerHTML = "Link " + i;
link.onclick = function (num) {
return function () {
alert(num);
};
}(i);
document.body.appendChild(link);
}
}
window.onload = addLinks;
We can also use self executing anon fns to create closures as well, etc..
My situation
The issue I'm facing is the same, but the context is a little different. Here's a failing example:
Hit 'add more lis' a few times and click 'hit me', which will alert -1
. The value of maxIndex
is cached. Relevant code:
var attached = false;
function actions() {
var elements = $('body').find('li');
var maxIndex = elements.length -1;
var cycle = {
next: function() {
alert( maxIndex );
}
};
if ( !attached ) {
$('#next').click(function(e) {
cycle.next();
开发者_StackOverflow社区 });
attached = true;
}
};
actions();
$('#add').click(function(e) {
e.preventDefault();
$('<li/>').text('god').appendTo('body');
actions();
});
I've tried applying closures to no avail. ( see http://jsfiddle.net/Bfcus/23/ and down to /1/ ).
I don't want to use with
statements or let
statements/expressions to solve this. I know another way this is solvable is by changing maxIndex
to be a property of a named object. Here's a working example doing it that way.
What I'm wondering is - is there a way of having it work while keeping the elements
variable definition inside of the action
function, and having the maxIndex
variable defined in the same scope? Basically, can http://fiddle.jshell.net/r7Ekj/2/show/ be adjusted to work almost in the same manner as it is, without relying on with/let/object property?
Weird, sometimes creating a thorough question actually helps you solve it and I swear I didn't have it solved beforehand...
I just created the maxIndex
variable outside of the actions
scope and actually assign it inside.. this makes it work because it isn't defined in the same function scope and so the binding behaves differently.
http://fiddle.jshell.net/r7Ekj/9/
( How embarassing? )
精彩评论