Getting Started with Ember.js Part 2: The List View


table display cars

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

View on 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:

table display cars

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


Advertisement

No Comments

Name
A name is required.
Email
An email is required.
Site
Invalid URL

No comments yet