How to intercept a willTransition even outside of the route


#1

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.


#2

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: http://jsfiddle.net/NQKvy/

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')
});

#4

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.


#5

Argh, forgot to click update…

Update showing the last example working http://jsfiddle.net/NQKvy/1348/


#6

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