CustomElement.svelte
<svelte:options tag="custom-element" />
<script>
import { onMount, onDestroy } from "svelte";
onMount(() => {
window.addEventListener("scroll", funcRef);
});
onDestroy(() => {
window.removeEventListener("scroll", funcRef);
});
const funcRef = (event) => {
doWhatever();
}
</script>实际上,当自定义元素从文档中移除时,应该删除事件处理程序,但它不会。我遗漏了什么?
发布于 2022-07-28 15:32:02
发布于 2022-07-28 15:42:19
您提供的代码将正常工作,当组件被销毁时,它将自动删除事件侦听器,但是这里有一个更好的版本。
<svelte:options tag="custom-element" />
<script>
import { onMount} from "svelte";
onMount(() => {
const funcRef = (event) => {
doWhatever();
}
window.addEventListener("scroll", funcRef);
return ()=>{
// this function is called when the component is destroyed
window.removeEventListener("scroll", funcRef);
}
});
</script>发布于 2022-11-04 15:57:57
我想你可以用
<svelte:window
on:scroll={funcRef}
/>如本例所示,https://svelte.dev/repl/30667c29ab92487597f7e845578f263a?version=3.52.0
https://stackoverflow.com/questions/73154257
复制相似问题