Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ember.js show default nested route if none provided

Tags:

ember.js

In my ember app (1.0.0 production version) I have a URL structure as follows:

/item
/item/{specific-item-name-defined-in-routes}

The Router mapping looks a little like this:

App.Router.map(function () {
    this.resource("item", function () { 
        this.resource("my-first-item");
        this.resource("another-item");
        ...
    });
});

If the user navigates to /item I want to display a specific post (e.g. /item/my-first-item). I can do this by using the redirect method of the route:

App.ItemRoute = Ember.Route.extend({
    redirect: function () {
        this.transitionTo('my-first-item');
    }
});

Unfortunately with this approach if I manually type into the address bar the URL /item/another-item or navigate directly to /item/another-item the app redirects me to /item/my-first-item. If I just change between nested routes (i.e. by clicking a link in the app it loads correctly).

How can I get the redirection to work around only when a nested route has not been provided?

like image 980
will-hart Avatar asked Sep 08 '13 22:09

will-hart


2 Answers

Instead of redirecting the item route, add the redirect hook to (the automatically generated) ItemIndexRoute:

App.ItemIndexRoute = Ember.Route.extend({
  redirect: function () {
    this.transitionTo('my-first-item');
  }
});
like image 168
Mike Grassotti Avatar answered Oct 30 '22 11:10

Mike Grassotti


Update for ember-cli and pods structure

Mike Grassotti's answer is still correct but I wanted to also add an update about how to achieve this in Ember 2.x with ember-cli when using the new pods application structure. When using pods you need to create an index folder inside of the desired pod and then you can place a route.js file inside that index folder so the resolver can find it.

Example Directory / File Structure

 pods
  ├─ application
  │   ├─ route.js
  │   ├─ controller.js
  │   └─ template.hbs
  └─ item
      ├─ index
      │    └─ route.js
      ├─ my-first-item
      │    ├─ route.js
      │    ├─ controller.js
      │    └─ template.hbs
      └── another-item
           ├─ route.js
           ├─ controller.js
           └─ template.hbs

Example route.js

The pods/item/index/route.js file from above would be something like:

import Ember from 'ember';

var ItemIndexRoute = Ember.Route.extend({
  redirect: function() {
    this.transitionTo('my-first-item');
  }
});

export default ItemIndexRoute;
like image 29
munsellj Avatar answered Oct 30 '22 12:10

munsellj