简体   繁体   中英

Svelte - on:event listener removal

I'm wondering whether assigning undefined to an element's event, ie on:mousemove prevents a memory leak the same as removeEventListener does, or at least should not be a concern long term. I've checked with getEventListeners on chrome, and it's there with the on:mousemove approach, but I'm not sure whether I should worry about this and use the more verobse approach with custom actions.

I have a Dropdown inside a Container. On moving the mouse over the container, I want to change the Dropdown's position.

My initial approach was writing a custom use:containerMouseMove action, that took Dropdown's visible as a dependency, and removed the event listener from the container, when the Dropdown became invisible.

Dropdown.svelte:

        use:mousemoveContainer={{ container, destroyOn: !visible }}
        on:mousemove_container={(e) => {
            if (mouseTrack) {
                [x, y] = calcCoordinates(e, container);
            }
        }}

Action definition:

type Deps = { container: HTMLElement; destroyOn: boolean };

export const mousemoveContainer = (node: HTMLDivElement, deps: Deps) => {
    const handleMouseMove = (e: MouseEvent) => {
        node.dispatchEvent(new CustomEvent('mousemove_container', { detail: e }));
    };
    return {
        update(deps: Deps) {
            if (!deps.destroyOn) {
                deps.container.addEventListener('mousemove', handleMouseMove);
            }
            if (deps.destroyOn) {
                deps.container.removeEventListener('mousemove', handleMouseMove);
            }
        }
    };
};

Then I learned about export const function as a way to communicate between parent and child, and it simplifies the code. But I'm not sure if there's not a memory leak right now.

    on:mousemove={dropdown.getVisible() ? dropdown.onContainerMouseMove : undefined}

onContainerMouseMove is the callback inside on:mousemove_container .

on:event listeners are removed automatically when the component is unmounted.

Within actions, one should return an object with a destroy() function and unsubscribe from events there. The function will be called when the element with the action on it is removed.

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