tj
2025-06-05 bba272999cc546f65781bf3d20245a3f819af67f
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/* Author: https://github.com/nathantsoi/vue-native-websocket */
import Notify from './notify.vue'
import Observer from './observer'
import Emitter from './emitter'
 
export default {
  install(app, connection, opts = {}) {
    if (typeof connection === 'object') {
      // eslint-disable-next-line no-param-reassign
      opts = connection
      // eslint-disable-next-line no-param-reassign
      connection = ''
    }
    let observer = null
 
    opts.$setInstance = wsInstance => {
      app.config.globalProperties.$socket = wsInstance
    }
    app.config.globalProperties.$connect = (connectionUrl = connection, connectionOpts = opts) => {
      connectionOpts.$setInstance = opts.$setInstance
      observer = new Observer(connectionUrl, connectionOpts)
      app.config.globalProperties.$socket = observer.WebSocket
    }
 
    app.config.globalProperties.$disconnect = () => {
      if (observer?.reconnection) {
        observer.reconnection = false
      }
      if (app.config.globalProperties.$socket) {
        app.config.globalProperties.$socket.close()
        delete app.config.globalProperties.$socket
      }
    }
    const hasProxy = typeof Proxy !== 'undefined' && typeof Proxy === 'function' && /native code/.test(Proxy.toString())
    app.component('LinNotify', Notify)
    app.mixin({
      created() {
        const vm = this
        const { sockets } = this.$options
 
        if (hasProxy) {
          this.$options.sockets = new Proxy(
            {},
            {
              set(target, key, value) {
                Emitter.addListener(key, value, vm)
                target[key] = value
                return true
              },
              deleteProperty(target, key) {
                Emitter.removeListener(key, vm.$options.sockets[key], vm)
                delete target.key
                return true
              },
            },
          )
          if (sockets) {
            Object.keys(sockets).forEach(key => {
              this.$options.sockets[key] = sockets[key]
            })
          }
        } else {
          Object.seal(this.$options.sockets)
 
          // if !hasProxy need addListener
          if (sockets) {
            Object.keys(sockets).forEach(key => {
              Emitter.addListener(key, sockets[key], vm)
            })
          }
        }
      },
      beforeUnmount() {
        if (hasProxy) {
          const { sockets } = this.$options
 
          if (sockets) {
            Object.keys(sockets).forEach(key => {
              delete this.$options.sockets[key]
            })
          }
        }
      },
    })
  },
}