1 | import {
|
2 | IComputedValue,
|
3 | IObservable,
|
4 | IObservableArray,
|
5 | Lambda,
|
6 | ObservableMap,
|
7 | getAtom,
|
8 | ObservableSet,
|
9 | isFunction,
|
10 | IObservableValue
|
11 | } from "../internal"
|
12 |
|
13 | const ON_BECOME_OBSERVED = "onBO"
|
14 | const ON_BECOME_UNOBSERVED = "onBUO"
|
15 |
|
16 | export function onBecomeObserved(
|
17 | value:
|
18 | | IObservable
|
19 | | IComputedValue<any>
|
20 | | IObservableArray<any>
|
21 | | ObservableMap<any, any>
|
22 | | ObservableSet<any>
|
23 | | IObservableValue<any>,
|
24 | listener: Lambda
|
25 | ): Lambda
|
26 | export function onBecomeObserved<K, V = any>(
|
27 | value: ObservableMap<K, V> | Object,
|
28 | property: K,
|
29 | listener: Lambda
|
30 | ): Lambda
|
31 | export function onBecomeObserved(thing, arg2, arg3?): Lambda {
|
32 | return interceptHook(ON_BECOME_OBSERVED, thing, arg2, arg3)
|
33 | }
|
34 |
|
35 | export function onBecomeUnobserved(
|
36 | value:
|
37 | | IObservable
|
38 | | IComputedValue<any>
|
39 | | IObservableArray<any>
|
40 | | ObservableMap<any, any>
|
41 | | ObservableSet<any>
|
42 | | IObservableValue<any>,
|
43 | listener: Lambda
|
44 | ): Lambda
|
45 | export function onBecomeUnobserved<K, V = any>(
|
46 | value: ObservableMap<K, V> | Object,
|
47 | property: K,
|
48 | listener: Lambda
|
49 | ): Lambda
|
50 | export function onBecomeUnobserved(thing, arg2, arg3?): Lambda {
|
51 | return interceptHook(ON_BECOME_UNOBSERVED, thing, arg2, arg3)
|
52 | }
|
53 |
|
54 | function interceptHook(hook: "onBO" | "onBUO", thing, arg2, arg3) {
|
55 | const atom: IObservable =
|
56 | typeof arg3 === "function" ? getAtom(thing, arg2) : (getAtom(thing) as any)
|
57 | const cb = isFunction(arg3) ? arg3 : arg2
|
58 | const listenersKey = `${hook}L` as "onBOL" | "onBUOL"
|
59 |
|
60 | if (atom[listenersKey]) {
|
61 | atom[listenersKey]!.add(cb)
|
62 | } else {
|
63 | atom[listenersKey] = new Set<Lambda>([cb])
|
64 | }
|
65 |
|
66 | return function () {
|
67 | const hookListeners = atom[listenersKey]
|
68 | if (hookListeners) {
|
69 | hookListeners.delete(cb)
|
70 | if (hookListeners.size === 0) {
|
71 | delete atom[listenersKey]
|
72 | }
|
73 | }
|
74 | }
|
75 | }
|