EmberJs弃用组件生命周期挂钩didReceiveAttrs

时间:2019-04-19 17:09:16

标签: javascript object ember.js ember-cli deprecated

对于Ember版本2.16,他们已经删除了传递到didReceiveAttrs组件生命周期挂钩的参数。以前我以对象的形式获取参数。

newAttrs:

EmptyObject: 
{
  dataTestId: "test-object"
  items: MutableCell {__MUTABLE_CELL__       [id=__ember1555539649631463096066386]: true, __REF__ [id=__ember1555539649631670217952659]: RootPropertyReference, value: Array(27)}
  prompt: SafeString {string: "Select an Initiator Group"}
  required: true
  selected: MutableCell {__MUTABLE_CELL__ [id=__ember1555539649631463096066386]: true, __REF__ [id=__ember1555539649631670217952659]: RootPropertyReference, value: undefined}
  __proto__: Object
}

弃用后如何在didReceiveAttrs中获得这样的对象?

2 个答案:

答案 0 :(得分:2)

嗯,这是2.12中添加的弃用。您可以在组件生命周期挂钩中获取参数,直到2.13.0

下面是另一种在2.13.0之后在钩子中获取参数的方法,

之前:

didReceiveAttrs({ oldAttrs, newAttrs }) {
  if (oldAttrs.temp !== newAttrs.temp) {
    this.thermometer.move({ from: oldAttrs.temp, to: newAttrs.temp });
  }
}

之后:

didReceiveAttrs() {
  let oldTemp = this.get('_oldTemp');
  let newTemp = this.get('temp');

  if (oldTemp && oldTemp !== newTemp) {
    this.thermometer.move({ from: oldTemp, to: newTemp });
  }
  this.set('_oldTemp', newTemp);
}

您可以从官方deprecation guide

获取更多信息

答案 1 :(得分:0)

有可以提供更改属性的余烬插件,

https://github.com/workmanw/ember-diff-attrs

速记用法:

import diffAttrs from 'ember-diff-attrs';

export default Ember.Component.extend({
  didReceiveAttrs: diffAttrs('email', 'isAdmin', function(changedAttrs, ...args) {
    this._super(...args);

    if(changedAttrs && changedAttrs.email) {
      let oldEmail = changedAttrs.email[0],
          newEmail = changedAttrs.email[1];
      // Do stuff
    }
  })
});

扩展用法:

import diffAttrs from 'ember-diff-attrs';

export default Ember.Component.extend({
  didReceiveAttrs: diffAttrs({
    keys: ['user', 'isAdmin'],
    isEqual(key, a, b) {
      if (key === 'user') {
        return (a && b) ? a.id === b.id : a === b;
      }
      return a === b;
    },
    hook(changedAttrs, ...args) {
      this._super(...args);

      if(changedAttrs && changedAttrs.user) {
        let oldUser = changedAttrs.user[0],
            newUser = changedAttrs.user[1];
        // Do stuff
      }
    }
  })
});