createScope.ts
Purpose
This module implements createScope(), which creates a Scope object for managing the lifecycle of destroyable resources, effects, and atoms.
Overview
Scope acts as a boundary for business logic. It collects created or attached resources and guarantees centralized cleanup through a single destroy() call. This is critical for controllers, view models, and deterministic tests.
Conceptual Architecture
The implementation is based on a linked list of teardown handlers:
onDestroy()registers a callback, unsubscribable resource, or destroyable resource.add()attaches an external resource to the scope.atom(),effect(),syncEffect(), andcreateScope()create child entities and immediately register them in the current scope.destroyScope()walks the registered teardowns in reverse registration order and collects errors.- If errors occur,
ScopeDestructionErroris thrown.
This makes Scope a simple ownership container for reactive resources.
Public API Description
createScope(): Scope
- Returns a new
Scopeinstance. - Lets callers register resources through
onDestroy()andadd(). - Provides convenience factories
atom,effect,syncEffect, andcreateScope.
Usage Examples
ts
import { createScope } from '@nrgyjs/core';
const scope = createScope();
const counter = scope.atom(0);
scope.onDestroy(() => {
console.log('scope destroyed');
});
counter.set(1);
scope.destroy();