我是 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
处理程序内部,this
是 window
对象。您需要将 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/