Monday, October 1, 2018

Learning Ember in VS Code -- Adding a Component

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, part two started our first route  and part three added a Click Event to the code. Today's section works on adding a component to the system to allow for shared user interfaces.

As a programmer, I have to say that Ember components are awesome. These are user interface elements that can be shared in different places in the application. This means either on separate and distinct pages or multiple times on the same web page.

In this situation, I want to turn my list of items into an "item-list" template. Again, Ember has a generator to perform the slog work of boilerplate coding for you.

1
ember generate component item-list

This generator creates:
  1. a component JavaScript class (in app\components)
  2. the component's template (in app\templates\components)
  3. And of course a Unit Test
The first thing we need to do is move the code from our items route template over to our new item-list template. Next we want to parameterize the H2 element with the 'title' attribute. The final change is to modify the word model to the attribute "items."

The code in the item-list component template should read:

1
2
3
4
5
6
7
<h2>{{title}}</h2>

<ul>
    {{#each items as |item|}}
    <li {{action "showItem" item}}><cite>{{item}}</cite></li>
    {{/each}}
</ul>

We also have to remember that the LI has an action associated with it. Thus, we need to move that action from the items route class to the item-list component class.

So, the item-list.js file needs to look like this:

 1
2
3
4
5
6
7
8
9
10
import Component from '@ember/component';

export default Component.extend({

    actions: {
        showItem(item) {
            alert(item);
        }
    }
});

And the items.js file needs to end up looking like this:

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'];
    }     
});

Then we need to return to the item route template, and wire it up to display our new component element.

1
{{item-list title="List of Books" items=model}}

What's going on here, is that the double curly braces indicate that this is a component, specifically the "item-list" component. The title used is the value passed into that attribute, while the array of items to use is passed into the items attribute, and is the model of the particular page.

In truth, the end result of this should show the exact page as previously, but components are an important concept to know as they allow for code re-usability.

The next entry will see about including Bootstrap into the framework.

No comments:

Blog Widget by LinkWithin