/ emberjs

Ember.js: How to track last visited route?

Recently, I added a global search feature in out Ember Application. As it was a global search, it was linked from most of the pages of the application.
User can click on search icon in the right-top corner and he will be redirected to search page.

But now how to go back to the page we came from? as User can go to search from any of the page of the application.

Here we will see how we can know about last visited route in ember application. We can find our previous route as follows:

import Ember from 'ember';

export default Ember.Route.extend({
  beforeModel: function() {
    var previousRoutes = this.router.router.currentHandlerInfos;
    var previousRoute = previousRoutes && previousRoutes.pop();
    if(previousRoute) {
      localStorage["lastVisitedRoute"] = previousRoute.name;
    }
  }
});

Here previousRoutes gives us the list of all the previous routes we have visited in current session.

In previousRoute, we are getting

< previousRoutes[3]
  C {
  context: Class, 
  name: "my_list.reviewed", 
  handler: Class, 
  params: Object, 
  factory: function…}

The name of route previousRoute.name we are going to store in localStorage here.

Instead of localStorage, we can also make use of controller-property and assign the route-name to controller-property in setupController hook.

Now at controller level:

We can implement an action, like here on click of cancel link, we will be returning back to the page we came from.

import Ember from 'ember';
export default Ember.Controller.extend({
  actions: {
    
    cancelSearch: function(){
      var route = localStorage["lastVisitedRoute"] || "my_list";
      this.transitionToRoute(route);
    },
  },
});

That's it!!

Swati Jadhav

I am a Rubyist, ROR developer, passionate about change and trying new things, both professionally and in general with life. Currently, working on Ember.js applications and fasci...

Read More