Skip to content

Repository files navigation

@wopjs/disposable

DocsBuild Statusnpm-versionCoverage Statusminified-sizecore-size

Manage side effect disposers in a compact, reusable and testable style. Designed and implemented with efficiency and ergonomics in mind.

Install

npm add @wopjs/disposable

Examples

import{disposableStore}from"@wopjs/disposable";// Example lib that returns a disposer functionconstlisten=(target,type,listener)=>{target.addEventListener(type,listener);return()=>target.removeEventListener(type,listener);};classA{dispose=disposableStore();constructor(){this.dispose.add(listen("type",event=>console.log(event)));}print(){console.log("print a");}}classB{dispose=disposableStore();// A is a disposable so it can be added to the store.a=this.dispose.add(newA());}constb=newB();b.a.print();// "print a"b.dispose();// both a and b are disposed

With more type annotations:

import{disposableStore,disposableMap,typeIDisposable,typeDisposableStore,}from"@wopjs/disposable";// Example lib that returns a disposer functionconstlisten=(target,type,listener)=>{target.addEventListener(type,listener);return()=>target.removeEventListener(type,listener);};classAimplementsIDisposable{dispose=disposableMap();someMethod(){// Create side effects on demand.this.dispose.make(// Easily implements debounce by providing a id for the disposer.// When adding disposer with the same id to the store, the previous disposer will be disposed."myIdForThisDebounce",()=>{consttimeoutId=setTimeout(()=>console.log("timeout"),1000);return()=>clearTimeout(timeoutId);});}}classBimplementsIDisposable{dispose: DisposableStore;a=newA();constructor(){// Add initial disposables.this.dispose=disposableStore([// A is a disposable so it can be added to the store.a,// Add a disposer function.listen("type",event=>console.log(event)),]);}}constb=newB();b.dispose();// All side effects in both a and b are disposed

Features

Non-invasive

  • Disposable adopts both disposer function () => void and disposable .dispose() contracts which are widely accepted. Implementing these patterns does not require any extra effort.

    // disposer function patternconstdisposer=()=>console.log("dispose");// class disposable patternclassMyDisposable{dispose(){console.log("dispose");}}constmyDisposable=newMyDisposable();// plain object disposable patternconstmyDisposable={dispose(){console.log("dispose");},};
  • And of course it works well with other @wopjs libraries.

    import{addEventListener}from"wopjs/dom";import{timeout}from"wopjs/time";

Compact

  • Disposables are designed to be composable and chainable.

    import{disposableStore,typeIDisposable}from"@wopjs/disposable";classAimplementsIDisposable{dispose=disposableStore();constructor(){this.dispose.add(()=>console.log("a"));}print(){console.log("print a");}}classBimplementsIDisposable{dispose=disposableStore();a=this.dispose.add(newA());}constb=newB();b.a.print();// "print a"b.dispose();// both a and b are disposed
  • You can also create your own side effects in a compact way.

    import{disposableStore}from"@wopjs/disposable";classA{dispose=disposableStore();constructor(){dispose.make(()=>{consthandler=()=>console.log("click");someEvent.on("type",handler);return()=>someEvent.off("type",handler);});}}consta=newA();a.dispose();// clear all disposers

Refreshable

  • Disposables can bind to keys with DisposableMap. Setting a disposable with the same key will dispose (flush) the old one first.

    import{disposableStore,disposableMap}from"@wopjs/disposable";import{addEventListener}from"@wopjs/dom";import{timeout}from"@wopjs/time";conststore=disposableStore();// let store also manage the DisposableMapconstmap=store.add(disposableMap());store.add(addEventListener(window,"click",event=>{// Clicking within 1s will trigger debounce effect (the pending timeout is cancelled before adding the new one).map.set("myId",timeout(()=>console.log(event),1000));}));

Small Footprint

  • Designed and implemented with efficiency and ergonomics in mind, not only the (minified) bundle size is less than 1kb, using this library also enables patterns that require way less code to manage side effect disposers and module life-cycles.

Concepts

Disposable

A disposable is an object that has a dispose method. The dispose method is used to dispose the object, which means to clean up any resources it holds.

// class disposableclassMyDisposable{dispose(){console.log("clean up");}}constmyDisposable=newMyDisposable();// plain object disposableconstmyDisposable={dispose(){console.log("clean up");},};

Disposer

A disposer is a function that cleans up resources. It is usually created by a factory function.

constaddListener=(target,type,listener)=>{target.addEventListener(type,listener);// disposer functionreturn()=>target.removeEventListener(type,listener);};constdisposer=addListener(window,"click",()=>console.log("click"));disposer();// listener is removed

DisposableDisposer

A disposable disposer is both a disposer an a disposable.

This pattern is useful if you want to create disposers that are compatible to more frameworks.

constaddListener=(target,type,listener)=>{target.addEventListener(type,listener);constdisposer=()=>target.removeEventListener(type,listener);disposer.dispose=disposer;returndisposer;};

For type annotation you may use DisposableDisposer:

importtype{DisposableDisposer}from"@wopjs/disposable";constsetInterval=(handler: ()=>void,timeout: number)=>{constticket=setInterval(handler,timeout);constdisposer: DisposableDisposer=()=>clearInterval(ticket);disposer.dispose=disposer;returndisposer;};

DisposableStore

A DisposableStore is a DisposableDisposer that manages other disposers and disposables.

import{disposableStore}from"@wopjs/disposable";constdispose=disposableStore();dispose.add(()=>console.log("disposed 1"));dispose.add(()=>console.log("disposed 2"));dispose.make(()=>{return()=>console.log("disposed 3");});dispose();// Logs "dispose 1", "dispose 2" and "dispose 3"

Since it is also a disposer, it can be easily composed with other disposables.

import{disposableStore,typeIDisposable}from"@wopjs/disposable";classAimplementsIDisposable{dispose=disposableStore();constructor(){this.dispose.add(()=>console.log("a"));}print(){console.log("print a");}}classBimplementsIDisposable{dispose=disposableStore();a=this.dispose.add(newA());}constb=newB();b.a.print();// "print a"b.dispose();// both a and b are disposed

DisposableMap

Like DisposableStore, a DisposableMap is a DisposableDisposer that manages disposers and disposables with key.

Map key introduces Refreshable which makes it more interesting when comes to creating side effects on the fly.

import{disposableMap}from"@wopjs/disposable";constdispose=disposableMap();dispose.set("key1",()=>console.log("disposed 1"));dispose.make("key2",()=>{return()=>console.log("disposed 2");});dispose();// Logs "disposed 1" and "disposed 2"

Since it is also a disposer, it can be easily composed with other disposables.

import{disposableMap,disposableStore,typeIDisposable,}from"@wopjs/disposable";classAimplementsIDisposable{dispose=disposableMap();constructor(){this.dispose.add("key1",()=>console.log("a"));}print(){console.log("print a");}}classBimplementsIDisposable{dispose=disposableStore();a=this.dispose.add(newA());}constb=newB();b.a.print();// "print a"b.dispose();// both a and b are disposed

DisposableOne

DisposableOne is a lightweight DisposableMap. It only manages one disposer or disposable at a time. It is useful if you want Refreshable but only need to manage one disposer or disposable.

import{disposableOne}from"@wopjs/disposable";constdispose=disposableOne();dispose.set(()=>console.log("disposed 1"));dispose.set(()=>console.log("disposed 2"));// Logs "disposed 1"dispose();// Logs "disposed 2"

Abortable

Abortable is a special kind of disposable that may be disposed outside of the store (like when setTimeout or once event finishes). It will notify the store to delete itself from the store when disposed. The signature is the same as a disposable disposer.

import{abortable,disposableStore}from"@wopjs/disposable";consttimeout=(handle,timeout)=>{letid;constdisposer=abortable(()=>clearTimeout(id));id=setTimeout(()=>{handler();disposer();},timeout);returndisposer;};constdispose=disposableStore();dispose.add(timeout(()=>console.log("timeout"),1000));// The `timeout` disposer will be removed from the `dispose` after 1s.

ESLint Plugin

This package comes with an ESLint plugin:

// eslint.config.mjs
import disposable from "@wopjs/disposable/eslint-plugin.js";
export default [
disposable.recommended
]

Rules:

  • disposable/readonly-dispose: Enforce dispose method to be readonly.

Biome Plugin

This package also comes with a Biome GritQL plugin:

{
"plugins": ["./node_modules/@wopjs/disposable/biome-plugin.grit"]
}

Check:

  • Enforces class dispose properties to be readonly when they hold a disposable type or are initialized by one of this package's disposable factory functions.

License

MIT @ wopjs

About

Manage side effect disposers in a compact, reusable and testable style.

Resources

Stars

2 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

Generated from wopjs/template