修饰器

什么是observable?

一种让数据的变化可以被观察的方法(原始类型,对象,数组,map)
mobx常用api-对可观察的数据做出反应,观察数据变化的方式computed,autorun,when,reaction

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
95
96
97
98
99
100
101
102
103
import {computed, extendObservable, isArrayLike, observable, autorun, when, reaction, action, runInAction} from 'mobx'

//array object map
const arr = observable(['a', 'b', 'c'])
console.log(arr, Array.isArray(arr), isArrayLike(arr), arr[1])

const obj = observable({'a': 1, 'b': 2})
//新增属性
// extendObservable({'c': 3})
console.log(obj.a, obj.b)

const map = observable(new Map())
map.set('a', 1)
console.log(map)
console.log(map.has('a'))
map.delete('a')
console.log(map.has('a'))

// 基本数据类型必须要用observable.box

var num = observable.box(20)
var str = observable.box('hello')
var bool = observable.box(true)
str.set('world')
console.log(num.get(), str.get(), bool)


class Store {
@observable array = []
@observable obj = {}
@observable map = new Map()

@observable string = 'hello'
@observable number = 20
@observable bool = false
@observable _bool = true

@computed get mixed() {
return store.string + '+' + store.number
}

@action bar() {
this.string = 'hello bar world'
this.number = 1010

}

@action.bound winBar() {
this.string = 'bound world'
this.number = 900
}
}

// 观察数据变化的方法
// computed,autorun,when,reaction

// computed将多个可观察数据组合成一个可观察数据
var store = new Store()
var foo = computed(() => {
return store.string + '+' + store.number
})
foo.observe(change => { //监听
console.log(change)
})
store.string = "world"
store.number = 40
console.log(foo.get()) //hello+20

// autorun自动追踪其所引用的观察数据,在数据发生变化的时候,重新触发
autorun(() => {
console.log(store.string + '+' + store.number)
console.log(store.mixed)
})
store.string = 'hello world'
store.number = 100

// when提供了条件执行逻辑,autorun的一种变种
when(() => store.bool, () => console.log('it true'))
store.bool = true


console.log('before')
when(() => store._bool, () => console.log('true true'))
console.log('after')

// reaction分离可观察数据声明,以副作用的方式对autorun做出改进
reaction(() => [store.string, store.number], arr => console.log(arr.join('')))
store.string = 'big world'
store.number = 90

// 修改可观察数据action
store.bar()
store.winBar()

runInAction(() => {
store.string = 'runInActive world'
store.number = 444
})

runInAction('modify', () => {
store.string = 'runInActive modify world'
store.number = 333
})