Skip to content

derive

derive<T>(func): ValueRef<T>

Defined in: aberdeen.ts:3157

Creates a reactive scope that automatically re-executes the provided function whenever any proxied data (created by proxy) read during its last execution changes, storing its return value in an observable.

Updates are batched and run asynchronously shortly after the changes occur. Use clean to register cleanup logic for the scope. Use peek or unproxy within the function to read proxied data without subscribing to it.

T

() => T

The function to execute reactively. Any DOM manipulations should typically be done using A within this function. Its return value will be made available as an observable returned by the derive() function.

ValueRef<T>

An observable object, with its value property containing whatever the last run of func returned.

Observation creating UI components

const $data = A.proxy({ user: 'Frank', notifications: 42 });
A('main', () => {
console.log('Welcome');
A('h3#Welcome, ' + $data.user); // Reactive text
A.derive(() => {
// When $data.notifications changes, only this inner scope reruns,
// leaving the `<p>Welcome, ..</p>` untouched.
console.log('Notifications');
A('code.notification-badge text=', $data.notifications);
A('a text=Notify! click=', () => $data.notifications++);
});
});

Note that the above could just as easily be done using A(func) instead of derive(func).

Observation with return value

const $counter = A.proxy(0);
setInterval(() => $counter.value++, 1000);
const $double = A.derive(() => $counter.value * 2);
A('h3', () => {
A(`#counter=${$counter.value} double=${$double.value}`);
})