Sunday, May 5, 2019

javascript - access variables(object) outside function within a for loop




my question may sound like a question about closure but it does have some difference.



var people = [{name: 'john', age: 20}, 
{name: 'james', age: 25},
{name: 'ryan', age: 19}];
var mainDiv = document.createElement('div', {id: 'mainDiv'});
for (var i = 0; i < people.length; i++) {
var button = document.createElement('button', {}, mainDiv);
var person = people[i];

button.onClick = function (e) {
console.log('printing name');
console.log(person.name);
};
}


This is just an example I made up. Since the person variable is pointing at the last object of the people array, at the end of the for loop, it always prints out the last element when the button is clicked. However what I wanted to achieve is to print out each corresponding person's name when each button is clicked. What should I do to make the inner 'onClick' function to point at the right object?


Answer



The closure in the code needs to capture the person object within a new context. This can be done by creating a new function (outer) which returns a function (inner) and passing the arguments to that outer function. Also it is best to attach events using attachEvent or addEventListener instead of onclick. Additional calls to maindDiv.onclick will overwrite any eventhandlers on the element.




var people = [{name: 'john', age: 20}, 
{name: 'james', age: 25},
{name: 'ryan', age: 19}];
var mainDiv = document.createElement('div', {id: 'mainDiv'});
for (var i = 0; i < people.length; i++) {
var button = document.createElement('button', {}, mainDiv);
var person = people[i];
attachEvent(button, "click",bindClickEvent(person));
}


//Outer function
function bindClickEvent(person){
//inner function retains context of outer function
return function(){
console.log('printing name');
console.log(person.name);
};
}


function attachEvent(elem, event, func){
if(elem.attachEvent){
elem.attachEvent("on" + event, func);
}else{
elem.addEventListener(event, func);
}
}


JS Fiddle: http://jsfiddle.net/vD5B7/1/



No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...