sveltejs / v2.svelte.dev

The Svelte v2 website
https://v2.svelte.dev
MIT License
210 stars 78 forks source link

Document DOM manipulation/access in `onstate` #348

Open kaisermann opened 6 years ago

kaisermann commented 6 years ago

Related to: https://github.com/sveltejs/svelte/issues/1522#issuecomment-413282000

My first attempt:

...
<script>
  export default {
    onstate({ changed, current, previous }) {
      /**
       * This fires on every state change, before the render.
       * The first time it runs, `previous` is undefined.
       *
       * Since this happens before the actual render, any manual
       * DOM access/manipulation should be done in the 'onupdate' lifecycle.
       */
      if (changed.time) {
        console.log(`time changed: ${previous && previous.time} -> ${current.time}`);
      }
    },

    oncreate() {
      /** This fires when the component has been rendered to the DOM */
      console.log('in oncreate');

      this.interval = setInterval(() => {
        this.set({ time: new Date() });
      }, 1000);
    },

    onupdate({ changed, current, previous }) {
      /**
       * This fires after 'oncreate', and after every state
       * change once the DOM is synchronised with the data
       */
      console.log(`The DOM has been updated`);
    },

    ondestroy() {
      /** This fires when the component is removed from the DOM */
      console.log('in ondestroy');

      clearInterval(this.interval);
    }
  }
  ...
</script>

cc @jacwright

jacwright commented 6 years ago

This looks correct and works for me in the REPL. I'm not sure what the issue is. Could you elaborate?

kaisermann commented 6 years ago

Oh my bad, it's an attempt to document what was said at https://github.com/sveltejs/svelte/issues/1522. Maybe I should've made a PR instead...