Reactive Properties

Reactive Properties

Reactive Properties in Matrix Framework provide a way to create properties that automatically notify when their values change.

Overview

Reactive Properties enable:

  • Change notification
  • Value validation
  • Coercion
  • Default values

Implementation

class ReactiveProperty<T> {
    private _value: T;
    private _subject = new Subject<T>();

    constructor(initialValue: T) {
        this._value = initialValue;
    }

    get value(): T {
        return this._value;
    }

    set value(newValue: T) {
        this._value = newValue;
        this._subject.next(newValue);
    }

    subscribe(callback: (value: T) => void): Subscription {
        return this._subject.subscribe(callback);
    }
}

Usage Example

class MyComponent extends CoreElement {
    public readonly textProperty = new ReactiveProperty<string>("");

    constructor() {
        super();
        this.textProperty.subscribe(value => {
            console.log(`Text changed to: ${value}`);
        });
    }
}

const component = new MyComponent();
component.textProperty.value = "Hello"; // Triggers notification

Key Features

  1. Change Notification

    • Subscribe to value changes
    • React to updates automatically
    • Chain reactions through components
  2. Validation

    • Validate values before setting
    • Coerce values to valid range
    • Throw on invalid values
  3. Default Values

    • Set initial values
    • Reset to defaults
    • Inherit from parent