Losing Scope of Array on Click Event Loop [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript closure inside loops - simple practical example
I have an array of 4 objects (that.pairs), and each object has a .t property which is a jQuery object/element. I'm trying to set an event on each t being clicked.
The problem is that when one of the them gets clicked, it's always the last pair (index 3) that gets passed into my doToggle() function.
Why is this happening? How can I fix it?
for (var i = 0; i < that.pairs.length; i++) {
var p = that.pairs[i];
p.t.click(function() {
that.doToggle(p);
});
}

It's because the p variable is shared by your closures, there's just one p variable. By the time your handlers are called, p has changed.
You have to use a technique I call freezing your closures
for (var i = 0; i < that.pairs.length; i++) {
// The extra function call creates a separate closure for each
// iteration of the loop
(function(p){
p.t.click(function() {
that.doToggle(p);
});
})(that.pairs[i]); //passing the variable to freeze, creating a new closure
}
A easier to understand way to accomplish this is the following
function createHandler(that, p) {
return function() {
that.doToggle(p);
}
}
for (var i = 0; i < that.pairs.length; i++) {
var p = that.pairs[i];
// Because we're calling a function that returns the handler
// a new closure is created that keeps the current value of that and p
p.t.click(createHandler(that, p));
}
Closures Optimization
Since there was a lot of talk about what a closure is in the comments, I decided to put up these two screen shots that show that closures get optimized and only the required variables are enclosed
This example http://jsfiddle.net/TnGxJ/2/ shows how only a is enclosed
In this example http://jsfiddle.net/TnGxJ/1/, since there's an eval, all the variables are enclosed.

Use $.each instead of a for loop so that you get a new variable scope with each iteration.
$.each(that.pairs, function(i, p) {
p.t.click(function() {
that.doToggle(p);
});
});
This way each click handler closes over a unique variable scope instead of the shared outer variable scope.

for (var i = 0; i < that.pairs.length; i++) {
var p = that.pairs[i];
(function(p){
p.t.click(function() {
that.doToggle(p);
});
}(p));
}
This trick with IIFE would solve the closure "issue" you're experiencing now.

for (var i = 0; i < that.pairs.length; i++) {
(function(num){
var p = that.pairs[num];
p.t.click(function() {
that.doToggle(p);
});
})(i)
}
Classic closure issue
Enclose them in an anonymous function and assign the current iteration in context. That should solve the problem..

Related

Trying to grasp let vs var a little better

Trying to grasp the differences between the two and I am experimenting with different examples to ensure I understand properly.
I have already looked at this question on Stack Overflow:
What's the difference between using "let" and "var" to declare a variable?
It seemed to make sense until I stumbled across this code segment:
http://jsbin.com/xepovisesi/edit?html,output
const buttons = document.getElementsByTagName("button");
for(var i = 0; i < buttons.length; i++) {
const button = buttons[i];
button.addEventListener("click", function() {
alert("Button " + i + " Pressed");
});
}
<button />
<button />
<button />
<button />
If you change the first for loop statement to a let, the functionality works as expected... It alerts which button was pressed. However var just alerts "Button 10 was pressed" every time. Why is it doing this?
Thanks,
James.
It's explained in the first paragraph of the accepted answer for the linked question:
The difference is scoping. var is scoped to the nearest function block
and let is scoped to the nearest enclosing block (both are global if
outside any block), which can be smaller than a function block.
var creates a variable in the scope outside for statement block. The equivalent code with let looks like this:
let i = 0;
for(i = 0; i < buttons.length; i++) {
const button = buttons[i];
button.addEventListener("click", function() {
alert("Button " + i + " Pressed");
});
}
Event listener for every button is bound to a single instance of i, which has value 10 after for loop ends, and you see that when you press each button.
This code
for(let i = 0; i < buttons.length; i++) {
const button = buttons[i];
button.addEventListener("click", function() {
alert("Button " + i + " Pressed");
});
}
has i in the scope of the of the for statement block. That means that for each iteration, new instance of i is created and bound in the event handler, so each handler shows different value for i.
Without let you can create a scope by introducing a function. The common way to write such code before let was
const buttons = document.getElementsByTagName("button");
for(var i = 0; i < buttons.length; i++) {
addButtonListener(i);
}
function addButtonListener(i) {
const button = buttons[i];
button.addEventListener("click", function() {
alert("Button " + i + " Pressed");
});
}
This is not indeed obvious and needs to be specified.
The reason is that let in a for(...) statement creates a new "binding" at each iteration. It's this way because the standard says so, but it could have been different without changing the meaning of let in other cases.
For example in Common Lisp it is unspecified (is implementation dependent) if a (dotimes ...) form will create a new binding at each iteration or not.
In other words Javascript code like:
for (let i=0; i<10; i++) {
...
}
is equivalent to
{
let __hidden__ = 0;
for (__hidden__ = 0; __hidden__ < 10; __hidden__++) {
let i = __hidden__;
...
}
}
and it's NOT the same as
{
let i = 0;
for (i = 0; i<10; i++) {
...
}
}
I personally think that this is indeed the most useful semantic (a new binding at each iteration) as reusing the same binding can be surprising in case of captures. It's also much easier to implement the other semantic when you need it (the second snipped is simpler and shorter than the first).
Reusing the same binding is instead for example what Python 3 does for variables in comprehensions:
[(lambda : i) for i in range(10)][3]() # ==> 9
Finally in my opinion the worst possible choice is leaving it implementation-dependent ... what Common Lisp surprisingly did...
(let ((L (list)))
(dotimes (i 10)
(push (lambda () i) L))
;; May be the following will print 10 times 10, or may
;; be the numbers from 9 to 0
(dolist (f L)
(print (funcall f))))
The difference is scope. In this example, you are creating a javascript closure (By having the event listener inside the for loop). Javascript does not write the value into the lexical scope of the function at the time the function is defined, rather, it looks up the value when the function is executed. When you use var, it will define the variable i inside the scope of whatever function it is inside of. In this case, the global scope. So each loop iteration refers to the same i variable, which gets incremented to 10 rather instantaneously, and the variable lives on past the for loop. So, when the event listener fires, it references the i variable on the global scope, whose value remains 10.
On the other hand, using let creates a LOCAL copy of i, which is scoped to its respective loop iteration. When the event listener is fired, it checks its own scope for the variable i which it obviously doesn't find, and then it moves outward, with the next step being the scope of the for loop to which it finds the local copy of i which retained its value for that specific iteration of the loop - hence you get the correct alert message for each button that is pressed.
Summary / TLDR;
var scopes variables to the function in which it is defined
let scopes variables to the block in which it is defined
Variables referenced in closures work their way outward through the scope chain when searching for a definition of a variable, stopping at the global scope.
Hope this helps!
Variable 'i' is being captured inside your button event handler.
1) If you don't have 'let' available, you can resolve this by scoping a new variable inside a IIFE like below:
const button = buttons[i];
(function() {
var j = i;
button.addEventListener("click", function() {
alert("Button " + j + " Pressed");
});
})()
2) Or, if you have 'let' available just do:
const button = buttons[i];
let j = i;
button.addEventListener("click", function() {
alert("Button " + j + " Pressed");
});
The reason for this is because the var keyword is hoisted to the top of scope, where as let is block scoped (closest curly brace). Let me explain by showing you how code is pseudo-interpreted by the JavaScript runtime.
Code using var...
function () {
for(var i = 0; i < buttons.length; i++) {
var button = buttons[i];
[...]
}
}
...gets converted to something like this by the JS runtime (due to hoisting):
function () {
var i, length, button;
for(i = 0; i < buttons.length; i++) {
button = buttons[i];
[...]
}
}
The thing to notice here is that the variables only exist once. These variables get updated on each iteration of the for loop. When the for loop is finished, all of the variables are holding the "last" value from the very last iteration.
Whereas the same code code using let...
function () {
for(let i = 0; i < buttons.length; i++) {
let button = buttons[i];
[...]
}
}
...gets treated differently. The variables are scoped to the curly braces around the for loop. Conceptually, you can think of it like a forEach statement:
function () {
buttons.forEach(function(item, i) {
var button = buttons[i]; // same as "item"
var length = buttons.length;
[...]
});
}
The thing to notice is that every iteration of the for loop gets its own variable i, length, and button - no sharing taking place. This is the distinction.

Javascript Closures and self-executing anonymous functions

I was asked the below question during an interview, and I still couldn't get my head around it, so I'd like to seek your advice.
Here's the question:
var countFunctions = [];
for(var i = 0; i < 3; i++){
countFunctions[i] = function() {
document.getElementById('someId').innerHTML = 'count' + i;
};
}
//The below are executed in turns:
countFunctions[0]();
countFunctions[1]();
countFunctions[2]();
When asked what would be the output of the above, I said count0,count1 and count2 respectively. Apparently the answer was wrong, and that the output should all be count3, because of the concept of closures (which I wasn't aware of then). So I went through this article and realized that I should be using closure to make this work, like:
var countFunctions = [];
function setInner(i) {
return function(){
document.getElementById('someId').innerHTML = 'count' + i;
};
}
for(var i = 0; i < 3; i++){
countFunctions[i] = setInner(i);
}
//Now the output is what was intended:
countFunctions[0]();//count0
countFunctions[1]();//count1
countFunctions[2]();//count2
Now that's all well and good, but I remember the interviewer using something simpler, using a self-executing function like this:
var countFunctions = [];
for(var i = 0; i < 3; i++) {
countFunctions[i] = (function(){
document.getElementById('someId').innerHTML = 'count' + i;
})(i);
}
The way I understand the above code, we are skipping the declaration of a separate function and simply calling and executing the function within the for loop.
But when I ran the below:
countFunctions[0];
countFunctions[1];
countFunctions[2];
It didn't work, with all the output being stuck at count2.
So I tried to do the below instead:
for(var i = 0; i < 3; i++) {
countFunctions[i] = function(){
document.getElementById('someId').innerHTML = 'count' + i;
};
}
, and then running countFunctions[0](), countFunctions[1]() and countFunctions[2](), but it didn't work. The output is now being stuck at count3.
Now I really don't get it. I was simply using the same line of code as setInner(). So I don't see why this doesn't work. As a matter of fact, I could have just stick to the setInner kind of code structure, which does work, and is more comprehensive. But then I'd really like to know how the interviewer did it, so as to understand this topic a little better.
The relevant articles to read here are JavaScript closure inside loops – simple practical example and http://benalman.com/news/2010/11/immediately-invoked-function-expression/ (though you seem to have understood IEFEs quite well - as you say, they're "skipping the declaration of a separate function and simply calling and executing the function").
What you didn't notice is that setInner does, when called, return the closure function:
function setInner(i) {
return function() {
document.getElementById('someId').innerHTML = 'count' + i;
};
}
// then do
var countFunction = setInner("N"); // get the function
countFunction(); // call it to assign the innerHTML
So if you translate it into an IEFE, you still need to create (and return) the function that will actually get assigned to countFunctions[i]:
var countFunctions = [];
for(var i = 0; i < 3; i++) {
countFunctions[i] = (function(i){
return function() {
document.getElementById('someId').innerHTML = 'count' + i;
};
})(i);
}
Now, typeof countFunctions[0] will be "function", not "undefined" as in your code, and you can actually call them.
Take a look at these four functions:
var argument = 'G'; //global
function passArgument(argument){
alert(argument); //local
}
function noArguments(){
alert(argument); //global
}
function createClosure_1(argument){
return function (){
alert(argument); //local
};
}
function createClosure_2(argument){
var argument = argument; //local
return function (){
alert(argument); //local
};
}
passArgument('L'); //L
noArguments(); //G
createClosure_1('L') //L
createClosure_2('L') //L
alert(argument) //G
I think, first function is obvious.
In function noArguments you reference the global argument value;
The third and fourth functions do the same thing. They create a local argument variable that doesn't change inside them and return a function that references that local variable.
So, what was in the first and the last code snippet of your question is a creation of many functions like noArguments,
that reference global variable i.
In the second snippet your setInner works like createClosure_1. Within your loop you create three closures, three local variables inside them. And when you call functions inside countFunctions, they get the value of the local variable that was created inside the closure when they were created.
In the third one you assign the result of the execution of those functions to array elements, which is undefined because they don't return anything from that functions.

A deep understanding of javascript closures [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 9 years ago.
I'm trying to grasp this bit of code, I know it's a closure but I'm not getting the result I think I should get.
This code returns me an [object MouseEvent], I can't understand why?
I'm adding a function call (updateProduct) to an .addEventListener using this code, and it returns an [object MouseEvent]
function addEventListenerToMinPlus(){
var x, y
for(var i = 0; i < productItemAll.length; i++){
x = productItemAll[i].querySelector(".boxNumbers-min")
x.addEventListener("click", function(i){return function(i){updateProduct(i)}}(i))
console.log(x)
}
}
function updateProduct(jow){
alert(jow)
}
jsFiddle
The browser invokes the event handler with an event object as the first parameter. Your function is declared to take a single parameter ("i"), so when you display it, that's what it is.
I suspect that what you meant was for the "i" inside the event handler to refer to the "i" in the outer function (the loop index). That also won't work, because the various handlers the loop creates will all refer to the same shared variable "i". See this old SO question.
The line
x.addEventListener("click", function(i) { return function(i) { updateProduct(i); }(i) }
produces a closure of the inner function
function(i) { updateProduct(i); }
The outer i is in the scope of this inner function, but it is shadowed by its parameter. So, in effect, the inner i represents the first argument passed to the click handler (the MouseEvent). If you want it to retain the value of the index, you have to change its name. Something like this:
x.addEventListener("click",
function(i) { return function(e) { updateProduct(i); }(i)
}
Now, in the inner function, e is the MouseEvent, and i is the outer index. I have updated the JSFiddle: http://jsfiddle.net/Cdedm/2/. Clicking the minus alerts 0 for the first item and 1 for the second, as expected.
that is because you are sending the element as parameter.
You should try doing this:
function addEventListenerToMinPlus(){
var x, y
for(var i = 0; i < productItemAll.length; i++){
x = productItemAll[i].querySelector(".boxNumbers-min")
x.addEventListener("click", function(){return updateProduct(i)})
console.log(x)
}
}
Hope this works,
Regards,
Marcelo
I think you are trying to do something like this. Your i will change by the time the click happens so it needs to be set to another local variable, in this case through the parameter on the new function. The click event handler will pass the event object you are getting currently
function addEventListenerToMinPlus() {
var x, y;
for(var i = 0; i < productItemAll.length; i++) {
x = productItemAll[i].querySelector(".boxNumbers-min");
x.addEventListener("click", function(i){return function(){updateProduct(i)}}(i));
}
}
function updateProduct(jow) {
alert(jow);
}
Unless you really really really know what you're doing, you can play about with closures all day and still not get it right with this sort of thing.
A more understandable appraoch by far, with more readable code for most people, is to use jQuery's .data() method to associate data (i in this case) with the element in question so it can be read back when the click event fires, for example :
function addEventListenerToMinPlus() {
var x, y;
for(var i = 0; i < productItemAll.length; i++) {
x = productItemAll[i].querySelector(".boxNumbers-min");
x.data('myIndex', i);//associate `i` with the element
x.addEventListener("click", function(i) {
var i = $(this).data('myIndex');//read `i` back from the element
updateProduct(i);
});
console.log(x);
}
}
For the record, a working closure would be as follows :
function addEventListenerToMinPlus() {
var x;
for(var i = 0; i < productItemAll.length; i++) {
x = productItemAll[i].querySelector(".boxNumbers-min");
x.addEventListener("click", function(i) {//<<<< this is the i you want
return function() {//<<<< NOTE: no formal variable i here. Include one and you're stuffed!
updateProduct(i);
}
}(i));
console.log(x);
}
}

Get iterator index into a onmousedown function

I am trying to do a seemingly trivial thing, but I cant figure this out. I am iterating over items found by the document.getElementByClassName method. I am doing so with indices so I can keep track of some stuff, and I need that index inside the onmousedown events for that specific element, however I can't figure out to do so.
var items = document.getElementsByClassName("someClass");
for (var i = items.length - 1; i >= 0; i--)
{
items[i].onmousedown=function(){
//This does not work:
var index = i; //I need the i variable from the loop above in here.
console.log(index);
this.innerHTML = doSomeWorkWith(index);
};
}
Anyone know how to do this? I have thought of adding it to the element itself so I can access a variable there, but I would prefere not to as it would clutter the html code.
You need to keep your indexes in closure, something as
for (var i = items.length - 1; i >= 0; i--){
(function(index){
...do anithing
})(i);
}
You'll need to create the handler functions on the fly, using another function. That can easily be done using immediately invoced function expressions (IIFEs). That way, you'll get the i to be evaluated when defining the handler, not when executing it.
var items = document.getElementsByClassName("someClass");
for (var i = items.length - 1; i >= 0; i--) {
items[i].onmousedown = (function (index) {
return function () {
console.log(index);
this.innerHTML = doSomeWorkWith(index);
}
})(i);
}
Basically, I'm not directly assigning a function to onmousedown, but creating one on the fly that has the value of i hardcoded.
To create that handler function, I'm using another function, that I immediately (in-place) invoke after defining it, without ever assigning a name. (Of course I just could create that function in global scope and us it here, but as I don't need it anywhere else, why should I?)
[Edit]: To use the event inside that function, use
var items = document.getElementsByClassName("someClass");
for (var i = items.length - 1; i >= 0; i--) {
items[i].onmousedown = (function (index) {
return function (event) {
this.innerHTML = doSomeWorkWith(index);
// do something with "event" here
}
})(i);
}
This is a classical problem, the anonymous function captures the variable and not its value, so when it is indeed called, the current value is not correct.
See this link for more information : Arguments to JavaScript Anonymous Function

Jquery does not quite work inside for loop [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript: closure of loop?
I have following code inside javascript:
for (var i=0; i < images_array.length; i++) {
$('#thumb_'+ i).live('click', function(){
$('#image_container_' + current_image_index).hide();
current_image_index = i;
alert(current_image_index);
$('#image_container_' + current_image_index).show();
});}
when I click on any thumb, i get images_array.length value. Does anyone know what is happenning?
You need to create a closure for the click handler function, like this:
for (var i=0; i < images_array.length; i++) {
$('#thumb_'+ i).live('click',
(function(i) {
return function(){
$('#image_container_' + current_image_index).hide();
current_image_index = i;
alert(current_image_index);
$('#image_container_' + current_image_index).show();
}
})(i)
);
}
The problem is that, without the closure, the variable is shared across every handler function -- it continues getting updated, which is why every handler ends up getting the array.length value. Using the closure creates a locally-scoped copy of the variable i.
Here's a demo that shows the difference:
Original
With closure
$.each(images_array,function(value,i) {
$('#thumb_'+ i).live('click', function(){
$('#image_container_' + current_image_index).hide();
current_image_index = i;
alert(current_image_index);
$('#image_container_' + current_image_index).show();
});}
As others have said, you need a closure. Now, you're already using jQuery so forget about for() and directly use $.each.

Categories

Resources