williamngan/pts

Resetting space on hot reload?

pikeas opened this issue · 2 comments

With Svelte, I have this component:

<script>
    import {onMount} from "svelte"
    import {CanvasSpace, SVGSpace, } from "pts"

    let node: HTMLElement
    let space: CanvasSpace | SVGSpace

    onMount(() => {
        space = new SVGSpace(node).setup({ // tried SVG and canvas
        })

        const player = myFunction(space)
        space.add(player)
        space.bindMouse().bindTouch().playOnce(1000)

        return () => { // this runs on unMount
            // none of these help
            space.dispose()
            space.removeAll()
            Array.from(node.children).forEach((c) => c.remove())
            space = null
        }
    })
</script>

<div bind:this="{node}"></div>

In dev, Svelte hot reloads all changed files, including this component and imports. This triggers the unMount/onMount functions, which I expected to fully reset the space. Instead, Pts is retaining state somewhere. Is there a better way to reset everything?

SVG and canvas seem to have different behavior.

SVG: start() works including on remount, animate() doesn't.
Canvas: start() runs but no form functions do anything (even on first load), animate() works including on remount.

Thanks for reporting this. I probably need to look into Svelte a bit more to get a better sense.

One potential suggestion: Would it work better if you pass the animate as prop, instead of const player = myFunction(space) ? Eg,

export let animateFn;

onMount( () => {
   // ...
   if (animateFn) animateFn( space, form );
});