Tiago Conceiçao
Tiago Conceiçao

Reputation: 467

How to run an action on every route transition in ember?

I have an Ember application with several routes and I want to scroll the page to top every time the user makes a transition. The problem is that I don't want to duplicate the same code on every route's didTransitionmethod.

So, Is there a way that I can observe all routes transitions and execute (declare) an action in just one place ?

Another way to put put this: If I have a parent route, can I fire the same action to all of its children ?

My current solution is to fire the action on every route's didTransition method like this:

//router.js
Router.map(function() {
  this.route('login');
   this.route('portal',{ path:'/'}, function() {
      this.route('clientes');
      this.route('convite');
      this.route('usuario', function() {
      this.route('view', { path: '/:id' });
  });
 });

 //everyChildren.route.js
 didTransition(){
   this.super(...arguments);
   Ember.$("html, body").animate({ scrollTop: 0 }, "slow");
 }

Is there a way to do this ?

PS:. I am using Ember version 2.14.0

Upvotes: 1

Views: 1360

Answers (2)

Lux
Lux

Reputation: 18240

Use ember-router-scroll.

This addon does what you want

Upvotes: 0

Gennady Dogaev
Gennady Dogaev

Reputation: 5991

You can try to define didTransition action on application route. If child route does not define handler for event, it should bubble up to parent route and application is a most top route.

Alternatively, you can create a mixin with didTransition action, and add that mixin to certain routes.

Also, looking at your code I think you might be interested in using liquid-fire addon (if your goal is animated transitions)

Upvotes: 2

Related Questions