During the execution of the page, a string gets composed containing the code that would need to be executed as the handler for the click event. The string could look like:
var handler = '"myFunction1(12, 20);myOtherFunction();"';
OR
var handler = '"myFunction1(12, 20);"'
When I create the buttons dynamically, and try to attach the events in a loop, it gets attached to the last button only. I can sense a closure issue but what am I missing?
Here is the code.
var buttons = [],
arg1 = 12,
arg2 = 20;
var butt1 = { Text: 'Bye', onClick: "anotherFunction();" },
butt = { Text: 'Hello', onClick: "myNewFunction();" },
butt2 = { Text: 'Bye333' };
buttons.push(butt1);
buttons.push(butt);
buttons.push(butt2);
function myNewFunction() {
   alert('my New  Function');
};
function myCloseFunction(arg1, arg2) {
    alert('close: ' + arg1 + ' other: ' + arg2)
}
function anotherFunction() {
    alert('Say Goodbye');
}
 window.onload = function () {
 var buttonContainer = document.getElementById('controlDiv'),
    closeOnClick = "myCloseFunction(" + arg1 + ", " + arg2 + ")",
    button;
for (var i = 0; i < buttons.length; i++) {
    buttons[i].onClick = (buttons[i].onClick == null) ? closeOnClick : (closeOnClick + ';\n' + buttons[i].onClick);
    button = document.createElement("INPUT");
    button.type = 'button';
    button.onclick = new Function(buttons[i].onClick);
    if (i > 0)
        buttonContainer.innerHTML += ' ';
    buttonContainer.appendChild(button);
   }
};
The HTML page is simple:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="Script.js" type="text/javascript"></script>
</head>
<body>
    <h1>hello</h1>
    <div id="controlDiv"></div>
</body>
</html>
Sensing a closure issue I have tried various options to close over any variables but was not successful. e.g.
button.onclick = (function (action, i) {
    var name1 = 'hello' + i,
        a123 = new Function('action', 'return function ' + name1 + '(){action();}')(action);
        return a123;
    } (new Function(buttons[i].onClick), i));
 
     
    