How to reset the EmberJS router namespace with this.route()

With this.route() being fully nestable as of Ember 1.7.0, the best practice has been to drop use of this.resource() altogether. I highly recommend always using this.route() for one reason in particular: preventing conflicting route names.

Example

In our sample app, we might have a route called workspaces, with an administrative area at admin.workspaces. If we were to follow the older convention of declaring any route with a noun as name as a resource, the route file should look like this:

// router.js using this.resource()

Router.map(function() {
  this.resource('workspace');
  this.route('admin', function () {
    this.resource('workspace');
  });
});

This router will generate route names of workspace, admin, and workspace.

Wait. Hold up. Two routes with workspace as the name?

You bet. Using this.resource() resets the namespace of the route. You can override the nested workspace route name by doing this.resource('admin.workspace', { path: /workspace }), but why bother when this.route() can take care of this for us?

// router.js using this.route()

Router.map(function() {
  this.route('workspace');
  this.route('admin', function () {
    this.route('workspace');
  });
});

Now we get generated route names of workspace, admin, and admin.workspace. Neat!

If in the event that you absolutely must reset the namespace of a nested route, you can use the { resetNamespace: true } option on the route.

// router.js using this.route() with reset namespace

Router.map(function() {
  this.route('workspace');
  this.route('admin', function () {
    this.route('workspace');
    this.route('project', { resetNamespace: true });
  });
});

We get the same three route names generated as the previous example, as well as a new route at project. That's right, no admin. is prepended. Resetting the namespace can be used prudently for lengthy route names. Be careful only to reset when you can guarantee that you'll likely never have a naming collision with another route.