簡體   English   中英

Ember.js:在服務的車把中使用計算屬性

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

所以我在我的component.js有這個計算屬性: contexts: Ember.computed.oneWay('myService.contexts'),

而且我可以從另一個動作中獲取內容

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

但是,當我嘗試在Handlebars( {{contexts}} )中使用計算屬性時,它只是空白。

我為這個問題創建了一個Ember Twiddle: https ://ember-twiddle.com/38de64d58dcf3298df6d4176f15cbc0e?openFiles = components.my-component-help.js%2Ctemplates.components.my-component-help.hbs

如果我有一個數組foo: [ 'foo','bar']並且我做{{foo}},它將輸出為車把。 但是,如果我將foo[ 'foo','bar']獲取並執行{{foo}}的計算屬性,我將一無所獲。

解決方案如下: https : //ember-twiddle.com/e9c2ef05e27013a389e0b2bfdaec3d40?openFiles=services.my-service.js%2Ctemplates.components.my-component-help.hbs

有兩個問題:

  1. contexts是一個數組。 當您console.log或對其JSON.stringify alert時,某些瀏覽器內部的那些方法JSON.stringify為您提供方便的對象。 灰燼不會那樣做。 你需要自己的數組格式化,或者像我一樣, each過它。 為了進行調試,請隨時使用log幫助器。

  2. 數組的計算屬性正在通過Ember的方法(例如pushObjectremoveObject監視數組是否發生突變。 簡單地使用pushsplice不會更新計算出的屬性。

無法對上述答案發表評論,因為我沒有足夠的聲譽,所以我認為是正確的,但是我想添加一個鏈接到與Ember的可枚舉方法有關的文檔:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM