javascript - 单击 easeljs 中形状的处理程序

标签 javascript jquery easeljs

我是 EaselJS 新手。我正在关注一个过时的教程。我想将带编号的方 block 放在舞台上,然后在我单击它们时让它们消失。

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

TypeError: this.stage is undefined

我做错了什么?

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;
})();

最佳答案

在 EaselJS 的 click 处理程序内部,thiswindow 对象。您需要将 bind 调用移动到监听器函数本身:

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

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

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

关于javascript - 单击 easeljs 中形状的处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23967854/

相关文章:

javascript - 为什么 JavaScript 中的静态私有(private)变量是静态的?

JavaScript、数字和字符串

javascript - Accordion 中的鼠标悬停和鼠标移出

jquery 在页面加载时弹出

javascript - 如果值不匹配,则 Angular 过滤器

javascript - 如何使用 javascript 将图像附加到选择选项中

javascript - 在新窗口中显示文件

javascript - 如何在EaselJS中触发和监听全局事件

javascript - 方法比较 : EaselJS vs Multiple Canvases vs Hidden Canvas for interactiveness

javascript - 使用鼠标添加和删除位图图像 "click"- JavaScript/CreateJS