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

destroy() does not have access to the current scope. #2693

Closed
hirasso opened this issue Feb 22, 2022 Discussed in #2103 · 2 comments
Closed

destroy() does not have access to the current scope. #2693

hirasso opened this issue Feb 22, 2022 Discussed in #2103 · 2 comments

Comments

@hirasso
Copy link

hirasso commented Feb 22, 2022

Discussed in #2103

Originally posted by bep September 21, 2021
So, custom data components can have a destroy() function, which is great.

I would expect to use this for cleaning, e.g. helping the Garbage Collector do its job. But the this does not seem to be the same as the data this.

Opening an issue for this, since it would open the door to a lot of great functionality to be able to access the scope from inside the destroy() directive.

@AugustMiller
Copy link

AugustMiller commented Feb 26, 2022

A brilliant user in the Discord server helped me with a similar question, yesterday—hopefully this will help unblock someone else who is interested in this "cleanup" process!

The key here is to avoid the "implicit return" factory function that the docs provide, as it starves you of space to do "setup" logic, or to store “non-state” data:

Alpine.data('my-component', () => ({ // Implicitly returned object, not a function body!
  init () {
    this.interval = window.setInterval(() => {
      console.log('Tick!');
    });
  },
  destroy () {
    window.clearInterval(this.interval); // Uh oh!
  },
}));

Instead, open a regular function body:

Alpine.data('my-component', () => {
  // Stuff available across all methods, and to destroy():
  let interval;
  let myObject;

  // Component definition, same as the implicit return from the first example:
  return {
    init () {
      myObject = new SomeBigScaryObject();

      interval = window.setInterval(() => {
        console.log('Tick!');
      }, 1000);
    },
    destroy () {
      window.clearInterval(interval);
      myObject.someDeInitMethod();
    },
  };
});

🌳

@AugustMiller
Copy link

Looks like this behavior was revised in #2733!

@hirasso hirasso closed this as completed Apr 9, 2022
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