OSDN Git Service

Regular updates
[twpd/master.git] / mobx.md
1 ---
2 title: Mobx
3 category: JavaScript libraries
4 layout: 2017/sheet
5 updated: 2018-05-14
6 ---
7
8 ### Properties
9
10 ```js
11 import {observable, computed} from 'mobx'
12
13 class Page {
14   @observable title = ''
15   @observable published = false
16   @observable author = null
17
18   @computed get authorName () {
19     return this.author || 'Anonymous'
20   }
21 }
22 ```
23
24 ### Actions
25
26 ```js
27 class Page {
28   @action publish () {
29     this.published = true
30     // do ajax/async here if you like
31   }
32 }
33 ```
34
35 ### Plain objects
36
37 ```js
38 const person = observable({
39   name: 'Ella Fitzgerald'
40 })
41 ```
42
43 ```js
44 const temp = observable(23)
45 temp.get()
46 temp.set(25)
47 temp.observe(...)
48 ```
49
50 ## Reactions
51
52 ### Importing
53
54 ```js
55 import {autorun, autorunAsync, when} from 'mobx'
56 ```
57
58 ### autorun()
59
60 ```js
61 // Runs it, finds out what it accessed, then observe those
62 autorun(() => {
63   console.log(page.title)
64 })
65 ```
66
67 ### when()
68
69 ```js
70 class Foo {
71   constructor () {
72     when(
73       () => !this.isVisible,
74       () => this.doSomething())
75   }
76 }
77 ```
78
79 ### expr()
80
81 ```js
82 // A temporary computed value. Its result is cached.
83 render () {
84   const isPublished = expr(() => page.published === true)
85   if (isPublished) { ... }
86 }
87 ```
88
89 ## [Modifiers](http://mobxjs.github.io/mobx/refguide/modifiers.html)
90
91 - `asMap(obj)` - JS map (dynamic keys)
92 - `asReference(fn)` - don't observe me
93 - `asStructure(obj)` - JS object (observe as deepEqual)
94 - `asFlat(array)` - JS array (observe its children)
95
96 ## React
97
98 ### mobx-react
99
100 ```js
101 import { observer } from 'mobx-react'
102
103 @observer
104 class PageView extends React.Component {
105   render () {
106     return <div>{this.props.page.title}</div>
107   }
108 }
109
110 <PageView page={page} />
111 ```
112
113 ### Functional components
114
115 ```js
116 import { observer } from 'mobx-react'
117
118 const PageView = observer(({page}) => {
119   <div>{page.title}</div>
120 })
121
122 <PageView page={page} />
123 ```
124
125 ## References
126
127 - <https://github.com/mobxjs/mobx>