How to find an attribute that passed in to a component did changed ember?

1.2k views Asked by At

I have a component in ember like

 {{some-setup-section
      processingOfId=processingOfId
      savingActivitySetUp=savingActivitySetUp
      editingActivitySetUp=editingActivitySetUp}}

and in my components js file

didUpdateAttrs() {
 this.updateDataOnChange();
 this._super(...arguments);}

I make use of didUpdateAttrs to find when some attribute have changed. In my case I need to exectue a function only when processingOfId have changed. Is there any method like this.attrs('processingOfId').didChanged() to help me solve my issue.

I tried

didUpdateAttrs({oldAttr, newAttr}) 

and check to see if oldAttr.someAttrs !== newAttr.someAttrs value but in console it says ember doesn't encourage passing in attrs like that and soon its going to be depricated. Is there any way I can solve this scenario

To wrap up the question is there any way to find which attribute updated in the 'didUpdateAttrs' method inside a component

1

There are 1 answers

0
Ember Freak On

There is no in built way,

  1. We have to do it ourself like the below,

Refer this RFC for more information.

Ember.Component.extend({
  didUpdateAttrs() {
    let oldCoordinates = this.get('_previousCoordinates');
    let newCoordinates = this.get('coordinates');

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

    this.set('_previousCoordinates', newCoordinates);
  }
});
  1. You can use addon 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
        }
      })
    });

Some quick notes:

  • The function hook provided to diffAttrs will always be called, even when a tracked attr is not changed.
  • changedAttrs will be null on the first call.

Refer addon README for usage