Ember.js 1.13: The correct way to observe the passed attribute of a component?

I am trying to upgrade my project to Ember 1.13 and I am a bit confused about the behavior of the new component attrs especially when I need to watch them.

For example, my test component observes bar , which is a parameter passed from the outside. I know that in Ember new Glimmer the engine when a component modifies any of its attributes. I cannot understand that the observer will also be launched at this time if I see attrs.bar (I did not change the bar !). But if I observe bar , then everything will be fine.

Code example:

HTMLBar:

{{test-cpnt foo=foo bar=bar}} <input type="button" {{action 'tap'}} value="tap"/> 

Controller:

  foo: 1, bar: 100, actions: { tap: function(){ this.set('foo', this.get('foo')+1); } } 

component:

 App.TestCpntComponent = Ember.Component.extend({ barObv1: Ember.observer('bar', function(){ console.log('bar observer is fired!'); }), barObv2: Ember.observer('attrs.bar', function(){ console.log('attrs.bar observer is fired!'); }), }); 

By clicking the button to change the value of foo , we will run barObv2 . I created jsbin to demonstrate: https://jsbin.com/qiwivu/2/edit?js,console,output

Does anyone know why an observer was called?

+4
source share
1 answer

Well, you do not need to use observers, since you are in Ember 1.13, you can use didUpdateAttrs , which is triggered whenever the attribute is updated.

 Ember.Component.extend({ .... didUpdateAttrs({oldAttrs, newAttrs}) { let oldBar = get(oldAttrs, 'bar.value'); let newBar = get(newAttrs, 'bar.value'); if (oldBar !== new Bar) { // your logic here } } .... }); 

If you intend to use an observer, you can observe the changes as shown below.

 barDidChange: Ember.observer('bar', function(){ console.log('bar observer is fired!'); }); 

Listening to attrs.bar will not work properly, whenever an attribute is updated (including init), attrs mutate each time, which causes observers to run, for more reference. attrs supposed to be used with angle-bracket components . Here is a good article why we should not use attr for curly components.

+1
source

All Articles