forked from mobxjs/mobx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintercept-read.ts
More file actions
56 lines (54 loc) · 1.84 KB
/
Copy pathintercept-read.ts
File metadata and controls
56 lines (54 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import {
IObservableArray,
IObservableValue,
Lambda,
ObservableMap,
fail,
getAdministration,
isObservableArray,
isObservableMap,
isObservableObject,
isObservableValue
} from "../internal"
export type ReadInterceptor<T> = (value: any) => T
/** Experimental feature right now, tested indirectly via Mobx-State-Tree */
export function interceptReads<T>(value: IObservableValue<T>, handler: ReadInterceptor<T>): Lambda
export function interceptReads<T>(
observableArray: IObservableArray<T>,
handler: ReadInterceptor<T>
): Lambda
export function interceptReads<K, V>(
observableMap: ObservableMap<K, V>,
handler: ReadInterceptor<V>
): Lambda
export function interceptReads(
object: Object,
property: string,
handler: ReadInterceptor<any>
): Lambda
export function interceptReads(thing, propOrHandler?, handler?): Lambda {
let target
if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) {
target = getAdministration(thing)
} else if (isObservableObject(thing)) {
if (typeof propOrHandler !== "string")
return fail(
process.env.NODE_ENV !== "production" &&
`InterceptReads can only be used with a specific property, not with an object in general`
)
target = getAdministration(thing, propOrHandler)
} else {
return fail(
process.env.NODE_ENV !== "production" &&
`Expected observable map, object or array as first array`
)
}
if (target.dehancer !== undefined)
return fail(
process.env.NODE_ENV !== "production" && `An intercept reader was already established`
)
target.dehancer = typeof propOrHandler === "function" ? propOrHandler : handler
return () => {
target.dehancer = undefined
}
}