The next step
is to get data to each route using the route’s model
callback. Each Ember.Route
has a method to
assign a model (which, remember, is the data backing the template) to a controller.
This method, called model,
returns data as a Promise
.
Under the hood, the Ember app initializes the Route
object
when the URL changes. This Route
object has four hooks
to set itself up: beforeModel, model,
afterModel, and setupController.
We will focus on the model callback for now.
Add some dummy data in the model callback in the SightingsRoute
,
app/routes/sightings.js:
import Ember from 'ember'; export default Ember.Route.extend({ model(){ return [ { id: 1, location: 'Asilomar', sightedAt: new Date('2016-03-07') }, { id: 2, location: 'Asilomar', sightedAt: new Date('2016-03-07') }, { id: 3, location: 'Asilomar', sightedAt: new Date('2016-03-07') }, { id: 4, location: 'Asilomar', sightedAt: new Date('2016-03-07') }, { id: 5, location: 'Asilomar', sightedAt: new Date('2016-03-07') }, { id: 6, location: 'Asilomar', sightedAt: new Date('2016-03-07') } ]; } });
Notice the syntax of the model hook:
model() { [your code goes here] }
This is ES6 shorthand for:
model: function() { [your code goes here] }
Throughout the next chapters you will be using this syntax to define your object methods in Ember.
The model callback is a place to retrieve
data needed to render a template. The route lifecycle methods in an
Ember.Route
return objects for each hook. The
model hook will eventually return data to a
setupController hook, which sets a property named model
on SightingsController
. You can access this data
in your templates: app/templates/sightings.hbs
and app/templates/sightings/index.hbs.
Edit app/templates/sightings/index.hbs as shown. We will explain the code after you enter it.
<h1>Index Route</h1><div class="panel panel-default"> <ul class="list-group"> {{#each model as |sighting|}} <li class="list-group-item"> {{sighting.location}} - {{sighting.sightedAt}} </li> {{/each}} </ul> </div>
This code might look strange if you have never used template languages.
The words in the double curlies ({{ }}
) are essentially
JavaScript functions disguised as statements. In English,
these lines say, “For each sighting
in the
model
property (which is expected to be an array), render an
<li>
element with the sighting
’s
location
and sightedAt
date.”
You will learn about {{ }}
syntax in general and {{#each}}
in particular
in Chapter 23.
Switch to http://localhost:4200/sightings in your browser, where your app should look like Figure 20.7.
You have now completed the first half of the route cycle by passing data to the template for it to display. In the next chapter, you will explore the Handlebars templating language. This language allows you represent the state of your application with properties from a controller, rendering only necessary DOM elements as the state of the application changes.
3.143.5.201