Browser Cancelable Events
Automatically invalidate async listeners and promises in one place.
Lightweight zero dependent library for browsers.
Motivation
Libraries like React, should invalidate all async tasks once component is unmounted,
using isMounted
is anti pattern.
Table of Contents
Quick start
Install
npm i --save browser-cancelable-events
Typescript
The project is written with typescript and comes with a built-in index.d.ts
Import
;
Require
const CancelableEvents isCancelledPromiseError = ;
Usage
Usage example using react component
; { superprops; thiscancelable = ; } { thiscancelable; thiscancelable; this; this; } // invalidate all events { thiscancelable; // this is the magic line } { return <div> ... </div> ; } // interval that updates every second { thiscancelable; } // do task with timeout { this } // use invalidated promise async { try const apiResult = await thiscancelable; const someVeryLongPromise = thiscancelable; thiscancelable; await someVeryLongPromise; catch err if // all good, component is not mounted or promise is cancelled return; // it's real error, should handle } // callback for window.addEventListener { // do something with resize event }
API
Cancelable object
Each one of the cancelable methods returns object with cancel method
cancel: Function
const timer = cancelable;timer;
Cancel All
Cancel all listeners method, invalidated everything immediately. Adding new listeners on cancelled event will throw exception
cancelable;
Timeout
cancelable -> CancelableObject
Interval
cancelable -> CancelableObject
Promise
cancelable -> Promise & CancelableObjectcancelable -> Promise<T> & CancelableObject
Promise example
const cancelable = ; cancelable; let cancelTimer;// invalidate promise after 1 secondconst promise = cancelable; promise; // if promise.cancel() called after fulfilled, nothing will happencancelTimer = cancelable;
Document event listener
Observes document.addEventListener
cancelable -> CancelableObject
Window event listener
Observes window.addEventListener
cancelable -> CancelableObject
Event listeners example
const cancelable = ; cancelable;cancelable; // remove all cancelable listenerscancelable;
Custom event emitter
You can use custom event emitter with cancelable events.
cancelable -> CancelableObject
Custom event emitter example
const EventEmitter = ; const emitter = ;// key "remove" because emitter.addListener(...).remove()cancelable;
Testing
npm run tests
License
MIT