jeudi 30 juillet 2015

Ember CLI- conditional output within an each loop using a component instead of itemController

In my Ember CLI app, I'm using {{#each}} helpers to output the rows of a table. 'name' 'created_date' and 'type' are all defined in the related model.

{{#each model as |job|}}
<tr>
  <td>{{job.name}}</td>
  <td>{{job.created_date}}</td>
  <td>{{job.type}}</td>
  <td>
  {{#if typeZero}}
     <p>Content that will display if the value of 'type' is 0.</p>
  {{/if}}
  </td>
</tr>
{{/each}}

In the fourth table cell of each row, I'd like to display certain content if that value of 'type' for that record is 0.

I first tried adding an itemController to the each helper:

{{#each job in model itemController="jobrowcontroller"}}
......
{{/each}}

This gave me an error: "Uncaught Error: Assertion Failed: The value that #each loops over must be an Array. You passed ***@controller:array:, but it should have been an ArrayController"

I found that itemController is now deprecated, and components should be used instead.

I created a component named job-table-row, and updated the page template:

  {{#each model as |job|}}
   {{#job-table-row model=job as |jobTableRow|}}
    <tr>
      <td>{{job.name}}</td>
      <td>{{job.created_date}}</td>
      <td>{{job.type}}</td>
      <td>
      {{#if typeZero}}
        <p>Content that will display if the value of 'type' is 0.</p>
      {{/if}}
      </td>
    </tr>
   {{/job-table-row}}
  {{/each}}

In the component handlebars file, I simply use {{yield}} and everything displays fine.

In the component js file, I have:

import Ember from 'ember';

export default Ember.Component.extend({
  tagName: '',
  typeZero: function() {
    var currentStatus = this.get('model.status');
    if (currentStatus === 0) {
      this.set('typeZero', true);
    } else this.set('typeZero', false);
  }.on('didInsertElement'),

});

The problem with this is that the function 'typeZero' only runs after the component has been inserted which is too late. Is it possible to achieve this with a component, or do I need to use a different method altogether?




Aucun commentaire:

Enregistrer un commentaire