0

An instance of an imported library (ScrollMagic) in the script tag of one page in Sapper, the instance keeps existing when navigating to other pages.

I tried destroying it within ondestroy, but I can't reference the variable referencing the instance (created wihtin oncreate).

How can I either scope the script tag to individual pages, or destroy the instance when leaving the page?

4

1 回答 1

0

You have two ways of accessing things in ondestroy that were created in oncreate. The first is to add them as properties of the component:

<script>
  import ScrollMagic from 'scrollmagic';

  export default {
    oncreate() {
      this.controller = new ScrollMagic.Controller(...);
      this.scene = new ScrollMagic.Scene(...);
    },

    ondestroy() {
      this.controller.destroy();
      this.scene.destroy();
    }
  };
</script>

The second is to use the this.on("destroy", ...) form:

<script>
  import ScrollMagic from 'scrollmagic';

  export default {
    oncreate() {
      const controller = new ScrollMagic.Controller(...);
      const scene = new ScrollMagic.Scene(...);

      this.on('destroy', () => {
        controller.destroy();
        scene.destroy();
      });
    }
  };
</script>
于 2018-05-02T17:43:15.587 回答