Reputation: 123
I would like to understand why in this "loop" I cannot attach the key of element in an event with a closure/inner function. I know what happens with other loops like for,while
... I don't understand the real reason why in this situation this approach doesn't work.
Q: Why can I not pass the key directly?
item.transaction(["itens"], "readonly").objectStore("itens").openCursor()
.onsuccess = function(e) {
var info = e.target.result;
if (info) {
var div = document.createElement("div");
var img = document.createElement("img");
var h2 = document.createElement("h2");
img.src = "../imagens/misc/" + info.value.image;
h2.innerHTML = info.value.title;
div.appendChild(h2);
div.onclick = function() {
//always the lasy key.
console.log(info.key);
};
div.appendChild(img);
box.appendChild(div);
info.continue();
}
};
I know type of solution works...
bt.onclick = (function(index) {
return function (){console.log('iterator: ' + index);}
})(i);
with ({ n: i }) {
bt.onclick = function(index) {
console.log('iterator: ' + n);
};
}
Upvotes: 0
Views: 56
Reputation: 8337
In the example given, you're overwriting div.onclick
for each iteration of the cursor.
What's going on might be clearer if you changed it to be:
console.log('overwriting onclick handler to log: ' + info.key);
div.onclick = function() {
console.log(info.key);
};
Or instead, don't overwrite:
console.log('adding onclick listener to log: ' + info.key);
div.addEventListener('click', function() {
console.log(info.key);
});
These will behave differently but perhaps help you to understand what's going on.
Upvotes: 2