Reputation: 16051
I created a php/javaScript automatisation of our form creation. Thus, when a dialog is created the button are added dynamicly and correctly, but I cannot access the JSON object in the function trigged on the click of the button.
Here is a exemple (The alert does not work, is not display):
aButtons[oGeneratedFormButtons[x].label] = function(){ alert(oGeneratedFormButtons[i].label); });
Can I pass data to the function or is there a way to know which button has been clicked.
Here is a simple sample : http://jsfiddle.net/DavidLaberge/h4Cgp/13/
Upvotes: 0
Views: 353
Reputation: 22386
try using closure like this:
for (var x = 0; x < JSON.length; x++) {
aButtons[JSON[x].label] = (function() {
var i = x;
return function() {
alert(i);
alert(JSON[i].label);
}
})();
}
Here is fiddle.
Upvotes: 1
Reputation: 76880
Are you sure that the problem is not that you are using a different variable (i instead of x) inside the function? Because oGeneratedFormButtons[x].label should be accessible inside the function if it's accessible outside it.
aButtons[oGeneratedFormButtons[x].label] = function(){ alert(oGeneratedFormButtons[x].label); });
Upvotes: 0