Observables

Observables are utilized to monitor changes in properties. Similar to how "element.addEventListener" is used in the DOM for event listening, observables serve a comparable purpose for regular classes. They provide a mechanism to be notified when a property undergoes a change, extending this functionality beyond the DOM to other class instances.

The Observable class found in "crs.binding.classes.observable" gives you a base class allowing you to register and unregister events as if a class was a element, using the same “addEventListener” and “removeEventListener” syntax.

class MyClass extends crs.binding.classes.Observable {
  ...
}

const callback = (args) => { console.log(args) };
const instance = new MyClass();
instance.addEventListener("event_name", callback });
instance.removeEventListener("event_name", callback });

Observable also has a method called notify that you can use to dispatch events from in the class. It takes two parameters:

  1. event name
  2. event detail object

You can also suppress notifications by setting the property "allowNotifications" to anything other than true.

Listening to changes on binding context

There are situations where it’s necessary to monitor changes to a property within a specific binding context. In such cases, you would set up a callback function that gets triggered in response to any alterations in that property, allowing you to effectively respond to these changes.

For this you will need three things.

  1. The bid of the context you want to listen on
  2. The property name you want to monitor for changes
  3. The callback function
await crs.binding.data.addCallback(bid, "firstName", this.#firstNameChanged);
await crs.binding.data.removeCallback(bid, "firstName", this.#firstNameChanged);

NB: You must remember to remove the callback when you are done.