Hillboy Hillboy - 2 years ago 115
Javascript Question

Ember.js: Using a computed property in handlebars from a Service

So I have this computed property inside my

contexts: Ember.computed.oneWay('myService.contexts'),

And I am able to get the content from another action


But when I try to use the computed property in Handlebars (
) it's just blank.

I created an Ember Twiddle for this question: https://ember-twiddle.com/38de64d58dcf3298df6d4176f15cbc0e?openFiles=components.my-component-help.js%2Ctemplates.components.my-component-help.hbs

If I have an array
foo: [ 'foo','bar']
and I do {{foo}} it outputs in handlebars. But if I make
a computed property that gets
[ 'foo','bar']
from and do
I get nothing.

Answer Source

Here's the solution: https://ember-twiddle.com/e9c2ef05e27013a389e0b2bfdaec3d40?openFiles=services.my-service.js%2Ctemplates.components.my-component-help.hbs

There were two issues:

  1. contexts is an array. When you console.log or alert it, those methods internally in some browsers JSON.stringify the object for you for your convenience. Ember will not do that. You need to format the array yourself or, as I did, each over it. For debugging purposes, feel free to use the log helper.

  2. Computed properties on arrays are watching for array mutations through Ember's methods such as pushObject and removeObject. Simply using push or splice won't update the computed property.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download