单击easeljs中的形状处理程序

use*_*060 1 javascript jquery easeljs

我是EaselJS的新手.我正在关注一个过时的教程.我想在一个舞台上放置编号的正方形,然后当我点击它们时让它们消失.

原始代码有一个onPress事件,我已将其修改为单击侦听器.但是我在单击处理程序中收到有关"this"对象范围的错误消息.

TypeError: this.stage is undefined
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

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;
})();
Run Code Online (Sandbox Code Playgroud)

aps*_*ers 5

在EaselJS的click处理程序内部,this是window对象.您需要将您的bind调用移动到侦听器函数本身:

tile.addEventListener("click", function(event){
            this.stage.removeChild(event.target);
            this.stage.update();
        }.bind(this));
Run Code Online (Sandbox Code Playgroud)

您还this可以使用Shape.on以下方法手动设置处理程序:

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