How to intercept a willTransition even outside of the route

This is my scenario. Whenever we leave a particular route I need to perform an action. However, this responsibility doesn’t belong to the route(s) in question. So I would rather add an event like (desired API)

App.Router.on('willTransition', {from: 'routeName'}, function () {
    // Do something here
});

A simple workaround is to handle the willTransition and delegate to the class, but as I said, I don’t want to couple these two. An alternative is to use a pub/sub like AmplifyJS, but I would rather not introduce another library if I could rely on EmberJS events to do this. Any idea?

I found some good references, but still no answer to my question.

All actions will bubble up to the application route. Just return true if you’re implementing willTransition anywhere else to allow it to bubble.

App.ApplicationRoute = Ember.Route.extend({
    actions: {
        willTransition: function () {
            // logic here
            console.log('will transition');
        }
    }
});

Example: Ember Latest - JSFiddle - Code Playground

But in your question you are asking, “whenever we leave a particular route I need to perform an action.” That’s a little different then willTransition, as willTransition happens /before/ the transition takes place and can be aborted.

App.Router = Ember.Router.extend({
    logTransition: function (transition) { 
        console.log(transition);
    }.on('didTransition')
});

Thanks. I didn’t think of using ApplicationRouter as the glue. I could probably extend it to provide “events” that others can subscribe and treat it as the bus.

I’m not sure about your last example, didTransition only works on routes, but from your example it seems like you’re binding handling it on the router. Does that work?

BTW, the jsfiddle doesn’t show any routes.

Argh, forgot to click update…

Update showing the last example working Ember Latest - JSFiddle - Code Playground

1 Like

Thanks. I think that’s a nice place to decouple it. Thanks for the pointer