1 | var React = require('react');
|
2 | var types = React.PropTypes;
|
3 |
|
4 | module.exports = {
|
5 | contextTypes: {
|
6 | streams: types.object
|
7 | },
|
8 |
|
9 | componentWillMount: function() {
|
10 | this._streams = {};
|
11 | },
|
12 |
|
13 | on: function(propName, cb) {
|
14 | var _streams = this._streams;
|
15 | if (_streams[propName]) _streams[propName].off();
|
16 | var obj = _streams[propName] = {
|
17 | cb: cb,
|
18 | off: noop
|
19 | };
|
20 | var ref = obj.ref = this.props[propName];
|
21 | if (!ref) return null;
|
22 | var streams = this.context.streams;
|
23 | streams.on(ref, cb);
|
24 | obj.off = function() {
|
25 | streams.removeListener(ref, cb);
|
26 | };
|
27 | },
|
28 |
|
29 | componentWillReceiveProps: function(newProps) {
|
30 | var streams = {};
|
31 | var stream, newRef;
|
32 | for (var k in streams) {
|
33 | stream = streams[k];
|
34 | newRef = newProps[k];
|
35 | if (stream.ref === newRef) continue;
|
36 | stream.off();
|
37 | this.on(newRef, stream.cb);
|
38 | }
|
39 | },
|
40 |
|
41 | componentWillUnmount: function() {
|
42 | var streams = this._streams;
|
43 | for (var k in streams) {
|
44 | streams[k].off();
|
45 | }
|
46 | }
|
47 | };
|
48 |
|
49 | function noop(){}
|