cheatsheets/mobx.md

127 lines
1.8 KiB
Markdown
Raw Permalink Normal View History

2016-12-11 23:06:05 +00:00
---
title: Mobx
category: JavaScript libraries
2020-07-04 13:33:09 +00:00
updated: 2018-05-14
2016-12-11 23:06:05 +00:00
---
### Properties
```js
import {observable, computed} from 'mobx'
class Page {
@observable title = ''
@observable published = false
2016-12-12 03:24:49 +00:00
@observable author = null
2016-12-11 23:06:05 +00:00
@computed get authorName () {
return this.author || 'Anonymous'
}
}
```
2018-05-14 04:45:45 +00:00
### Actions
2016-12-11 23:06:05 +00:00
```js
class Page {
@action publish () {
this.published = true
// do ajax/async here if you like
}
}
```
2018-05-14 04:45:45 +00:00
### Plain objects
2016-12-11 23:06:05 +00:00
```js
const person = observable({
name: 'Ella Fitzgerald'
})
```
```js
const temp = observable(23)
temp.get()
temp.set(25)
temp.observe(...)
```
## Reactions
2018-05-14 04:45:45 +00:00
### Importing
2016-12-11 23:06:05 +00:00
```js
import {autorun, autorunAsync, when} from 'mobx'
```
### autorun()
```js
// Runs it, finds out what it accessed, then observe those
autorun(() => {
console.log(page.title)
})
```
### when()
```js
class Foo {
constructor () {
when(
() => !this.isVisible,
() => this.doSomething())
}
}
```
2016-12-12 03:24:49 +00:00
### expr()
```js
// A temporary computed value. Its result is cached.
render () {
const isPublished = expr(() => page.published === true)
if (isPublished) { ... }
}
```
## [Modifiers](http://mobxjs.github.io/mobx/refguide/modifiers.html)
- `asMap(obj)` - JS map (dynamic keys)
- `asReference(fn)` - don't observe me
- `asStructure(obj)` - JS object (observe as deepEqual)
- `asFlat(array)` - JS array (observe its children)
2016-12-11 23:06:05 +00:00
## React
2018-05-14 04:45:45 +00:00
### mobx-react
2016-12-11 23:06:05 +00:00
```js
import { observer } from 'mobx-react'
@observer
class PageView extends React.Component {
render () {
return <div>{this.props.page.title}</div>
}
}
<PageView page={page} />
```
### Functional components
```js
import { observer } from 'mobx-react'
const PageView = observer(({page}) => {
<div>{page.title}</div>
})
<PageView page={page} />
```
## References
- <https://github.com/mobxjs/mobx>