melt-ui / runes

Experimenting what Melt will look like with Runes
44 stars 1 forks source link

Improve Auto Cleanup Logic #11

Open abdel-17 opened 3 months ago

abdel-17 commented 3 months ago

Currently, we auto cleanup effects by calling onDestroy in a try { ... } block with an empty catch {} to avoid errors when a melt component is created outside of a .svelte file. This is error-prone, however.

An admittedly hacky, but less error-prone alternative, is to first check if we can safely call onDestroy by calling an $effect with a noop.

function canSafelyCleanup() {
    try {
        $effect(noop);
        return true;
    } catch {
        return false;
    }
}
abdel-17 commented 2 months ago

Alternative suggestion: Don't rely on $effect.root. If you want to use a builder outside of Svelte components, you can wrap it with $effect.root manually. Maybe we can provide it as a separate helper.

let tooltip: Tooltip;

$effect.root(() => {
  tooltip = new Tooltip();
});