forked from mobxjs/mobx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathactiondecorator.ts
More file actions
94 lines (90 loc) · 3.17 KB
/
Copy pathactiondecorator.ts
File metadata and controls
94 lines (90 loc) · 3.17 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { fail, addHiddenFinalProp } from "../utils/utils"
import { createAction } from "../core/action"
import { BabelDescriptor } from "../utils/decorators2"
import { action, defineBoundAction } from "./action"
function dontReassignFields() {
fail(process.env.NODE_ENV !== "production" && "@action fields are not reassignable")
}
export function namedActionDecorator(name: string) {
return function(target, prop, descriptor: BabelDescriptor) {
if (descriptor) {
if (process.env.NODE_ENV !== "production" && descriptor.get !== undefined) {
return fail("@action cannot be used with getters")
}
// babel / typescript
// @action method() { }
if (descriptor.value) {
// typescript
return {
value: createAction(name, descriptor.value),
enumerable: false,
configurable: false,
writable: true // for typescript, this must be writable, otherwise it cannot inherit :/ (see inheritable actions test)
}
}
// babel only: @action method = () => {}
const { initializer } = descriptor
return {
enumerable: false,
configurable: false,
writable: false,
initializer() {
// N.B: we can't immediately invoke initializer; this would be wrong
return createAction(name, initializer!.call(this))
}
}
}
// bound instance methods
return actionFieldDecorator(name).apply(this, arguments)
}
}
export function actionFieldDecorator(name: string) {
// Simple property that writes on first invocation to the current instance
return function(target, prop, descriptor) {
Object.defineProperty(target, prop, {
configurable: true,
enumerable: false,
get() {
return undefined
},
set(value) {
addHiddenFinalProp(this, prop, action(name, value))
}
})
}
}
export function boundActionDecorator(target, propertyName, descriptor, applyToInstance?: boolean) {
if (applyToInstance === true) {
defineBoundAction(target, propertyName, descriptor.value)
return null
}
if (descriptor) {
// if (descriptor.value)
// Typescript / Babel: @action.bound method() { }
// also: babel @action.bound method = () => {}
return {
configurable: true,
enumerable: false,
get() {
defineBoundAction(
this,
propertyName,
descriptor.value || descriptor.initializer.call(this)
)
return this[propertyName]
},
set: dontReassignFields
}
}
// field decorator Typescript @action.bound method = () => {}
return {
enumerable: false,
configurable: true,
set(v) {
defineBoundAction(this, propertyName, v)
},
get() {
return undefined
}
}
}