0

I have an object containing a number of buttons (label and callback) which I dynamically want to add to the DOM:

var buttons = {
    'Save': function() {
        return false;
    },
    'Abort': function() {}
};

for(label in buttons) {
    $('#buttonbar').append('<button>' + label + '</button>');

    var callback = buttons[label];
    $('#buttonbar button:last-child').click(function() {
        //var result = callback();
        alert(callback);
    });
}

But regardless which button I click, the variable callback always contains the function of the last button. See this fiddle.

Any ideas how to solve that?

Lars Ebert
  • 3,487
  • 2
  • 24
  • 46

1 Answers1

0

Thanks to the hint given by Barmar I found the solution:

var buttons = {
    'Save': function() {
        return false;
    },
    'Abort': function() {}
};

for(label in buttons) {
    $('#buttonbar').append('<button>' + label + '</button>');

    var callback = buttons[label];
    (function(cb) {
        $('#buttonbar button:last-child').click(function() {
            alert(cb);
        });
    })(callback);
}
Community
  • 1
  • 1
Lars Ebert
  • 3,487
  • 2
  • 24
  • 46