@Observe()¶
An alternative to the @Watch() decorator is the @Observe() decorator. The @Observe() decorator allows you to observe changes to any property, regardless if it is decorated with @Prop(), @State(), or any other decorator.
- Observe(options)¶
Decorates a method with an observable which invokes it when the decorated property changes.
function Observe(property: PropertyKey, options?: ObserveOptions)
- Arguments:
property (
PropertyKey) – The name of the property to observe for changes.options (
ObserveOptions) – Optional configuration for the decorator.
- Returns:
Method decorator that invokes the decorated method when the observed property changes.
- Return type:
MethodDecorator
- class ObserveOptions()¶
Configuration options for observing a property.
export type ObserveOptions = { immediate?: boolean; whileConnected?: boolean; };
- ObserveOptions.immediate¶
- Type:
boolean
Optional: Yes
Default:
falseIf
true, the decorated method will be invoked immediately with the current value of the observed property when the component is connected to the DOM.
- ObserveOptions.whileConnected¶
- Type:
boolean
Optional: Yes
Default:
falseIf
true, the decorated method will be invoked only when the component is connected to the DOM. If component is disconnected from the DOM and re-connected, the decorated method will be invoked again with the current value of the observed property, if value has changed since the last invocation.
Example¶
1import { Component, h } from '@stencil/core';
2import { Observe } from '@runopenode/rxjs-stencil';
3
4@Component({
5 tag: 'my-component',
6 shadow: true,
7})
8export class MyComponent {
9
10 private _foo: string = '';
11
12 private _bar: string = '';
13
14 @Observe('_foo', { immediate: true, whileConnected: true })
15 @Observe('_bar', { immediate: true, whileConnected: true })
16 private _onChange(current: string, previous: string, property: PropertyKey): void {
17 console.log(`Property ${String(property)} changed from ${previous} to ${current}`);
18 }
19
20 public render(): any {
21 return (
22 <div>{this._foo}</div>
23 <div>{this._bar}</div>
24 );
25 }
26}