forked from mobxjs/mobx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatom.ts
More file actions
77 lines (66 loc) · 1.98 KB
/
Copy pathatom.ts
File metadata and controls
77 lines (66 loc) · 1.98 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
import {
IDerivationState,
IObservable,
createInstanceofPredicate,
endBatch,
getNextId,
noop,
onBecomeObserved,
onBecomeUnobserved,
propagateChanged,
reportObserved,
startBatch
} from "../internal"
export const $mobx = Symbol("mobx administration")
export interface IAtom extends IObservable {
reportObserved()
reportChanged()
}
export class Atom implements IAtom {
isPendingUnobservation = false // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed
isBeingObserved = false
observers = new Set()
diffValue = 0
lastAccessedBy = 0
lowestObserverState = IDerivationState.NOT_TRACKING
/**
* Create a new atom. For debugging purposes it is recommended to give it a name.
* The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management.
*/
constructor(public name = "Atom@" + getNextId()) {}
public onBecomeUnobserved() {
// noop
}
public onBecomeObserved() {
/* noop */
}
/**
* Invoke this method to notify mobx that your atom has been used somehow.
* Returns true if there is currently a reactive context.
*/
public reportObserved(): boolean {
return reportObserved(this)
}
/**
* Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate.
*/
public reportChanged() {
startBatch()
propagateChanged(this)
endBatch()
}
toString() {
return this.name
}
}
export const isAtom = createInstanceofPredicate("Atom", Atom)
export function createAtom(
name: string,
onBecomeObservedHandler: () => void = noop,
onBecomeUnobservedHandler: () => void = noop
): IAtom {
const atom = new Atom(name)
onBecomeObserved(atom, onBecomeObservedHandler)
onBecomeUnobserved(atom, onBecomeUnobservedHandler)
return atom
}