Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document DOM manipulation/access in onstate #348

Open
kaisermann opened this issue Aug 18, 2018 · 2 comments
Open

Document DOM manipulation/access in onstate #348

kaisermann opened this issue Aug 18, 2018 · 2 comments

Comments

@kaisermann
Copy link
Member

kaisermann commented Aug 18, 2018

Related to: sveltejs/svelte#1522 (comment)

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
Copy link
Contributor

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

@kaisermann
Copy link
Member Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants