Components

Components take the code/markup combo idea and make it reusable. They consist of a Javascript source file (like a controller) and its corresponding Handlebars template.

Unlike controllers, they are isolated by design. They are not aware of their surrounding context, but they receive data through their attributes, including actions (closure functions).

A sample component template could look like this:

<article class="blog-post">
  <h1>{{this.title}}</h1>
  <p>{{yield}}</p>
  <label for="title">Blog Title</label>
  <p>Edit title: <Input @id="title" @type="text" @value={{this.title}} /></p>
</article>

Given the above template, you can now use the <BlogPost /> component:

{{#each this.model as |post|}}
  <BlogPost @title={{post.title}}>
    {{post.body}}
  </BlogPost>
{{/each}}

The Component Lifecycle

Part of what makes components so useful is that they let you take complete control of a section of the DOM. This allows for direct DOM manipulation, listening and responding to browser events, and using 3rd party JavaScript libraries in your Ember app.

As components are rendered, re-rendered and finally removed, Ember provides lifecycle hooks that allow you to run code at specific times in a component's life.

On Initial Render

  1. init

  2. didReceiveAttrs

  3. willRender

  4. didInsertElement

  5. didRender

On Re-Render

  1. didUpdateAttrs

  2. didReceiveAttrs

  3. willUpdate

  4. willRender

  5. didUpdate

  6. didRender

On Component Destroy

  1. willDestroyElement

  2. willClearRender

  3. didDestroyElement

Last updated