Search code examples
ember.jsroutesrouterember-cli

How do I add or change routes on runtime in ember (ember-cli)


I'm building an application with ember-cli and want be able to change a route on runtime. Say we have the following router defined:

import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
  location: config.locationType
});

Router.map(function() {
  this.route('me');
  this.route('users', function() {
    this.route('user', {path:'/user_id'});
  });
});

export default Router;

After authentication, I want to change the path of the me route into the authenticated users id (or slug):

this.route('me', path:'/6');

This way I can have my navigation, including proper active states, like so:

{{link-to "me"}}Me{{/link-to}}
{{link-to "users"}}Users{{/link-to}}

I've read that you can run router.map() multiple times without overwriting previous routes but I can't figure out how the subsequent map call is made from another module than router.js.


Solution

  • First of all, I would highly recommend against this. Not only is it probably not supported by Ember and likely to cause a ton of issues, but there are many ways to handle this situation without dynamically altering the route structure.

    That being said, you can call map() from another module as you would from within the router module, just import the router first. As an example, if you were going to do it in the afterModel hook:

    import Router from '../router';
    
    export default Ember.Route.extend({
        model: function() {
            return this.getAndAuthenticateUser();
        },
        afterModel: function() {
            Router.map(function() {
                this.route('newlyDefinedRoute');
            });
        }
    });