1- var React = require ( 'react' ) ,
2- io = require ( 'socket.io-client' ) ;
3-
4- var sockets = { } ;
5-
6- module . exports = React . createClass ( {
7- displayName : 'Socket' ,
8- propTypes : {
9- url : React . PropTypes . string ,
10- name : React . PropTypes . string ,
11- options : React . PropTypes . shape ( {
12- reconnection : React . PropTypes . bool ,
13- reconnectionAttempts : React . PropTypes . number ,
14- reconnectionDelay : React . PropTypes . number ,
15- reconnectionDelayMax : React . PropTypes . number ,
16- randomizationFactor : React . PropTypes . number ,
17- timeout : React . PropTypes . number
18- } )
19- } ,
20- getDefaultProps : function ( ) {
21-
22- return {
23- name : 'default' ,
24- options : {
25- forceNew : true
26- }
27- } ;
28- } ,
29- statics : {
30- socket : function ( name ) {
31-
32- name = name || 'default' ;
33-
34- if ( ! sockets . hasOwnProperty ( name ) ) {
35-
36- throw new Error ( 'There is no "' + name + '" socket mounted.' ) ;
37- }
38-
39- return sockets [ name ] ;
40- }
41- } ,
42- componentWillMount : function ( ) {
1+ import React , { Component , PropTypes } from 'react' ;
2+
3+ export const NAME = 'default' ;
4+
5+ const SOCKETS = { } ;
6+
7+ export const has = name => SOCKETS . hasOwnProperty ( name ) ;
8+
9+ export const get = ( name = NAME ) => {
10+
11+ if ( ! has ( name ) ) {
12+
13+ throw new Error ( `There is no "${ name } " socket mounted.` ) ;
14+ }
15+
16+ return SOCKETS [ name ] ;
17+ } ;
18+
19+ class Socket extends Component {
20+
21+ componentWillMount ( ) {
4322
44- if ( sockets . hasOwnProperty ( this . props . name ) ) {
23+ const { name , url , options } = this . props ;
4524
46- throw new Error ( 'Another "' + this . props . name + '" socket is already mounted.' ) ;
25+ if ( has ( name ) ) {
26+
27+ throw new Error ( `Another "${ name } " socket is already mounted.` ) ;
4728 }
4829
49- sockets [ this . props . name ] = io ( this . props . url , this . props . options ) ;
50- } ,
51- componentWillUnmount : function ( ) {
30+ SOCKETS [ name ] = io ( url , options ) ;
31+ }
32+
33+ componentWillUnmount ( ) {
34+
35+ const { name} = this . props ;
36+
37+ SOCKETS [ name ] . disconnect ( ) ;
38+ delete SOCKETS [ name ] ;
39+ }
5240
53- sockets [ this . props . name ] . disconnect ( ) ;
54- delete sockets [ this . props . name ] ;
55- } ,
56- render : function ( ) {
41+ render ( ) {
5742
5843 return false ;
5944 }
60- } ) ;
45+ }
46+
47+ Socket . displayName = 'Socket' ;
48+
49+ Socket . propTypes = {
50+ url : PropTypes . string ,
51+ name : PropTypes . string ,
52+ options : PropTypes . object
53+ } ;
54+
55+ Socket . defaultProps = {
56+ url : '/' ,
57+ name : NAME
58+ } ;
59+
60+ export default Socket ;
0 commit comments