mardi 16 octobre 2018

Where do I add and remove event listeners in the Ember controller life cycle?

If I want to listen for certain events or callbacks only on a certain route, and stop listening when not on that route. Where would I write that code?

There are a lot of hooks and events in an Ember component life cycle, but I cannot find any documentation on where to listen and unlisten for route-specific events or callbacks.

An example would be Listening to GPS coordinates:

// Listen
this.set('watch', navigator.geolocation.watchPosition(navigator.geolocation.watchPosition(watchFn))

// Unlisten
navigator.geolocation.clearWatch(this.get('watch'))

(Note that I want to listen on the route/controller, not on a component.)

First thought is to set the watch at __init(), but the controller is a singleton so this will fire only once.

Second thought is to set actions for activate() and deactivate() in the route, but they don't seem to fire so they are not what I think they are.

Then there is setupController() and resetController(). The resetController() seems to work reliably indeed and fires every time I leave the route. But setupController() also seems to fire only once. Which might make sense, since the controller is a singleton.

Then I thought I could use willTransition() or didTransition() in stead of setupController(). They work as expected for starting the listeners when navigating to a different route first.

But when I navigate away to a route that redirects back to this route, although both hooks executed, it seems like resetController() is fired after didTransition(). I'm not sure if that's what happens, but the effect is the same: The listeners stop listening, but they don't start listening. If I navigate away to an unrelated route and back again, the listeners will be activated again.

I'm stuck in the maze of possibilities.

  1. How can I achieve this? (I assume this is a normal approach. But if not: I'm out of time. Willing to do ugly hacks at this point.)
  2. Is there a best practice and/or "Ember way" to achieve this type of on(x) off(x) behavior?



Aucun commentaire:

Enregistrer un commentaire