Observer with params to know the new value of the observed property


#1

I have found the situation that I am observing a property change but I also want to know, into the Observer, what has been the change.

I have the intuition that once one Observer is triggered the property the Observer is observing may have changed its value already… maybe for another previously executed Observer.

So my question/suggestion is having the possibility of knowing the new value set to the observed property that has triggered the Observer:

onPropertyChanges: Ember.observer('property1', 'property2', function(changesOnProperties){
  let oldValueOnProperty1 = changesOnProperties.property1.oldValue;
  let newValueOnProperty1 = changesOnProperties.property1.newValue;

  ...
})

#2

I believe you will have to manually track property changes.

Here’s something I would do. https://ember-twiddle.com/265267bc441ae05df255?numColumns=1&openFiles=application.controller.js%2C

Basically you would create computed property and use set hook to capture old and new value. You would then save those values. I used changedProperties there since it resembled yours changesOnProperties.


#3

That is crazy work @kklisura, very nice!.

Still I think it is too intrusive, it depends in the properties to be all defined as trackPropertyChanges.

Which means that it makes me difficult to use this system with any kind of properties as computed property or DS.attr for example.


#4

I see that the Observer method has actually interesting params as: value and rev:

But in the documentation they say: “The value property is currently reserved and unused” :confused:


#5

As to using DS.attr (on DS.Model), I believe you already have changedAttributes property. http://emberjs.com/api/data/classes/DS.Model.html#method_changedAttributes

Although, I don’t know how would it behave when observing some properties, since i’m not into Ember Data. :slightly_smiling:

We can try extending that twiddle to support computed properties too. :slightly_smiling:


#6

Thanks again @kklisura.

I moved this thread to the Proposals category to see if someone is listen and they can fix this issue from the design level.


#7

Observers have fallen out of favor in general, so I wouldn’t expect any move from the core team that restores them. What you’re trying to do could be accomplished with beforeObservers but [they were deprecated in Ember 1.12]((http://emberjs.com/deprecations/v1.x/#toc_beforeobserver).

In component-land, the before– and after values of properties can be had by using the lifecycle hooks that were introduced in 1.13. I used these successfully to replace observers but they only work in components, as their name suggests :wink: