codehugger
codehugger

Reputation: 639

How to add route or state to Ember.Router on runtime?

I have the following Ember.Router on my Application:

App.Router = Ember.Router.extend({
    location: 'hash',
    rootElement: '#content',
    enableLogging: true,

    root: Ember.State.extend({
        route: '/',

        index: Ember.State.extend({
            route: '/',
            redirectsTo: 'main.welcome'
        }),

        main: Ember.State.extend({
            route: '/main',

            welcome: Ember.ViewState.extend({
                route: '/welcome',
                view: App.WelcomeView
            })
        })
    })
});

What I want to be able to do is add additional routes by adding to the App.Router after it has been declared (this is to enable arbitrary modules). Whether it is done before or after App.initialize() is unimportant.

Here is an example on how the module route object would look like:

Module.routes = Ember.State.extend({
    route: '/module',
    index: Ember.State.extend({
        route: '/'
        view: Module.IndexView
    })
});

Any help on the matter is much appreciated.

Upvotes: 2

Views: 1093

Answers (1)

Stéphane Blond
Stéphane Blond

Reputation: 810

You may extract the state you want to enrich, so that you can reopen it later.

App = Ember.Application.create();

App.RootState = Em.State.extend({
    index : Em.State.extend({
        route : '/'
    }),
    main: Em.State.extend({
        route : '/main',
        index : Em.State.extend({
            route : '/'
        })
    })
});

App.Router = Ember.Router.extend({
    location : 'hash',
    enableLogging : true,
    root : App.RootState
});

// later...

App.RootState.reopen({
    module: Em.State.extend({
        route : '/module',
        index : Em.State.extend({
            route : '/'
        })
    })
});

App.initialize();​

EDIT: I use the latest version on GitHub

Upvotes: 5

Related Questions