observe()
Observes a property, a bound property from an attached parent, or an observable object.
observe<K extends string & keyof this>(
target: K,
f: NoInfer<(this: this, value: this[K]) => void>,
): void;
observe<T extends ObservableObject>(
target: T,
f: NoInfer<(this: this, value: T) => void>,
): T;
observe<T = unknown>(
target: Binding<T>,
f: NoInfer<(this: this, value: T, bound?: boolean) => void>,
): void;
Notes
- Use a string parameter to observe a property directly. The provided function is called whenever the property is set to a new value. While the property is set to an observable object, the function is also called when the object emits a change event (until the object is unlinked, or the property is set to a new value).
- Use a binding parameter to observe a property from an attached parent object, if any. The provided function is called when the binding found a property to bind to, and when it is set to a new value.
- Use an observable object parameter to observe the provided object, for as long as both objects are not unlinked. The provided function is called whenever the object emits a change event.
Parameters
- target — A property name, binding, or observable object instance
- f — A function that will be called when the associated value changes; the function is called with the value of the property or binding, and a boolean indicating whether the value is bound (i.e. an attached parent object is found with the matching bound property).
Return value
The target parameter
Examples
class SomeWidget extends Widget {
constructor() {
super();
// Observe a bound property
this.observe(new Binding("foo"), (fooValue) => {
// ... handle foo value, e.g. from an activity
});
// Observe a property (from this object)
this.observe("someViewModel", (someViewModel) => {
// ... handle someViewModel value, after direct updates
// and change events if property is an observable object
});
}
// ...
}
class SomeActivity extends Activity {
// Observe an observable object
constructor(public readonly auth: AuthProvider) {
super();
this.observe(auth, (auth) => {
// ... handle change events on the auth provider object
// as long as the activity and provider are not unlinked
});
}
}
Related
class ObservableObject
The base class of all observable objects, which can be placed into a tree structure to enable event handling and data binding.
