[英]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.我想知道是否将
undefined
分配给元素的事件,即on:mousemove
是否像removeEventListener
一样防止 memory 泄漏,或者至少从长远来看不应该是一个问题。 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.我已经在 chrome 上使用
getEventListeners
进行了检查,它与on:mousemove
方法一起使用,但我不确定我是否应该担心这一点并使用自定义操作的更冗长的方法。
I have a Dropdown inside a Container.我在容器中有一个下拉列表。 On moving the mouse over the container, I want to change the Dropdown's position.
将鼠标移到容器上时,我想更改下拉列表的 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.我最初的方法是编写一个自定义 use:containerMouseMove 操作,它将 Dropdown 的可见作为依赖项,并在 Dropdown 变得不可见时从容器中删除事件侦听器。
Dropdown.svelte:下拉列表.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.然后我了解了 export const function 作为父子之间通信的一种方式,它简化了代码。 But I'm not sure if there's not a memory leak right now.
但我不确定现在是否没有 memory 泄漏。
on:mousemove={dropdown.getVisible() ? dropdown.onContainerMouseMove : undefined}
onContainerMouseMove
is the callback inside on:mousemove_container
. onContainerMouseMove
是on:mousemove_container
里面的回调。
on:event
listeners are removed automatically when the component is unmounted. on:event
监听器在组件卸载时自动移除。
Within actions, one should return an object with a destroy()
function and unsubscribe from events there.在操作中,应该返回一个带有
destroy()
function 的 object 并取消订阅那里的事件。 The function will be called when the element with the action on it is removed.当带有操作的元素被移除时,将调用 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.