@twobirds/microcomponents
Version:
Micro Components Organization Class
102 lines (67 loc) • 2.82 kB
Markdown

# Observables
This module provides utilities for observing and binding data to DOM elements using placeholders. It supports reactive updates when data changes.
## Table of Contents
- [Overview](#overview)
- [Functions](#functions)
- [Types](#types)
- [Example](#example)
---
## Overview
The module defines an `observe` function that makes object properties observable.
You can use this function to turn a single property or all properties of an object into observables.
This functionality can be used standalone in any framework.
## Functions
### `observe( target: LooseObject, propertyName?: string ): LooseObject`
**Description**
Registers a distinct property or all object properties as an observable, making them reactive.
Those properties are dual use:
- **Direct Assign Native Values**:
- Directly assign native values to the property, and the observable will be notified of the change and its callbacks will be run.
- **Use as an Instance of Observable**
- Use the property as an instance of the `Observable` class. This allows you to attach callbacks and react to changes. You can bind the property to DOM elements.
## Types
### `Observable`
**Type**
```typescript
export type Observable = {
observe: (cb: Callback) => void; // attach a callback to be notified of changes
notify: () => void; // mostly internal use, but can be called to trigger all callbacks
bind: (target: HTMLElement | DocumentFragment | ShadowRoot) => void; // the target DOM element to bind the observable to. {placeholder} will be replaced with the actual data value.
};
```
**Methods**
- `observe(cb: Callback)`
Registers a callback to be notified of changes.
- `notify( enable?: boolean)`
- Enables / Disables notifications.
- By default, notifications are enabled.
- If `enable` is `false`, notifications are disabled. You need to explicitly call `notify(true)` to re-enable notifications.
- Otherwise calls all registered callbacks with the current data.
- `bind(target: HTMLElement | DocumentFragment | ShadowRoot)`
Binds the observable to a DOM element, replacing placeholders with data values.
## Example
HTML:
```html
<div id="user-card">
<p>Hello, {name}</p>
<p>Age: {age}</p>
</div>
```
JavaScript:
```javascript
import { observe } from './observables.js';
const data = {
name: 'John',
age: 30,
};
observe(data); // all properties of the data object will be observed.
const element = document.getElementById('user-card');
data.bind(element);
```
When `data.name` or `data.age` changes, the DOM updates automatically.
---
## Notes
- Only objects can be bound to the DOM.
- Native values (strings, numbers, booleans) are wrapped in observable proxies.
- Changes to observable properties trigger updates in bound DOM elements.