-
When we reference non-Svelte objects in Svelte components, is it okay to mutate those objects from $effect, as well as subscribe to changes from Here is a an example in a playground to show what I mean. Changing a non-Svelte object from $effect: let emojisGen = new RandomEmojis();
let emojisCount = $state(9);
let interval = $state(3);
let showEmojis = $state(true);
$effect(() => {
emojisGen.setup(emojisCount, interval);
}); Subscribing to changes from a non-Svelte object: let emojis = $state(emojisGen.getEmojis());
$effect(() => {
emojisGen.observe(onNewEmojisGen);
return () => {
emojisGen.unobserve(onNewEmojisGen);
};
});
function onNewEmojisGen() {
emojis = emojisGen.getEmojis();
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Sure. Something similar to the (If the effect is not dependent on DOM state updates, you could switch to |
Beta Was this translation helpful? Give feedback.
Sure.
Something similar to the
observe
/unobserve
is often done with browser objects likeMutationObserver
/IntersectionObserver
. Or you have an object like aMediaQueryList
that dispatches events so you haveaddEventListener
/removeEventListener
.(If the effect is not dependent on DOM state updates, you could switch to
$effect.pre
.)