Ember.js shows default nested route if none are provided

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

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

The router mapping looks something like this:

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

If the user goes to /item , I want to display a specific entry (for example, /item/my-first-item ). I can do this using the route redirect method:

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

Unfortunately, with this approach, if I manually enter the address bar URL /item/another-item or go directly to /item/another-item , the application will redirect me to /item/my-first-item . If I just switch between nested routes (i.e. by clicking the link in the application, it loads correctly).

How can I redirect redirection only when the nested route was not provided?

+4
source share
3 answers

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

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

Update for ember-cli and pods framework

Mike Grassotti's answer is still correct, but I also wanted to add an update on how to achieve this in Ember 2.x with ember-cli when using the new pods application structure. When using containers, you need to create the index folder inside the desired module, and then you can put the route.js file inside this index folder so that the recognizer 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 above will look something like this:

 import Ember from 'ember'; var ItemIndexRoute = Ember.Route.extend({ redirect: function() { this.transitionTo('my-first-item'); } }); export default ItemIndexRoute; 
+3
source

FYI, according to official Ember 2.6 documentation

The nested router is as follows:

app/router.js

 Router.map(function() { this.route('posts', function() { this.route('favorites'); }); }); 

It is equivalent to:

app/router.js

 Router.map(function(){ this.route('index', { path: '/' }); this.route('posts', function() { this.route('index', { path: '/' }); this.route('favorites'); }); }); 
0
source

Source: https://habr.com/ru/post/1501209/


All Articles