I have a list of dynamically created buttons, and need to add an event to each of the buttons. Here is my code:
Ui.prototype.bindEvents = function(len) {
var buttons = [];
for(var i = 0; i < len; i++){
buttons.push(this.div.querySelector('#btn'+i));
}
var mat = 0;
// my try
/* for(var j = 0; j < buttons.length ; j++){
console.log('outside ' + j);
if (buttons[j]) {
buttons[j].addEventListener('click', function() {
console.log('inside ' + buttons[j]);
// mat = j;
pc.app.fire("SwitchMaterial",j);
}, false);
}
}*/
// how it works with an static amount of buttons
if (buttons[0]) {
buttons[0].addEventListener('click', function() {
mat = 0;
pc.app.fire("SwitchMaterial",mat);
}, false);
}
if (buttons[1]) {
buttons[1].addEventListener('click', function() {
mat = 1;
pc.app.fire("SwitchMaterial",mat);
}, false);
}
if (buttons[2]) {
buttons[2].addEventListener('click', function() {
mat = 2;
pc.app.fire("SwitchMaterial",mat);
}, false);
}
if (buttons[3]) {
buttons[3].addEventListener('click', function() {
mat = 3;
pc.app.fire("SwitchMaterial",mat);
}, false);
}
};
here is the link to my project:
https://playcanvas.com/editor/scene/536029