gpt4 book ai didi

javascript - 如何从事件函数的模块模式中调用函数

转载 作者:行者123 更新时间:2023-11-30 17:12:39 25 4
gpt4 key购买 nike

我正在通过制作一个简单的基于 html5 的游戏来试验 Javascript 模块模式和 html5 Canvas ,并且遇到了我的第一个障碍。我正在监听 Canvas 上的鼠标移动事件。

init: function () {
var gameCanvas = document.getElementById("gameCanvas");
gameCanvas.addEventListener("mousemove", this.redrawAvatar);
}

我正在做的是让我的头像跟随鼠标指针在 Canvas 上的移动。

问题是我的模块中有几个函数,我希望从 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 中,this 对象不再是我的模块,而是事件的来源(在本例中为 Canvas )。

这是我的模块的本质:

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

}());

如何访问我想调用的模块中的函数?

最佳答案

您可以使用 bind在函数中使用当前上下文(在您的例子中是游戏模块)而不是事件的上下文。

gameCanvas.addEventListener("mousemove", this.redrawAvatar.bind(this));

这是一个重现绑定(bind)效果的基本演示。它使用点击事件。

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>

运行代码片段或 jsFiddle Demo

关于javascript - 如何从事件函数的模块模式中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26684334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com