不要在addEventListener中传递参数吗?

时间:2018-05-14 18:35:58

标签: javascript function addeventlistener

为什么在将addEventListener添加到function playSound(e) { const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`); const key = document.querySelector(`.key[data-key="${e.keyCode}"]`); if (!audio) return; //stop the function from running audio.currentTime = 0; // rewinds to the start audio.play(); key.classList.add("playing"); } window.addEventListener('keydown', playSound); 时我不得不传递参数?如何自动传递事件?

go get -v github.com/veandco/go-sdl2/sdl

代码按原样运行

2 个答案:

答案 0 :(得分:1)

以这种方式思考:

function addEventListener(event, handler) {
  const eventObject = new Event();

  switch(event) {
    case "keydown":
      handler(eventObject);

  }
}

这显然是一个简化版本,但是传入的函数是通过addEventListener

的参数调用的

答案 1 :(得分:0)

首先定义了这个功能。在通常情况下,我们会将该函数称为某个位置。但在这种情况下,您希望在触发keydown事件时调用它。为此,您已将该函数作为回调传递给keydown事件。幕后发生了类似下面的事情。

function keydown(callback) {

 var e = getEvent(); // here it will get you the event object.
 callback(e); // here your function playSound is called.

}
相关问题