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

Could store.observer be automatically cancelled on component destruction? #1181

Closed
aphitiel opened this issue Feb 21, 2018 · 6 comments
Closed
Labels

Comments

@aphitiel
Copy link
Contributor

aphitiel commented Feb 21, 2018

When destroying a component, observers observing component state get cancelled automatically while observers on store stay alive.

oncreate() {
  this.observe(...  // Gets cancelled
  this.store.observe(... // Stays alive

This came as a surprise to me, with a bit of foot-gun potential. Would it make sense to autocancel store-observers, too?

Here is a slightly contrived REPL. Nested.html has observers spammig the console. The store.observer keeps logging after pressing the button.

@Rich-Harris
Copy link
Member

I'm not sure there's a good way to achieve this — when you call this.store.observe, the store has no way of knowing which component called it, so there's no way to remove the observer when the component is destroyed. It's basically like any other listener on an external object, you have to remove it manually:

oncreate() {
  const observer = this.store.observe('foo', ...);
  this.on('destroy', observer.cancel);
}

@Conduitry
Copy link
Member

I was thinking it's possible maybe to monkeypatch the instance of store that each component gets. But that does seem fairly ugly. It's probably best to make component authors deal with this, or perhaps to provide something in svelte-extras that registers an observer and automatically deregisters it when a particular module is destroyed.

@ekhaled
Copy link
Contributor

ekhaled commented Feb 24, 2018

Can we not do this.observe('$foo', ....)?

@Rich-Harris
Copy link
Member

@ekhaled's suggestion should work, but doesn't (in dev mode, at least) due to a bug: https://svelte.technology/repl?version=1.55.0&gist=7a951686a98f98bfad9c21d240ade73b

Monkey-patching would be a bit gross — I think this.on('destroy', observer.cancel) is a reasonable expectation.

Rich-Harris added a commit that referenced this issue Feb 24, 2018
allow observing $foo in dev mode
@Rich-Harris
Copy link
Member

Fixed the bug with observing $foo in dev mode, so I think we should close this.

@aphitiel
Copy link
Contributor Author

Perfect, thanks a lot! Observing $foo actually was the first thing I tried, but didn't see it in the docs. Glad it's supposed to work!

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

No branches or pull requests

4 participants