1 | 'use strict';
|
2 |
|
3 | var React = require('react'),
|
4 | invariant = require('react/lib/invariant'),
|
5 | shallowEqual = require('react/lib/shallowEqual');
|
6 |
|
7 | function createSideEffect(onChange, mixin) {
|
8 | invariant(
|
9 | typeof onChange === 'function',
|
10 | 'onChange(propsList) is a required argument.'
|
11 | );
|
12 |
|
13 | var mountedInstances = [];
|
14 |
|
15 | function emitChange() {
|
16 | onChange(mountedInstances.map(function (instance) {
|
17 | return instance.props;
|
18 | }));
|
19 | }
|
20 |
|
21 | return React.createClass({
|
22 | mixins: [mixin],
|
23 |
|
24 | statics: {
|
25 | dispose: function () {
|
26 | mountedInstances = [];
|
27 | emitChange();
|
28 | }
|
29 | },
|
30 |
|
31 | shouldComponentUpdate: function (nextProps) {
|
32 | return !shallowEqual(nextProps, this.props);
|
33 | },
|
34 |
|
35 | componentWillMount: function () {
|
36 | mountedInstances.push(this);
|
37 | emitChange();
|
38 | },
|
39 |
|
40 | componentDidUpdate: function () {
|
41 | emitChange();
|
42 | },
|
43 |
|
44 | componentWillUnmount: function () {
|
45 | var index = mountedInstances.indexOf(this);
|
46 | mountedInstances.splice(index, 1);
|
47 | emitChange();
|
48 | },
|
49 |
|
50 | render: function () {
|
51 | if (this.props.children) {
|
52 | return React.Children.only(this.props.children);
|
53 | } else {
|
54 | return null;
|
55 | }
|
56 | }
|
57 | });
|
58 | }
|
59 |
|
60 | module.exports = createSideEffect; |
\ | No newline at end of file |