class 方法在未被调用的情况下触发

class method triggered without being called

我已经定义了一个 class 来处理播放音频文件。我正在实例化 class,并调用它的 addEventListener() 方法,此时 playSound() 在没有点击元素的情况下被触发。此外,当我调用 getEventListeners(bgMusic.elem) - 监听器不再附加。

class WebAudio {

    constructor(soundFile, elem) {
        this.soundFile = soundFile;
        this.elem = elem;
        this.audio = new Audio('sound/' + this.soundFile);
    }

    addListener() {
        this.elem.addEventListener('touchstart', this.playSound());
    }

    playSound() {
        if (context.state != 'suspended') {
            console.log('playing audio file');
            if (!this.audio.playing) {
                this.audio.play();
            }
        } else {
            console.log("Audio Context locked? " + context.state)
        }
    }

}

var AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
function webAudioTouchUnlock(context) {
    return new Promise( (resolve, reject) => {
        //if AudioContext is suspended, and window has been interacted with
        if (context.state === 'suspended' && 'ontouchstart' in window) {
           console.log(context.state);
           var unlock = () => {
               //resume AudioContext (allow playing sound), remove event listeners
               context.resume().then(() => {
                   console.log("context resumed");
                   document.body.removeEventListener('touchstart', unlock);
                   document.body.removeEventListener('touchend', unlock);
                   resolve(true);
               }, function (reason) {
                 reject(reason);
               });
           };
           document.body.addEventListener('touchstart', unlock, false);
           document.body.addEventListener('touchend', unlock, false);
       } else {
           console.log('context not suspended? Context is ' + context.state);
           resolve(false);
       }
    });
}

webAudioTouchUnlock(context);
let bgMusic = new WebAudio('bensound-clearday.mp3', document.querySelector('#sound_button'));
bgMusic.addListener();

当您添加事件侦听器时:

 this.elem.addEventListener('touchstart', this.playSound());

您需要调用函数:this.playSound() 并将该函数的结果 (undefined) 添加为侦听器。

您只想添加对函数的引用:

this.elem.addEventListener('touchstart', this.playSound);

这样听众也可以在需要时调用它。

此外,您可能需要使用类似这样的东西来维护正确的 this:

this.elem.addEventListener('touchstart', () => this.playSound());

或:

this.elem.addEventListener('touchstart', this.playSound.bind(this));