0

I am using WebMidi in a react app and can't figure out how to selectively remove listeners. I have to remove all of the listeners for a particular input.

Does anybody know how to remove listeners one at a time? I need to leave a listener for cc's open while turning another listener for step record on and off.

const startMidiListeners = () => {
    var recordListeners: Array<any> = []
    for (const input of WebMidi.inputs) {
        const listeners = input.addListener("midimessage", e => {
            console.log('received midimessage')
        }, {});
        if (typeof listeners == "object") {
            console.log(`startMidiListeners - added single listener: ${typeof listeners}`);
            recordListeners.push(listeners)
        } else {
            console.log(`startMidiListeners - added multiple listeners: ${typeof listeners}`);
            recordListeners.concat(listeners)
        }
    }

    setRecordListeners(recordListeners)
}

const stopMidiListeners = () => {
    console.log(`stopMidiListeners - stop ${recordListeners.length} listeners`);

    // This doesn't remove the listener
    for (const recordListener in recordListeners) {
        console.log('remove listener')
        WebMidi.removeListener(WebMidi.eventMap.midimessage, recordListener)
    }

    // I have to do this to stop getting callbacks
    // for (var inputNum = 0; inputNum < WebMidi.inputs.length; inputNum++) {
    //     WebMidi.inputs[inputNum].removeListener()
    // }

    setRecordListeners([])
}
ohthepain
  • 2,004
  • 3
  • 19
  • 30
  • 1
    You need the original function that you passed to `.addListener`, in order to remove it. So, instead of `.addListener("midimessage", () => {...})`, you instead do `const midimessageHandler = () => {...}` and then, later, `.addListener('midimessage', midimessageHandler)`. Set up this way, you can then remove it with `.removeListener('midimessage', midimessageHandler)`. – Ouroborus Sep 24 '22 at 06:00
  • That works, thank you. It has to be called on the input, not the static WebMidi object. – ohthepain Sep 24 '22 at 07:23

0 Answers0