@@ -3,45 +3,55 @@ import IO from "socket.io-client";
33
44export default {
55
6- install ( Vue , connection = "" , opts ) {
6+ install ( Vue , connection , opts ) {
77
88 let socket ;
99
1010 if ( typeof connection === "object" )
1111 socket = connection ;
1212 else
13- socket = IO ( connection , opts ) ;
13+ socket = IO ( connection || "" , opts ) ;
1414
1515 Vue . prototype . $socket = socket ;
1616
17- Vue . mixin ( {
17+ let addListeners = function ( ) {
18+ if ( this . $options . hasOwnProperty ( "socket" ) ) {
19+ var conf = this . $options . socket ;
20+ if ( conf . namespace ) {
21+ this . $socket = IO ( conf . namespace , conf . options ) ;
22+ }
23+
24+ if ( conf . events ) {
25+ let prefix = conf . prefix || "" ;
26+ Object . keys ( conf . events ) . forEach ( ( key ) => {
27+ let func = conf . events [ key ] . bind ( this ) ;
28+ this . $socket . on ( prefix + key , func ) ;
29+ conf . events [ key ] . __binded = func ;
30+ } ) ;
31+ }
32+ }
33+ }
34+
35+ let removeListeners = function ( ) {
36+ if ( this . $options . hasOwnProperty ( "socket" ) ) {
37+ var conf = this . $options . socket ;
1838
19- beforeCompile ( ) {
20- if ( this . $options . hasOwnProperty ( "socket" ) ) {
21- var conf = this . $options . socket ;
22- if ( conf . events ) {
23- let prefix = conf . prefix || "" ;
24- Object . keys ( conf . events ) . forEach ( ( key ) => {
25- let func = conf . events [ key ] . bind ( this ) ;
26- socket . on ( prefix + key , func ) ;
27- conf . events [ key ] . __binded = func ;
28- } ) ;
29- }
39+ if ( conf . namespace ) {
40+ this . $socket . disconnect ( ) ;
3041 }
31- } ,
32-
33- beforeDestroy ( ) {
34- if ( this . $options . hasOwnProperty ( "socket" ) ) {
35- var conf = this . $options . socket ;
36- if ( conf . events ) {
37- let prefix = conf . prefix || "" ;
38- Object . keys ( conf . events ) . forEach ( ( key ) => {
39- socket . off ( prefix + key , conf . events [ key ] . __binded ) ;
40- } ) ;
41- }
42+
43+ if ( conf . events ) {
44+ let prefix = conf . prefix || "" ;
45+ Object . keys ( conf . events ) . forEach ( ( key ) => {
46+ this . $socket . off ( prefix + key , conf . events [ key ] . __binded ) ;
47+ } ) ;
4248 }
4349 }
50+ }
4451
52+ Vue . mixin ( {
53+ beforeCompile : addListeners ,
54+ beforeDestroy : removeListeners
4555 } ) ;
4656
4757 }
0 commit comments