I have an object that has a list of JSONs in specific format as an attribute and from this list I want to create a set of buttons, which should execute the same function, but with arguments given by the JSONs. Below I wrote this as a simple example of how I wanted to do this. Each button should log the number that it is labelled with. So "one" prints 1, "two" prints 2 etc., but instead each button prints 4.
Now the problem is (a least to my understanding of javascript) late-binding. Namely that all functions will be created as late as possible, which is why all buttons will print the last value of "value". How do I avoid this? My attempt with "var self = this" also did not work.
function My_object(div) {
this.list = [{
label: "one",
value: 1
}, {
label: "two",
value: 2
}, {
label: "three",
value: 3
}, {
label: "four",
value: 4
}];
this.div = div;
}
My_object.prototype.createButtonsInDiv = function() {
var self = this,
i = 0,
label = '',
value = 0;
for (i = 0; i < this.list.length; i++) {
label = this.list[i].label;
value = this.list[i].value;
this.div.appendChild(newButton(label, function() {
console.log(value); // will always print '4'
console.log(self.list[i].value); // will always get an error
}));
}
};
function newButton(label, func) {
var button = document.createElement('button');
var buttonText = document.createTextNode(label);
button.appendChild(buttonText);
button.addEventListener("click", func);
return button;
}
var my_div = document.getElementById('my_div');
var o = new My_object(my_div);
o.createButtonsInDiv();
The html in this example consists of a single div with id="my_div".