Emberjs: Conditional redirect in router
Asked Answered
V

3

10

Is there a way to have a conditional redirect in the Ember.js Router, without breaking internal consistency of the router?

Valenti answered 25/6, 2012 at 14:9 Comment(2)
Can you explain a little more why you're transitioning to a different route from connectOutlets? (I'm kind of a noob in ember, so maybe I just don't understand what you're trying to do)Carob
By the way, routes now have a redirect: element you can override, it is in the current guide.Allround
V
23

What you could do (as of today), is something like that:

root: Ember.Route.extend({
    index: Ember.Route.extend({
        enter: function(router) {
            var logged = /* get from appropriated source... */;
            Ember.run.next(function() {
                if (logged) {
                    router.transitionTo('loggedIn');
                } else {
                    router.transitionTo('loggedOut');
                }
            });
        }
    }),

    loggedIn: Ember.Route.extend({
        // ...
    }),

    loggedOut: Ember.Route.extend({
        // ...
    })
})

Do not miss the Ember.run.next as while you are in enter, the state transition is always pending, so you have to transition after that.

We use it as shown for authent, but you could imagine using it for whatever condition you have to...

Valentin answered 25/6, 2012 at 15:36 Comment(3)
If you do it on connectOutlets instead of enter you shouldn't need the Ember.run.next.Civilly
do you have an example how to do it with connectOutlets?Whiting
Well, the code is exactly the same, except the wrapping inside Ember.run.next(function () { ... });Valentin
B
3

The new router now includes a

beforeModel 

hook which you could over-ride to include conditional logic while transitioning to a route. The beforeModel hook will be called before the

model 

hook is called and it gets passed a

transition

object. You can decide if you want to redirect to another route using

transitionToRoute()

or you could abort the transition if you don't want to redirect by calling

transition.abort()
Brockman answered 28/4, 2014 at 9:31 Comment(0)
K
2

Depending on what you're trying to do, you may be looking for conditional transitions. This is covered in another stackoverflow question, the TLDR of which is to check this fiddle.

Keniakenilworth answered 26/7, 2012 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.