fguillen
fguillen

Reputation: 38832

EmberJS, Helpers and ComputedProperty

I have a Helper that receives an array of elements and returns some other array based on the first one.

{{#each (sorted-strings myStrings) as |string|}}
  {{string}}
{{/each}}

The implementation of the Helper can be something like:

// app/helpers/sorted-strings.js
import Ember from 'ember';

export function sortedStrings(params/*, hash*/) {
  return params[0].sort();
}

export default Ember.Helper.helper(sortedStrings);

The Helper works ok, but if the original myString Array changes the changes are not affecting the already rendered list.

How can I combine the behaviour of a ComputedProperty and the result of a Helper?

Upvotes: 0

Views: 111

Answers (3)

fguillen
fguillen

Reputation: 38832

After a lot of struggling I just figured out that the proper solution is to declare a Component instead of a Helper. This way I can explicitly declare a Computed Property that observes changes in the myStrings Array:

// app/components/sorted-strings.js
export default Ember.Component.extend({
  myStrings: null,
  sortedMyStrings: Ember.computed('myStrings', function() {
    return this.get('myStrings').sort();
  });
});

// app/templates/components/sorted-strings.hbs
{{#each sortedMyStrings as |string|}}
  {{string}}
{{/each}}

// template
{{sorted-strings myStrings=myStrings}}

Upvotes: 1

David Votrubec
David Votrubec

Reputation: 4166

Use notifyPropertyChange() that will notify the helper that the array has changed. I think that the helper has a reference to the array and does not know that it's content or length has changed

Like this

actions: {
    add() {
     this.get('myStrings').pushObject('testing');
     this.notifyPropertyChange('myStrings');
    }
  }

I have updated the Twiddle - here is the new link https://ember-twiddle.com/31dfcb7b208eb1348f34d90c98f50bbb?openFiles=controllers.application.js%2C

Upvotes: 3

Igor
Igor

Reputation: 1588

Passing a computed property to the helper should work fine. Check out this twiddle.

Maybe your computed property is not getting updated properly.

Upvotes: -1

Related Questions