Search code examples
ember.jsember-old-router

How to use multiple router objects in ember.js


I'm still new to ember.js but one part of the framework that I'm yet to see at scale is the basic Ember Router. In a small single page app you have just one router that manages all the state / routes / etc. But as your app grows how do you manage complexity if the pattern seems to focus around just 1 object?

Curious if this is just something I've overlooked or if this is assumed to be a massive global state management object like the AppDelegate in iOS for example.


Solution

  • I don't know if my way is the generally accepted best practice, but I do know that when the router gets big that it should be split into multiple files. I accomplished that like this:

    app_router.js

    App.Router = Ember.Router.extend({
      enableLogging: true,
      root: Ember.Route.extend({
        route: '/',
        index: Ember.Route.extend({
          route: '/',
          redirectsTo: 'app.index'
        }),
        app: Ember.Route.extend({
          route: '/app',
          showProfile: Ember.Route.transitionTo("user.index"),
          index: Ember.Route.extend({
            route: '/',
            redirectsTo: 'items'
          }),
          items: App.ItemsRoute,
          item: App.ItemRoute,
          users: App.UsersRoute,
          user: App.UserRoute,
          hashtagbrand: App.HashtagbrandRoute
        })
      })
    });
    

    items_router.js

    App.ItemsRoute = Ember.Route.extend({
      route: '/items',
      connectOutlets: function(router, items) {
        router.get("applicationController").connectOutlet({
          name: 'carouselContainer',
          outletName: 'carousel',
          context: App.store.find(App.Item)
        });
        router.get("applicationController").connectOutlet({
          name: 'logo',
          outletName: 'header'
        });
      },
      index: Ember.Route.extend({
        route: '/'
      })
    }); 
    
    
    App.ItemRoute = Ember.Route.extend({
      route: '/items/:id',
      //...
      index: Ember.Route.extend({
        route: '/'
        //...
      })
    });