Search code examples
javascriptphaser-framework

Phaser.Signal: listener is a required param of add() and should be a Function


I am currently using Phaser 2.x.The problem is in create method. I am passing the function as an argument to the this.claimButton.events.onInputDown.add() method. But it is not able to reference the function what am I currently referring to.What can I do for this.

I have tried with this.game.claimTicket() and this.game.claimTicket and also tried this.claimTicket into the this.claimButton.events.onInputDown.add() as a parameter. But I am still getting the error saying Uncaught Error: Phaser.Signal: listener is a required param of add() and should be a Function. But when I tried this.claimButton.events.onInputDown.add(function () { console.log('hello') }) It worked just fine.

var GameState = {
    //initiate game settings
    init: () => {
        //adapt to screen size, fit all the game
        this.game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
        this.game.scale.pageAlignHorizontally = true;
        this.game.scale.pageAlignVertically = true;
    },
    preload: () => {
        this.game.load.image('background', 'assets/images/background.jpg')
        this.game.load.image('ticket', 'assets/images/ticket2.jpg')
        this.game.load.image('claimButton', 'assets/images/claimButton.png')
    },
    create: () => {
        this.background = this.game.add.sprite(0, 0, 'background')
        this.ticket = this.game.add.sprite(this.game.world.centerX, 130, 'ticket')
        this.ticket.anchor.setTo(0.5)
        this.claimButton = this.game.add.sprite(this.game.world.centerX + 180, 125, 'claimButton')
        this.claimButton.anchor.setTo(0.5);

        this.claimButton.inputEnabled = true;
        this.claimButton.input.pixelPerfectClick = true;
        //this.claimButton.events.onInputDown.add(function () { console.log('It worked as I expected') })
        this.claimButton.events.onInputDown.add(this.game.claimTicket,this)
    },
    claimTicket: (sprite) => {
        console.log('claimed')
    }

};

//initiate the Phaser framework
var game = new Phaser.Game(640, 360, Phaser.AUTO);

game.state.add('GameState', GameState);
game.state.start('GameState');

I expected the function claimTicket to be called from inside the this.claimButton.events.onInputDown.add() but it showing the error


Solution

  • it's because this binding of arrow function.

    the this inside GameState.create is the outer scope (probably the global)


    Just don't use arrow function here.

    let GameState = {
        ...
        create(){
            ...
        },
        ...
    }
    

    or

    let GameState = {
        ...
        create:function(){
            ...
        },
        ...
    }