类方法被触发而未被调用

时间:2019-05-27 15:21:46

标签: javascript ios html5-audio

我已经定义了一个类来处理播放音频文件。我正在实例化该类,然后调用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();

1 个答案:

答案 0 :(得分:2)

当您添加事件监听器时,例如:

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