Why do I need to define an index route in Ember.js?

Earlier my routes were defined:

this.route('username', {
  path: '/:username'
}, function() {
  this.route("room", {
    path: "/:room",
});

      

I changed it to:

this.route('username', {
    path: '/:username'
  }, function() {
    this.route('index')
});
this.route("room", {
  path: "/:room"
});

      

This works great. But my route is username/index

not loading unless I explicitly specify an index in router.js

.

Below will not be :

this.route('username', {
  path: '/:username'
});
this.route("room", {
  path: "/:room",
});

      

Is this normal behavior?

+3


source to share


1 answer


If a route

has a nested route

s, it is assumed that a route exists for the parent index

. This refers to this in the manual: https://guides.emberjs.com/v2.13.0/routing/defining-your-routes/#toc_index-routes

In particular, the key phrase:

At every nesting level (including the top level), Ember automatically provides a route for the / path named. To see when the next level of nesting occurs, check your router when you see the feature to the next level.

So, in your example, because it is room

nested in username

then username

gets an automatic route index

. When you removed room

from nesting, the default route index

for username

disappeared.

FYI, you don't even need to specify a pointer route, just put in an empty callback. eg:.

this.route('username', {
    path: '/:username'
  }, function() {});

      



This will work the same way, automatically creating a route username/index

.

In one of my early Ember (1.x) apps, I wanted the index route to always be there, regardless (for consistency), so I defined a variable:

var NO_CHILDREN= function() {};

      

Then I could write my routes, for example:

this.route('username', {
    path: '/:username'
  }, NO_CHILDREN);

      

Hope it helps

+3


source







All Articles