Tutorial Ember ( Version 1.13 ) ? Part 5

By | February 2, 2016

In the part 4 of this tutorial about the creation of a blog with Ember, we have started by build the blog administration. Today, we will see how to create a Ember component and when to use it.

Component :

Ember has recently change his model from a Template-View-Controller-Action paradigm to a Template-Component-Action paradigm. In Ember, a component can be seen as a small autonomous application with it own scope, it own template and soon it own rooting system with the arrival of Routable Components. Ember-cli give us a tool that is really easy to use to generate components, their templates and their tests classes. To generate one, type this command in the console :


ember generate component <component-name>

The component name must be “dasherized”. For example, bootstrap-table is a valide name whereas bootstrapTable is not. This rule is very importante because it let you create components that will not conflit with the future HTML components. To generate our bootstrap-table component, type this command in the console.


ember generate component bootstrap-table

This command will generate the following file :

  • app/components/bootstrap-table.js – Contains component mechanical
  • app/templates/components/bootstrap-table.js – The component template
  • test/integration/components/bootstrap-table.js – Contains the component tests

Here is the bootstrap-table.js file code :


import Ember from 'ember';

export default Ember.Component.extend({
    tagName: 'div',
    classNames: ['col-xs-12'],
    actions : {
        deleteAll() {
            var posts_id = [];
            this.$("input[type='checkbox']:checked").each(function() {
                var checkbox = Ember.$(this);
                checkbox.parent().parent().parent().parent().remove();
                posts_id.push(checkbox.attr('id'));
            });
            this.sendAction("deleteAction", posts_id);
        },
        add() {
            this.sendAction("addAction");
        }
    },

    __init : function() {
        console.log("Init bootstrap-table");
    }.on('didInsertElement')
});

The first thing to note is that our component extends from Ember.Component. This class let you customize your components with some attributes.

  • tagName – Let you define the html tag which will be the root of your component. This tag will contain all the template of your component.
  • classNames – Lets you add some CSS classes to your component. Note that Ember accept classes defined at the call of the component in the application template by the HTML class attribute.
  • classNameBinding – Lets you add dynamically some CSS classes to your component with a binding with a attribute of your component.
  • attributeBindings – The Same thing than ClassNameBinding but with an attribute. I let you see the documentation for more informations.

Next comes the “actions” method which regroup all of your component logic. It’s through actions that your component is able to react to an event and communicate with a route or a controller. In our case, two actions are defined, deleteAll and add. The component will react to this actions when they will be invoked by one of the component’s template elements. Let see this template:


{{yield}}
<div class="row">
    <div class="col-xs-12">
        <button id="add" type="button" class="btn btn-primary" {{action "add"}}>Add</button>
        <button id="deleteAll" type="button" class="btn btn-danger" {{action "deleteAll"}}>Delete All</button>
    </div>
</div>

As we can see, template buttons register add and deleteAll actions that are defined in the component. Action are register with the tag {{action “actionName”}}. An action is triggered when the primary event of the element on which it is registered is invoked. Ici ce sont des boutons et l’événement primaire est le clique. Lors du clique sur le bouton Add l’action “add” est appelée et attrapée par le composant qui la traite. Il en va de même pour le bouton DeleteAll.

When the component has finished to process the event, it can call the route or controller action of the application using the sendAction() method. This one takes in first parameter the name of the action to invoke and eventually one or more parameters to send to the action. The name of the action to invoke is defined in the application template at the time of the component’s call. Do you remember of the index.hbs of the previous post? We have defined the bootstrap-table component like this :


{{#bootstrap-table deleteAction="deleteAll" addAction="add"}}

When the component executes the  this.sendAction(“addAction”); instruction, Ember will search for the name of the action passed in parameter. In our cas the action is called “add”.

If I summarizes, when a click is triggered on the Add button, this one send an action event named “add’, catched by the component.  The component processes the action and calls the this.sendAction(“addAction”) method. Ember retrieves the parameter passed to the bootstrap-table component that correspond to the “addAction” name, here “add”, and triggers an action that can be catch by the routes or controllers. In our case, this actions are catched by the  admin.post.index route that we have seen in the part 4 of this tutorial.

This can be a little bit tricky the first time but this lets your component be reusable by anyone. Your components doesn’t need to know in advance the name of the action to invoke. For example, if I re-use the bootstrap-table component but this time the route action name is “theBestAction. All i need to do is to change the component declaration in the template like this:


{{#bootstrap-table deleteAction="deleteAll" addAction="theBestAction"}}

A last thing, you can see a {{yield}} tag in the component template. This tag tells to the component where to place the child element thatyou put between component tags.In our bootstrap-table case, this is the html table code.

The bootstrap-table component is very simple. We just add and manage 2 buttons. It can be easily upgrade by allowing to manage directly the table and creating child components like row and column, header, footer. It could also manage functionalities like drag-and-drop or content filtering. If you have time, it can be a great exercise to develop your knowledge in components.

Components in Ember is a huge subject that need a tutorial on it own. I thinks I will do one after this Ember tutorial. In the next part we will end the administration posts part.

See you soon.

00

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.