Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript传递参数错误,单击事件传递传递过程中的所有参数_Javascript_Events_Parameters_Arguments_Pixi.js - Fatal编程技术网

JavaScript传递参数错误,单击事件传递传递过程中的所有参数

JavaScript传递参数错误,单击事件传递传递过程中的所有参数,javascript,events,parameters,arguments,pixi.js,Javascript,Events,Parameters,Arguments,Pixi.js,我正在用js和pixi.js制作一个游戏,我在传递函数的参数时遇到了问题。下面的代码 newGame() { // Some code before, then I get the audio which I want to play let audio = this.soundsArray[this.shuffleQuestionsInLevel[this.rightAnswer].sound]; // Auto play audio at the begining of

我正在用js和pixi.js制作一个游戏,我在传递函数的参数时遇到了问题。下面的代码

newGame()
{
  // Some code before, then I get the audio which I want to play
  let audio = this.soundsArray[this.shuffleQuestionsInLevel[this.rightAnswer].sound];
    
  // Auto play audio at the begining of game
  this.playSound(audio);
  // Click to repeat the sound
  this.soundBtn.on('pointerdown', this.playSound.bind(this, audio));
}

// Play audio after 5 seconds
playSound(audio)
{  
  setTimeout(() => audio.play(), 5000);
}
在第一场比赛中,一切都完美无瑕,声音恰到好处。但是,从第二个游戏开始,单击事件this.soundBtn.on('pointerdown',this.playSound.bind(this,audio))播放传球中的所有声音,这意味着在第二场比赛中,将播放2种声音,在第三场比赛中,将播放3种声音

开始时自动播放音频的代码
this.playSound(audio)
每次都能正常工作。在这个游戏中只有声音可以播放


我不知道为什么我调用相同的函数并传递相同的参数,但只传递代码来自动播放音频工作。我想点击事件的工作完全一样。有人知道有什么问题吗?谢谢。

在启动游戏时(当您调用
newGame()
时),您似乎正在连接事件处理程序,但您从未分离它:

//此行附加处理程序,但每次都附加一个新的处理程序!
this.soundBtn.on('pointerdown',this.playSound.bind(this,audio));
//为了理解原因,让我们把它写得更明确一些
//
//首先,通过调用bind从this.playSound创建一个新的“listener”函数
const listener=this.playSound.bind(this,audio);
//然后将此函数作为事件处理程序附加
this.soundBtn.on('pointerdown',listener);
//但是由于监听器不再具有与此相同的功能
//(因为.bind生成一个新函数)下面的行将不起作用
//而听众将保持联系
this.soundBtn.off('pointerdown',this.playSound);
为了解决此问题,您很可能需要将
侦听器
函数存储在某个位置,以便以后将其分离:

newGame(){
// ...
this.\uu playAudio=this.playAudio.bind(this,audio);
this.soundBtn.on('pointerdown',this.\u playAudio);
}
//然后当比赛结束时
this.soundBtn.off('pointerdown',this.\u playAudio);
或者,如果
soundBtn
支持它,则在游戏结束时,只需分离所有
pointerdown
处理程序:

this.soundBtn.off('pointerdown');

效果很好。非常感谢你,你挽救了我的大学生涯^^!他很高兴能帮上忙:)