-
Notifications
You must be signed in to change notification settings - Fork 2
/
FluxyMixin.js
81 lines (74 loc) · 1.66 KB
/
FluxyMixin.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
'use strict'
/**
* This mixin lets you setup your listeners. It is similar to Fluxible's mixin.
*
* Usage:
*
* mixins: [FluxyMixin],
*
* statics: {
* storeListeners: {
* doFoo: FooStore,
* doBar: BarStore
* }
* },
*
* doFoo: function (storeState) {
* this.setState({ foo: FooStore.getState() })
* },
*
* doBar: function (storeState) { },
*
* render: function () {
* // state will be in the keys you provided
* this.state.foo
* }
*
* ----
*
* You can also pass in an Array of stores to storeListeners:
*
* statics: {
* storeListeners: [FooStore, BarStore]
* }
*
* Changes will then be passed to a function `onChange` which you will have
* to define:
*
* onChange() {
* this.setState({
* foo: FooStore.getState(),
* bar: BarStore.getState()
* })
* }
*/
var Subscribe = require('./Subscribe')
var FluxyMixin = {
componentDidMount: function () {
Subscribe.create(this)
var stores = this.constructor.storeListeners
if (Array.isArray(stores)) {
if (!this.onChange) {
throw new ReferenceError(
'onChange should exist in your React component but is not defined'
)
}
stores.forEach(function (store) {
Subscribe.add(this, store, this.onChange)
}, this)
} else {
Object.keys(stores).forEach(function (handler) {
if (!this[handler]) {
throw new ReferenceError(
handler + ' does not exist in your React component'
)
}
Subscribe.add(this, stores[handler], this[handler])
}, this)
}
},
componentWillUnmount: function () {
Subscribe.destroy(this)
}
}
module.exports = FluxyMixin