【问题标题】:EmberJS, how to observe changes in any object of a hashEmberJS,如何观察散列的任何对象的变化
【发布时间】:2016-06-20 22:33:35
【问题描述】:

我有一个像这样的对象:

// app/services/my-service.js
import Ember from 'ember';

export default Ember.Service.extend({
  counters: Ember.Object.create()
})

myService.counters 是一个 hash,例如:

{
  clocks: 3,
  diamons: 2
}

我想为这个对象添加一个计算属性,这样会返回myService.counters.clocks加上myService.counters.diamons的总和

// app/services/my-service.js
...
count: Ember.computed('counters.@each', function(){
  return _.reduce(this.get('counters'), function(memo, num){ return memo + num; }, 0);
})
...

但是观察者配置不被接受,我有错误:

Uncaught Error: Assertion Failed: Depending on arrays using a dependent key ending with `@each` is no longer supported. Please refactor from `Ember.computed('counters.@each', function() {});` to `Ember.computed('counters.[]', function() {})`.

但如果我做出建议的更改:

// app/services/my-service.js
...
count: Ember.computed('counters.[]', function(){
  return _.reduce(this.get('counters'), function(memo, num){ return memo + num; }, 0);
})
...

count 属性未更新。

我可以让它工作的唯一方法是这样的:

// app/services/my-service.js
...
count: Ember.computed('counters.clocks', 'counters.diamons', function(){
  return _.reduce(this.get('counters'), function(memo, num){ return memo + num; }, 0);
})
...

在这种情况下如何使用任何类型的通配符?

【问题讨论】:

    标签: ember.js computed-properties


    【解决方案1】:

    @each[] 用于观察数组元素和数组。

    您不能使用通配符,因为它会严重影响性能。有多个属性的简写:

    count: Ember.computed('counters.{clocks,diamons}', function() {
        return this.get('counters').reduce((memo, num) => memo + num, 0);
    })
    

    我还更新了计算逻辑以使用Array#reduce,以及一个带隐式返回的箭头函数。

    【讨论】:

    • 问题是我事先不知道哪些是我的counters 的键:/ .. 这个 attribute 是由修改的模块从类中操作出来的值,甚至添加新键。
    • 如果需要在运行时指定计算属性的依赖键,请使用defineProperty
    猜你喜欢
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    相关资源
    最近更新 更多