Ember.js execute action when clicking browser back button

3.8k views Asked by At

I need to execute an API call when user clicks on the back button in the browser and then redirect to a route based on backend response. I've read about location API but I can't figure out how to distinguish between url changes due to clicks on link and url changes due to browser back button. Any suggestion is really appreciated.

2

There are 2 answers

0
GUL On BEST ANSWER

I've found a solution and share it here. I don't know if it's the best solution but it works for me.

I've created an array with the list of routes in the order they can be navigated, suppose it's ['route1', 'route2', 'route3', 'route4']. In my situation, a route can be skipped but order must be maintained. For example navigation path can be

route1 --> route2 --> route4

but not

route1 --> route4 ---> route3

Going from route4 to route3 can be done only using back action (browser button or in-page button).

In willTransition action for each of that route, I compare the index of the target route in the array with the index of the current route. If the first value is lower than the second one, the user is navigating back and then I can execute API call:

// environment.js
ENV.APP.routeList = ['route1', 'route2', 'route3', 'route4']

// route
App.Route1 = Ember.Route.extend({
    ...

    actions: {
        willTransition: function(transition) {
            var routeList = ENV.APP.routeList;
            if (routeList.indexOf(transition.targetName) < routeList.indexOf(this.get("routeName"))) {
                console.log("GO BACK");
                this.send("back");
            }
        }
    }
});
3
Kori John Roys On

I'd check out willTransition. Since your question doesn't give us a lot to work with, here's some pseudo code:

routes/some_route.js

export default Ember.Route.extend({
  actions: {
    willTransition: function(transition) {
      var route = this;
      backEndAjaxCall().then(function(response) {
        if (response.itsAGoodIdeaToTransition) {
          transition.abort();
          route.transitionTo("some_other_route");
        } else {
          // Bubble the `willTransition` action so that
          // parent routes can decide whether or not to abort.
          return true;
        }
      });
    }
  }
});