Getting Started with Ember.js Part 2: The List View
In the last post, we set up Rails to serve up a list of cars. Now let’s hook up Ember to display that data.
Getting Started with Ember.js
- Part 1: Project Setup -> Github: one two three
- Part 2: The List View -> Github
- Part 3: Showing a Single Car -> Github
- Part 4: Creating a New Car -> Github
- Part 5: Deleting a Car and Wrapup -> Github
Let’s start off by adding the model that describes the Car. Add a new file in app/assets/javascripts/models/Car.js
Cars.Car = DS.Model.extend({
make: DS.attr('string'),
model: DS.attr('string'),
color: DS.attr('string'),
condition: DS.attr('string')
});
Add a route for the index view that uses Ember Data to find the list of cars. Note that you could certainly use JQuery’s getJSON instead.
Create a new file: app/assets/javascripts/routes/CarsRoutes.js. Add the index route and associate it with the Car model. findAll is part of the Ember Data API; you could just as easily replace that with a JQuery getJSON call or any other method of issuing and HTTP call. It should look like this:
Cars.CarsIndexRoute = Ember.Route.extend({
model: function() {
return this.store.findAll('car');
}
});
Add the resource route in app/assets/javascripts/router.js. We’ll include more routes in the empty function later. Make sure it’s there since it changes how the routes are registered. Just leave it empty for now.
Cars.Router.map(function() {
this.resource('cars', function() {
});
});
Finally, add the index template in app/assets/javascripts/templates/cars/index.js.hbs
<div id="cars-index" class="panel">
<h1>Cars</h1>
<table role="grid">
<thead>
<tr>
<th>Make</th>
<th>Model</th>
<th>Color</th>
<th>Condition</th>
</tr>
</thead>
<tbody>
{{# each car in model}}
<tr>
<td>{{car.make}}</td>
<td>{{car.model}}</td>
<td>{{car.color}}</td>
<td>{{car.condition}}</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
That’s it for the list view! Visit localhost:3000/#/cars and it should look like this now:

Now that you’ve got the index working, head on to Part 3: Showing a Single Car.

No Comments
No comments yet