-
Notifications
You must be signed in to change notification settings - Fork 2
/
ReactStateMagicMixin.js
82 lines (71 loc) · 1.78 KB
/
ReactStateMagicMixin.js
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
'use strict'
/**
* This mixin automatically sets the state for you based on the key you provide
*
* Usage:
*
* mixins: [ReactStateMagicMixin],
*
* statics: {
* registerStores: {
* foo: FooStore,
* bar: BarStore
* }
* },
*
* render: function () {
* // state will be in the keys you provided
* this.state.foo
* this.state.bar
* }
*
* Alternatively:
*
* statics: {
* registerStore: FooStore
* },
*
* render: function () {
* // all of FooStore's state will be dumped into this.state
* this.state
* }
*/
var Subscribe = require('./Subscribe')
var ReactStateMagicMixin = {
getInitialState: function () {
return this.getStateFromStores()
},
componentDidMount: function () {
Subscribe.create(this)
var stores = this.constructor.registerStores
if (this.constructor.registerStore && this.constructor.registerStores) {
throw new ReferenceError(
'You are attempting to use `registerStore` and `registerStores` ' +
'pick one'
)
}
if (this.constructor.registerStore) {
Subscribe.add(this, this.constructor.registerStore, this.altSetState)
} else {
Object.keys(stores).forEach(function (formatter) {
Subscribe.add(this, stores[formatter], this.altSetState)
}, this)
}
},
componentWillUnmount: function () {
Subscribe.destroy(this)
},
getStateFromStores: function () {
if (this.constructor.registerStore) {
return this.constructor.registerStore.getState()
}
var stores = this.constructor.registerStores
return Object.keys(stores).reduce(function (obj, key) {
return obj[key] = stores[key].getState(), obj
}, {})
},
altSetState: function () {
this.setState(this.getStateFromStores())
}
}
module.exports = ReactStateMagicMixin