A Programmer's Dream

Learning Ember in VS Code -- The First Route

Posted by Stephen Wrighton on 18 Sep 2018


This is my continuing efforts to work with the Ember JS (www.emberjs.org) Framework. The expectation is to build a simple wish list of items.  Part one started the Ember application, while today's section works on adding the first route to the system, where we display a list of items.
The first thing to do is modify the Application.hbs file (found in app/templates/application.hbs) and replace its contents with the below. 

1
2
3
<h1>Wish List</h1>

{{outlet}}

Now, we want to add a route to the system, specifically a route which provides a list of products that need to be shown. Luckily, Ember has a number of generators that make the creation of boilerplate code for common tasks simple and easy.  What this means in practice is that we need to run the below command inside our current Ember application's directory


1
ember generate route items

This command generates the template seen when the user visits the "/items" route, the actual route logic in the application router, and a route object which fetches the model to be used by the template. And you get a unit test. 
So, our first step is to go manipulate the template.  Open the "items.hbs" file found in app/templates and and an h2 tag with the text "Items."  An {{outlet}} line should already exist, and needs to remain for right now. 
After saving, you will be able to navigate to http://localhost:4200/items, and see the new page.
Of course, a template is not much use without the model to display the details of.  So, let's open up the items.js file from the "app/routes" folder.
The boilerplate has an import statement, and the standard extension statement.  We need to add a "model" method. The important part here is that the model method supports any library that uses JavaScript promises. For now, though, we just want to return a simple array.  So, modify the code until it looks like the below:

1
2
3
4
5
6
7
import Route from '@ember/routing/route';

export default Route.extend({
model() {
return ['Friday', 'Dragon Riders of Pern', 'Foundation', 'Ringworld', 'RAMA'];
}
});

Once that's changed, then the model is returning an array of items. In this case, a list of book titles.  Our next step is to tell Ember  how we want to display the array. We need to return to the items template, and add the code to make the program loop through the array and print its contents. 

1
2
3
4
5
6
7
<h2>Items</h2>

<ul>
{{#each model as |item|}}
<li><cite>{{item}}</cite></li>
{{/each}}
</ul>

So, using the "each" helper, we create a list of book titles, also notice the use of the "CITE" tag to emphasis that his is a title. 

Tweet me @kidananubix if you like this post.

Tweet