UNPKG

2.73 kBMarkdownView Raw
1# disposables
2
3Disposables let you safely compose resource disposal semantics.
4Think DOM nodes, event handlers, socket connections.
5
6This tiny package includes several disposables:
7
8* [`Disposable`](https://github.com/gaearon/disposables/blob/master/modules/Disposable.js) ensures its `dispose` action runs only once;
9* [`CompositeDisposable`](https://github.com/gaearon/disposables/blob/master/modules/CompositeDisposable.js) ensures a group of disposables are disposed together;
10* [`SerialDisposable`](https://github.com/gaearon/disposables/blob/master/modules/SerialDisposable.js) switches underlying disposables on the fly and disposes them.
11
12This implementation of disposables is extracted from [RxJS](https://github.com/Reactive-Extensions/RxJS/blob/master/src/core/disposables).
13I took the liberty to tweak the code style to my liking and provide this as a standalone package.
14
15The API is *mostly* the same as RxJS except stricter in a few places.
16It does not strive for 100% API compatibility with RxJS, but general disposable behavior should match.
17
18It's best if you consult the source and tests, as classes are small and few.
19
20### Usage
21
22#### Importing
23
24```js
25import { Disposable, CompositeDisposable, SerialDisposable } from 'disposables';
26
27// or you can import just the ones you need to keep it even tinier
28// import SerialDisposable from 'disposables/modules/SerialDisposable';
29
30function attachHandlers(node) {
31 let someHandler = ...;
32 node.addEventHandler(someHandler);
33
34 // use Disposable to guarantee single execution
35 return new Disposable(() => {
36 node.removeEventHandler(someHandler);
37 });
38}
39
40// CompositeDisposable lets you compose several disposables...
41let nodes = ...;
42let compositeDisp = new CompositeDisposable(nodes.map(attachHandlers));
43
44// and more later...
45let moreNodes = ...
46moreNodes.map(attachHandlers).forEach(d => compositeDisp.add(d));
47
48// and dispose them at once!
49function goodbye() {
50 compositeDisp.dispose();
51}
52
53// ... or replace with a bunch of new ones ...
54let serialDisp = new SerialDisposable();
55serialDisp.setDisposable(compositeDisp);
56
57function replaceNodes(newNodes) {
58 let nextCompositeDisp = newNodes.map(attachHandlers);
59
60 // release all the previous disposables:
61 serialDisp.setDisposable(nextCompositeDisp);
62}
63
64// with a guarantee of each dispose() called only once.
65```
66
67### Why Use This Over RxJS
68
69* You only need disposables and not observables;
70* RxJS is still figuring out [its modularity story](https://github.com/Reactive-Extensions/RxJS-Modular) and [it's not ready](https://github.com/Reactive-Extensions/RxJS-Modular/issues/4#issuecomment-90879664).
71
72Really, there are no other reasons.
73
74### License
75
76Like the original RxJS code, it is licened under Apache 2.0.