Last Updated: February 25, 2016
·
6.21K
· ram9cc

Ember JS Nested Routing & Outlets Pattern ( Baking Goodies )

Source Code for Example

Link

What's to learn here?

Ember generates a Controller and a View for a Resource that can be used with a Custom Router (which gives us a way to feed data to a template)

What style of problem am I trying to solve?

I have a bakery and I want to list my goodies.

Ember has a faculty to generate controllers and views based on a resource and a Route (a data source).

This is the basic setup that ember expects in order to use this pattern.

In my example - I want visiting the '/#/bakery' path to take the user to my bakery which is full of goodies!

Application template (needs an outlet)

<script type="text/x-handlebars" id='application'>
   <h2>Welcome to Shop Land</h2>

   {{outlet}}
 </script>

Bakery template (needs an outlet )

  <script type="text/x-handlebars" id="bakery">
At {{#link-to 'goodies' name}}"{{name}}" {{/link-to}}
    <br/>
    <!-- outlet is where goodies will appear (render) -->
    {{outlet}}
  </script>

Goodies template (renders in a outlet)

<script type="text/x-handlebars" id="goodies">
  You see the following goodies:
  <ul>
  {{#each item in model}}
    <li>{{item.name}}</li>
  {{/each}}
  </ul>
</script>

Set up a basic Ember app

App = Ember.Application.create();

Create a Router with resource 'bakery' at path "#/bakery"

Create a resource under bakery at path #/bakery/:bakery_id

App.Router.map(function() {
  this.resource('bakery', {path:'/bakery'}, function() {
    this.resource('goodies',{path:':bakery_id'})
  })
});

Create Route to the Bakery resource (model)
and design the route to transition to the goodies path

App.BakeryRoute = Ember.Route.extend({
  model: function() {
    return {name:'Yummy Land'};
  },
  afterModel: function() {
    this.transitionTo('goodies',this.model().name);
  }
});

Create a Route to the Goodies resource (model)

App.GoodiesRoute = Ember.Route.extend({
  model: function() {
    return [{name:'Eclair'},{name:'Donut'},{name:'Oatmeal Cookie'}];
  }
});

This collection of code ends up rending a page at the url "#/bakery/Yummy Land"
that looks like this.

Welcome to Shop Land

At "Yummy Land" 
You see the following goodies:
* Eclair
* Donut
* Oatmeal Cookie