所以我通过制作一个简单的基于html5的游戏来试验javascript模块模式和html5画布,并遇到了我的第一个障碍。我在画布上听一个mousemove事件。
init: function () {
var gameCanvas = document.getElementById("gameCanvas");
gameCanvas.addEventListener("mousemove", this.redrawAvatar);
}
我正在做的是让我的头像跟随鼠标指针在画布上的移动。
问题是我在我的模块中有几个函数,我希望从redrawAvatar函数中调用它,如下所示:
redrawAvatar: function (mouseEvent) {
var gameCanvas = document.getElementById("gameCanvas"),
avatarCoord = {x: mouseEvent.offsetX, y: mouseEvent.offsetY},
enemyCoord = {x: 100, y: 100};
this.clear(gameCanvas);
this.drawAvatar(avatarCoord);
this.drawEnemy(enemyCoord);
if (that.isCollision({coord: avatarCoord, size: 30}, {coord: enemyCoord, size: 30})) {
alert("Avatar died, collided with enemy");
}
}
在redrawAvatar里面,这个对象不再是我的模块,而是事件的来源(在这种情况下是画布)
以下是我的模块的精髓:
var MyGame = (function () {
var Game = {
draw: function (image, coord) {},
drawAvatar: function (coord) {},
clear: function (canvas) { canvas.width = canvas.width + 1 - 1;},
drawEnemy: function (xPos, yPos) {},
isCollision: function (a, b) {},
redrawAvatar: function (mouseEvent) {
var gameCanvas = document.getElementById("gameCanvas"),
avatarCoord = {x: mouseEvent.offsetX, y: mouseEvent.offsetY},
enemyCoord = {x: 100, y: 100};
this.clear(gameCanvas);
this.drawAvatar(avatarCoord);
this.drawEnemy(enemyCoord);
if (that.isCollision({coord: avatarCoord, size: 30}, {coord: enemyCoord, size: 30})) {
alert("Avatar died, collided with enemy");
}
},
init: function () {
var gameCanvas = document.getElementById("gameCanvas");
gameCanvas.addEventListener("mousemove", this.redrawAvatar);
}
};
(function () {
var that = Game;
that.init();
}());
}());
如何访问我想要调用的模块中的函数?
答案 0 :(得分:2)
您可以使用bind
在函数中使用当前上下文(在您的情况下是游戏模块)而不是事件的上下文。
gameCanvas.addEventListener("mousemove", this.redrawAvatar.bind(this));
这是一个重现绑定效果的基本演示。它使用点击事件。
var MyGame = (function () {
var Game = {
scoped: 5,
redrawAvatar: function (mouseEvent) {
alert(this.scoped);
},
init: function () {
var gameCanvas = document.getElementById("d");
gameCanvas.addEventListener("click", this.redrawAvatar.bind(this));
}
};
(function () {
var that = Game;
that.init();
}());
}());

<div id="d">Basic element for click handler (click for demo)</div>
&#13;
运行代码段或 jsFiddle Demo