forked from goatslacker/alt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connectToStores.js
96 lines (86 loc) · 2.56 KB
/
connectToStores.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* 'Higher Order Component' that controls the props of a wrapped
* component via stores.
*
* Expects the Component to have two static methods:
* - getStores(): Should return an array of stores.
* - getPropsFromStores(props): Should return the props from the stores.
*
* Example using old React.createClass() style:
*
* const MyComponent = React.createClass({
* statics: {
* getStores(props) {
* return [myStore]
* },
* getPropsFromStores(props) {
* return myStore.getState()
* }
* },
* render() {
* // Use this.props like normal ...
* }
* })
* MyComponent = connectToStores(MyComponent)
*
*
* Example using ES6 Class:
*
* class MyComponent extends React.Component {
* static getStores(props) {
* return [myStore]
* }
* static getPropsFromStores(props) {
* return myStore.getState()
* }
* render() {
* // Use this.props like normal ...
* }
* }
* MyComponent = connectToStores(MyComponent)
*
* A great explanation of the merits of higher order components can be found at
* http://bit.ly/1abPkrP
*/
import React from 'react'
import { assign, isFunction } from './functions'
function connectToStores(Spec, Component = Spec) {
// Check for required static methods.
if (!isFunction(Spec.getStores)) {
throw new Error('connectToStores() expects the wrapped component to have a static getStores() method')
}
if (!isFunction(Spec.getPropsFromStores)) {
throw new Error('connectToStores() expects the wrapped component to have a static getPropsFromStores() method')
}
const StoreConnection = React.createClass({
getInitialState() {
return Spec.getPropsFromStores(this.props, this.context)
},
componentWillReceiveProps(nextProps) {
this.setState(Spec.getPropsFromStores(nextProps, this.context))
},
componentDidMount() {
const stores = Spec.getStores(this.props, this.context)
this.storeListeners = stores.map((store) => {
return store.listen(this.onChange)
})
if (Spec.componentDidConnect) {
Spec.componentDidConnect(this.props, this.context)
}
},
componentWillUnmount() {
this.storeListeners.forEach(unlisten => unlisten())
},
onChange() {
this.setState(Spec.getPropsFromStores(this.props, this.context))
},
render() {
return React.createElement(
Component,
assign({}, this.props, this.state)
)
}
})
return StoreConnection
}
export default connectToStores