简体   繁体   中英

Can't manage to remove event listeners from element

I have to functions which are being called in different places. The first one initializes event listeners and destroy() tries to remove those event listeners. The initialization is working, the destruction not.

private onClick = (index) => {
    // do something with index
}

load = (data) => {
    this.initialPositions = data;

    this.initialPositions.forEach((value, index) => {
        value.frame.addEventListener("click", this.onClick.bind(value.frame, index));
    });
};

destroy = () => {
    this.initialPositions.forEach((value, index) => {
        value.frame.removeEventListener("click", this.onClick.bind(value.frame, index));
    });
};

initialPosition is an array of objects including frame which is a DOM Element and supposed to listen for click events.

Within the application, if already initialized, destroy is being called before load to remove the event listeners of the previously set initialPositions . This seems to not work, since repeating this process, onClick will be executed multiple times.

this.onClick.bind() is creating a new function object , which means you are calling removeEventListener() with a different function that you called addEventListener with. What you'll need to do is push the reference to each onClick handler to an array when you call load() and then iterate the array, passing each element to removeEventListener when you destroy. Something like this:

load = (data) => {
    this.initialPositions = data;
    this.bindings = []
    this.initialPositions.forEach((value, index) => {
        const binding = this.onClick.bind(value.frame, index)
        this.bindings.push(binding)
        value.frame.addEventListener("click", binding);
    });
};

destroy = () => {
    this.bindings.forEach((binding) => {
        value.frame.removeEventListener("click", binding);
    });
    delete this.bindings;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM