Ilya Libin
Ilya Libin

Reputation: 1617

Create objects in a loop with onclicklistener in JavaScript phaser game framework

I'm trying to create an easy quiz game which displays a question and 5 variants of answers.

I work with phaser.js but I think it will applicable for JavaScript in general.

Here is my function that creates 5 buttons

[char_db.js]

for (var i = 0; i < 5; i++) {
    button[i] = game.add.button((30+10*i), (30+5*i), 'buttons', actionOnClick(i), this, 1, 0, 2);
}

And here is my onclick listener which is doing pretty same for each button (but in feature it will do a different functions)

[index.html]

function actionOnClick (id) {
   //  Manually changing the frames of the button, i.e, how it will look when you play with it
   button[id].setFrames(2, 1, 3);
}

I got an error

[Uncaught TypeError: Cannot read property 'setFrames' of undefined]

My button array was declared in a very beginning

button = new Array();

Any suggestions?

Upvotes: 0

Views: 1528

Answers (1)

PhotonStorm
PhotonStorm

Reputation: 3385

There are 2 issues with your code:

1) You're invoking the actionOnClick(i) function in the Button constructor, which isn't the required parameter type (Button expects a reference to a function here).

2) Your actionOnClick function assumes that an ID will be passed by the Button click event, but it won't. In Phaser the first parameter that will be sent is the object that invoked the callback.

With these two things in mind the following approach should work:

for (var i = 0; i < 5; i++) {
  button[i] = game.add.button((30+10*i), (30+5*i), 'buttons', actionOnClick, this, 1, 0, 2);
}

function actionOnClick (button) {
   button.setFrames(2, 1, 3);
}

Upvotes: 1

Related Questions