简体   繁体   中英

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

So I have this computed property inside my component.js : contexts: Ember.computed.oneWay('myService.contexts'),

And I am able to get the content from another action

 openHelp(){
      console.log(this.get('contexts'))
      alert(this.get('contexts'))
    }
  }

But when I try to use the computed property in Handlebars ( {{contexts}} ) 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 foo a computed property that gets [ 'foo','bar'] from and do {{foo}} I get nothing.

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.

Can't comment on the above answer which is correct because I don't have enough reputation, but I wanted to add a link to the documentation relating to Ember's observable methods for enumerables:

https://guides.emberjs.com/v2.5.0/object-model/enumerables/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM