user1801060
user1801060

Reputation: 2821

Click handler for shapes in easeljs

I'm an EaselJS newbie. I'm following an outdated tutorial. I want to put numbered squares on a stage and then have them dissapear when I click on them.

The original code had an onPress event which I have modified to a click listener. However I get an error message about the scope of the "this" object within my click handler.

TypeError: this.stage is undefined

What am I doing wrong?

c99.Game = (function() {
    function Count99Game(){
        this.canvas = document.getElementById('game-canvas');

        this.stage = new createjs.Stage(this.canvas);
        var totalTiles = 10;

        for(var i = totalTiles; i>0; i--){
            var tile = new c99.Tile(i);
            this.stage.addChild(tile);

            tile.x = Math.random()*(this.canvas.width - tile.width);
            tile.y = Math.random()*(this.canvas.height - tile.height);

            tile.addEventListener("click", function(event){
                this.stage.removeChild(event.target);
                this.stage.update();
            }).bind(this);
        }       

        this.stage.update();
    }

    return Count99Game;
})();

Upvotes: 1

Views: 1440

Answers (1)

apsillers
apsillers

Reputation: 115950

Inside of EaselJS's click handler, this is the window object. You need to move your bind call to the listener function itself:

tile.addEventListener("click", function(event){
            this.stage.removeChild(event.target);
            this.stage.update();
        }.bind(this));

You can also set the handler's this manually using Shape.on:

// pass outer `this` to event listener
tile.on("click", function(event){
            this.stage.removeChild(event.target);
            this.stage.update();
        }, this);

Upvotes: 5

Related Questions