2

请参阅下面的示例代码。鉴于我有一个组件my-text-box

my-text-box.hbs

{{my-text-box value=modelName}}

我想value通过didReceiveAttrs钩子观察属性的变化,而不是observers为了更好的性能。

my-text-box.js

didReceiveAttrs: function(args) {
    if (args.oldAttrs == null) {
        // This is the initial render, but I don't need to anything here.
    } else if (args.newAttrs.value != args.oldAttrs.value) {
        // supposed `value` was changed from outside, I can do something here...

        // BUT, `args.newAttrs.value` is not always the prop value, 
        // `Ember` would automatically wrap it with `{{mut}}` helper. 
        // The data structure would be: 
        // {
        //    value: value,
        //    update: function (val) {
        //        source.setValue(val);
        //    }
        // }
    }
}

我想要的是我不必关心 attr 值是否是一个mutable单元格,我应该得到一种总能获得真正价值的方法。我看到有一个HTMLBars hook ember-htmlbars/hooks/get-value,但它没有暴露给公共 API。我在想的是,也许Ember应该改变两者newAttrsoldAttrs拥有直接价值而不是那些mutable对象。

有人有办法处理吗?谢谢!

4

2 回答 2

1

我的建议是自己存储之前的值,然后比较:

export default Ember.Component.extend({
  _previousAttr: null,

  didReceiveAttrs() {
    this._super(...arguments);
    if (this.get('_previousAttr') !== this.get('attrName')) {
      this.set('_previousAttr', this.get('attrName'));
      // do your thing
    }
  }
});
于 2016-12-07T02:34:27.923 回答
1

根据RFC #191 ,不推荐使用 Ember 组件生命周期挂钩参数。

所以最好做这样的事情:

Ember.Component.extend({
  didReceiveAttrs() {
    let oldAttrs = this.get('_previousAttrs');
    let newAttrs = this.get('newAttrs');

    if (oldAttrs && oldAttrs !== newAttrs) {
      this.map.move({ from: oldAttrs, to: newAttrs });
    }

    this.set('_previousAttrs', newAttrs);
  }
});

或者,也许您可​​以暂时使用这个ember-diff-attrs 插件

于 2017-04-17T09:47:40.853 回答