A Programmer's Dream

Learning Ember in VS Code -- The First Event!

Posted by Stephen Wrighton on 25 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, part two started our first route and today we're actually going to have the application do something by having it respond to a mouse click.


Currently, the application shows a list. Not exactly ground breaking, or very useful.  So, what we need is to make the system respond to user interaction. Since this is the web, that interaction is a click event.  

To accomplish this, we add an action to the list item element in the items template.  The action helper takes in the name of the function to run, and the paramters for that function. for this function we'll name it "showItem" (and notice the casing for expected JavaScript styling) and pass it the item object that's referenced in the #each helper.

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

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

The default behavior for the action helper is to add a click event listener to the associated HTML element. This means that clicking the LI element will call the showPerson function from the items route class.

This means we need to modify the items route class file to add this function definition. For now, all we'll do is use an alert dialog to display the book title, later we'll make changes to display more information about the item. 

 1
2
3
4
5
6
7
8
9
10
11
12
import Route from '@ember/routing/route';

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

So, now our application is actually doing something.
Ember Alert
Next time, we'll be introducing how to share things appropriately. 

Tweet me @kidananubix if you like this post.

Tweet