带参数的移相器按钮处理程序函数

Phaser button handler function with parameter

本文关键字:按钮 处理 程序 函数 参数      更新时间:2023-09-26

我正在使用Phaser.js来构建一个html游戏。这可能更像是一个通用的 javascript 问题,但我使用 Phaser 作为上下文,所以我尝试使用处理程序设置一个按钮,这是 main.js 中的按钮定义:

var someParam = 2;
var btn = game.add.button(0, 0, 'playButton', actions.handler, this, 1, 0, 1);

在另一个名为 actions.js 的文件中,我定义了处理程序函数:

var handler = function(someParam) {
    console.log(someParam);
};
module.exports = {
    handler: handler
};

问题是如何将该 someParam 传递到处理程序函数中?

我不知道

Phaser,但在 JavaScript 中你有两个可能的选择:

1)

game.add.button(0, 0, 'playButton', function(){
  actions.handler(someParam);
}, this, 1, 0, 1);

2)

game.add.button(0, 0, 'playButton',actions.handler.bind(this,someParam) , this, 1, 0, 1);

选项 2 会将函数绑定到特定someParam,因此如果它发生更改,则不会在处理程序中更改它。