Quick way to Observe multiple properties on Object

Short background:

I’m implementing a vis-timeline, and want to dynamically load data onRangeChanged. Simple, BUT not very performant, calling for a thrtolle/debounce. Also not to taxing, but trying to do so cleanly, I wanted to use Aurelias built-in propertyObserver, and listen on a simple range object (two properties only, start, end).

Now this can be easily done with the verbose bindingEngine approach… but is there a way to keep it smaller with something similar to the @observable decorator?

1 Like

Here is an example of subscribing to multiple properties at once and call change handler only once https://codesandbox.io/s/elegant-greider-hihl3

The difference compared to observable is we need to queue the callback to next tick, to ensure all the changes has been in place. You can have a look at the method generateRandomName to see this (callback needs to be called after both first/last names have been changed)

Why hasn’t something like propertiesObserver made it’s way into the official framework?

Thinking about this a bit more, is it possible to have the framework do a deep observe on an object, either explicitly or implicitly?

Some ideas to consider:

class ClassX {
   @observable propA;
   propB; // Not observed
   @observable propC;

export class SomeComponent {
   @observable propX = new ClassX();  // recursively inspects observable properties

   propXChanged(newValue, oldValue, propertyPath) { // propX, propX.propA, propX.propB, propX.propC


export class SomeComponent {
   @observable({ depth: 1}) propX = {
        propA: ...,
        propB: ...,
        propC: ....

   private  propXChanged(newValue, oldValue, propertyPath) { // propX, propX.propA, propX.propB, propX.propC

Just some ideas.

I would say that observing all properties of an object might be expensive and should be done only in special circumstances. And to that end, the solution from @bigopon should work quite nicely.

Contextually, it should be noted that there is this awesome @watch decorator: GitHub - bigopon/aurelia-watch-decorator: A decorator to reduce boilerplate in your Aurelia project that is now a part of the official Au2.

I’m running into an issue that’s going to require another topic, and it involves object property observation.

If the need of observation is limited to a specific are of the app, then you can have a proxy-based solution (refer: Proxy - JavaScript | MDN). Otherwise, it might be better to stick to the individual property observation.