I'm making several buttons from an object and append them to the only div in the body: #main, everything works fine except for actual click function: I can't seem to make the buttons alert different properties.
This is my object:
var BrushDesc = function (n, i, t) {
this.presetName = n;
this.elemId = i;
this.preset = t;
};
var brush = {};
brush.circ = new BrushDesc("circle", "circle", "basic circle");
brush.rect = new BrushDesc("rectangle", "rect", "19-2");
brush.softy = new BrushDesc("round soft", "softy", "softy");
brush.rake = new BrushDesc("|||", "rake", "21-3");
that was my first attempt appending the buttons but this always alerts last .preset
property of the object:
for (var i in brush) {
$('<button id="'+brush[i].elemId+'">'+brush[i].presetName+'</button>')
.appendTo("#main")
.click(function() {alert(brush[i].preset)});
}
So I thought 'okay :('. Then I made it differently and this seems to work but in the same time this looks really wrong (mostly because this relies on .elemId
and brush.property
having the same name:
for (var i in brush) {
$('<button id="'+brush[i].elemId+'" class="main">'+brush[i].presetName+'</button>')
.appendTo("#main")
}
$(".main").click(function() {
var buttonId = $(this).attr("id");
for (var i in brush) {
if (brush[i].elemId == buttonId) alert(brush[i].preset)
}
});
Can anyone please make it right?
edit: Thanks for pointing the Closures thread (haven't used them yet) Felix, but I'm not sure I understand how to apply this to my objects
var tps = [];
function createTps(i) {return function() {alert(br[i].preset)}} //doh
for (i = 0; i<5; i++) {tps[i] = createTps(i)} //but I should have keys here, not numbers?
var j = 0;
for (var i in br) {
$('<button id="' + br[i].elemId + '" class="main">' + br[i].presetName + '</button>')
.appendTo("#main")
.click(function() {tps[j](); j++}); //yeah, sure
}
edit2 Actually a friend of mine suggested to use Immediately-Invoked Function Expression instead of closure and it worked perfectly
for (var i in brush) {
(function (i) {
$('<button id="'+brush[i].elemId+'">'+brush[i].presetName+'</button>')
.appendTo("#main")
.click(function() {alert(brush[i].preset)});
})(i);
}