Ember.js: Tutorial — Part 1: Working With Data

Lessons

  1. Work with a route file
  2. Return local data from model hook
  3. Access route model from template
  4. Mock server data with static JSON file
  5. Fetch remote data from model hook
  6. Adapt server data
  7. Loops and local variables in a template with {{#each}}

1-2. Work with a route file

IMPORTANT

This section include lessons for:

  • 2. Return local data from model hook

1-2.1. Generate index route

NOTE

Select n for ? Overwrite app/templates/index.hbs? prompt.

1-2.2. Edit index route

NOTE

  • Route's file fetches data and loads it into route
  • async method model() is also known as model hook
    • It fetches and prepares data needed by route
    • It is automatically called when a route is visited
    • Object returned is the model of route
    • async enables use of await keyword for fetching data to finish

3. Access route model from template

3.1. Edit index template

NOTE

Route's model can be accessed from template with @model.

3.2. Re-edit index template

NOTE

Remove previously written <h1>{{@model.title}}</h1>.

3.3. Edit rental component

3.4. Edit rental component test

NOTE

  • A component test is rendered and tested in isolation
    • It does not route and has no access to data returned by model hook
  • this.setProperties feeds component with data similar from a route

3.5. Run rental component test


4. Mock server data with static JSON file

4.1. Download data.zip

NOTE

Visit localhost:4200/api/rentals.json to view JSON data.


5. Fetch remote data from model hook

5.1. Edit index route

NOTE

  • Fetch API
    1
    fetches data asynchronously
    • It also returns a response object asynchronously
    • It must be paired with await keyword to consume its data
    • Parsing its response data is also asynchronous (so await is also used)

6. Adapt server data

6.1. JSON:API

  • The structure of JSON file follows
    JSON:API
    2
    format
    • It returns an array nested under data key
    • Every object in this array has a type and id
    • Important data are nested within attributes key

6.2. Edit index route


7. Loops and local variables in a template with {{#each}}

7.1. Edit index template

NOTE

  • Visit localhost:4200 to see a dynamic rental list
  • {{#each}}…{{/each}} loops through an array returned by model hook
    • Each iteration returns a block that can be aliased
      • e.g. |rental|
    • Inside each block, its aliased block can be accessed
      • e.g. {{rental}}

References

Show Comments