-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdispatchOn.js
70 lines (59 loc) · 1.95 KB
/
dispatchOn.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
import React, { Component, PropTypes } from 'react';
import { Subscription } from 'rxjs/Subscription';
const $$reduxObservableSubscription = '@@reduxObservableSubscription';
const dispatchFactories = (subscription, store, factories, args) => {
factories.map(factory => store.dispatch(factory(...args)))
.forEach(sub => sub && subscription.add(sub));
};
export function dispatchOn({
willMount = null,
mount = null,
update = null,
willRecieveProps = null
}) {
return (ComposedComponent) =>
class DispatchOnMountComponent extends Component {
constructor(props) {
super(props);
}
static contextTypes = {
store: PropTypes.object.isRequired
}
getSubscription() {
const subscription = this[$$reduxObservableSubscription];
if (!subscription || subscription.isUnsubscribed) {
this[$$reduxObservableSubscription] = new Subscription();
}
return this[$$reduxObservableSubscription];
}
componentWillMount() {
if (willMount) {
dispatchFactories(this.getSubscription(), this.context.store, willMount, [this.props]);
}
}
componentDidMount() {
if (mount) {
dispatchFactories(this.getSubscription(), this.context.store, mount, [this.props]);
}
}
componentDidUpdate(prevProps) {
if (update) {
dispatchFactories(this.getSubscription(), this.context.store, update, [this.props, prevProps]);
}
}
componentWillReceiveProps(nextProps) {
if (willRecieveProps) {
dispatchFactories(this.getSubscription(), this.context.store, willRecieveProps, [this.props, nextProps]);
}
}
componentWillUnmount() {
const subscription = this[$$reduxObservableSubscription];
if (subscription) {
subscription.unsubscribe();
}
}
render() {
return (<ComposedComponent {...this.props} />);
}
};
}