EmberJS – Attributes with didReceiveAttrs

didReceiveAttrs hook

The didReceiveAttrs hook can be used after the init method and called when the component’s attributes are updated and it will not run when the re-rendered is initiated internally.

Syntax

import Ember from 'ember';

export default Ember.Component.extend ({
   ...
   didReceiveAttrs() {
      //code here    
   },
   ...
})

Example

The example given below describes the use of didReceiveAttrs hook to be used when the component’s attributes are updated. Create a component with the name post-action which will get defined under app/components/.

Open the post-action.js file and add the following code −

import Ember from 'ember';

export default Ember.Component.extend ({
   didInitAttrs(options) {
      console.log('didInitAttrs', options);
   },

   didUpdateAttrs(options) {
      console.log('didUpdateAttrs', options);
   },

   willUpdate(options) {
      console.log('willUpdate', options);
   },

   didReceiveAttrs(options) {
      console.log('didReceiveAttrs', options);
   },

   willRender() {
      console.log('willRender');
   },

   didRender() {
      console.log('didRender');
   },

   didInsertElement() {
      console.log('didInsertElement');
   },

   didUpdate(options) {
      console.log('didUpdate', options);
   },
});

Now open the component template file post-action.hbs with the following code −

<p>name: {{name}}</p>
<p>attrs.data.a: {{attrs.data.a}} is in console</p>
{{yield}}

Open the index.hbs file and add the following code −

<div>
   <p>appName: {{input type = "text" value = appName}}</p>
   <p>Triggers: didUpdateAttrs, didReceiveAttrs, willUpdate, willRender,
      didUpdate, didRender</p>
</div>

<div>
   <p>data.a: {{input type = "text" value = data.a}}</p>
</div>
<hr>

{{post-action name = appName data = data}}
{{outlet}}

Create an index.js file under app/controller/ with the following code −

import Ember from 'ember';

export default Ember.Controller.extend ({
   appName:'Adglob',
   data: {
      a: 'output',
   }
});

Previous Page:-Click Here

Leave a Reply