1 | import {
|
2 | CreateObservableOptions,
|
3 | isObservableMap,
|
4 | AnnotationsMap,
|
5 | startBatch,
|
6 | endBatch,
|
7 | asObservableObject,
|
8 | isPlainObject,
|
9 | ObservableObjectAdministration,
|
10 | isObservable,
|
11 | die,
|
12 | getOwnPropertyDescriptors,
|
13 | $mobx,
|
14 | ownKeys
|
15 | } from "../internal"
|
16 |
|
17 | export function extendObservable<A extends Object, B extends Object>(
|
18 | target: A,
|
19 | properties: B,
|
20 | annotations?: AnnotationsMap<B, never>,
|
21 | options?: CreateObservableOptions
|
22 | ): A & B {
|
23 | if (__DEV__) {
|
24 | if (arguments.length > 4) die("'extendObservable' expected 2-4 arguments")
|
25 | if (typeof target !== "object")
|
26 | die("'extendObservable' expects an object as first argument")
|
27 | if (isObservableMap(target))
|
28 | die("'extendObservable' should not be used on maps, use map.merge instead")
|
29 | if (!isPlainObject(properties))
|
30 | die(`'extendObservable' only accepts plain objects as second argument`)
|
31 | if (isObservable(properties) || isObservable(annotations))
|
32 | die(`Extending an object with another observable (object) is not supported`)
|
33 | }
|
34 |
|
35 | const descriptors = getOwnPropertyDescriptors(properties)
|
36 |
|
37 | const adm: ObservableObjectAdministration = asObservableObject(target, options)[$mobx]
|
38 | startBatch()
|
39 | try {
|
40 | ownKeys(descriptors).forEach(key => {
|
41 | adm.extend_(
|
42 | key,
|
43 | descriptors[key as any],
|
44 |
|
45 | !annotations ? true : key in annotations ? annotations[key] : true
|
46 | )
|
47 | })
|
48 | } finally {
|
49 | endBatch()
|
50 | }
|
51 | return target as any
|
52 | }
|