Passing model data to a component through its template


#1

I’m using ember 1.12.1 with ember-cli 0.2.6, with the ember pods structure. I’ve created a component that should filter out prices that are zero or undefined, based on the pattern from this post Patterns for initializing components (with .on('init')).

Everything seems to be working just fine, except when I’m passing it model.price like so: {{price-filter price=model.price}}, price is undefined when it reaches the if statement in component.js. But when I use it like this: {{price-filter price=10}}, i.e. with a hardcoded price, it works just fine.

Is this normal, or am I doing something wrong? Because from reading this post: http://www.samselikoff.com/blog/data-down-actions-up/, I’d say that it should be possible, expected even.

component.js

'use strict';
import Ember from 'ember';

/**
 * Only displays content passed to it when the price is defined and it
 * isn't 0. Prevents empty prices from being shown.
 */

export default Ember.Component.extend({
  validPrice: false,

  setup: function() {
    if (this.get('price') && this.get('price') !== 0) {
      this.set('validPrice', true);
    }
  }.on('init')
});

template.hbs

{{#if validPrice}}
  {{yield}}
{{/if}}

template.hbs where the component is used

...
{{#price-filter price=model.price}}
  {{model.price}}
{{/price-filter}}
...

#2

So this works:

export default Ember.Component.extend({
  validPrice: function() {
    if (this.get('price') && this.get('price') > 0) {
      return true;
    }

    return false;
  }.property('price')
});

Not really sure yet why the other solution wouldn’t work, but this makes more sense and it works as well!


#3

The reason that the earlier code wouldn’t work is because the model wasn’t resolved when the component initialised.

if you debug the computed property you’ll notice that the first time the function is executed the model isn’t resolved yet same as in the previous code snippet where you hook onto the init method of the component.

However after the model is resolved and thus it’s values changes, the computed property is triggered again and the value is recalculated and updated in the template.

that’s why a computed property in this case works.