Copy link to clipboard
Copied
Hi!
I try to give a function call to 3 buttons i have on my stage. Each of these Buttons should call the same function but with different parameters:
var _this = this;
cnt = 0;
_this.txt_info.text = "";
for (i = 1; i <= 3; i++) {
_this["but" + i].on('click', function () {
schreibe(i);
});
}
function schreibe(u) {
cnt++;
_this.txt_info.text = "Clicked on button " + u + "\nClick count: " + cnt;
}
The result is strange:
Clicking on a button will call the function, but the parameter is allways 4 - no matter if i click on but1, but2 or but3. Click count works fine and is counting - no matter if i click on but1, but2 or but3.
This will work, but on a later project i have about 20 buttons on my stage and i wont do the following code for each button:
var _this = this;
cnt = 0;
_this.txt_info.text = "";
// THE FOLLOWING CODE WILL WORK - BUT I NEED IT 20 TIMES :-(
_this.but1.on('click', function () {
schreibe(1);
});
_this.but2.on('click', function () {
schreibe(2);
});
_this.but3.on('click', function () {
schreibe(3);
});
function schreibe(u) {
cnt++;
_this.txt_info.text = "Clicked on button " + u + "\nClick count: " + cnt;
}
What is going wrong? It's me - this is sure 🙂 Please help.
Hi.
I think it's easier if you pass the optional data argument to the on method and retrieve that information that you need by accessing the data parameter in the event handler. Like this:
var _this = this;
var i;
var cnt = 0;
function schreibe(e, data)
{
cnt++;
_this.txt_info.text = "Clicked on button " + data.u + "\nClick count: " + cnt;
}
_this.txt_info.text = "";
for (i = 0; i < 3; i++)
_this["but" + (i + 1)].on("click", schreibe, this, false, { u: i + 1 });
Regards,
JC
Copy link to clipboard
Copied
Hi.
I think it's easier if you pass the optional data argument to the on method and retrieve that information that you need by accessing the data parameter in the event handler. Like this:
var _this = this;
var i;
var cnt = 0;
function schreibe(e, data)
{
cnt++;
_this.txt_info.text = "Clicked on button " + data.u + "\nClick count: " + cnt;
}
_this.txt_info.text = "";
for (i = 0; i < 3; i++)
_this["but" + (i + 1)].on("click", schreibe, this, false, { u: i + 1 });
Regards,
JC
Copy link to clipboard
Copied
Thanks a lot, JoãoCésar
This has solved my problem! Great support!
Copy link to clipboard
Copied
Great!
You're welcome.