12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- export default {
- install (Vue, options) {
- let ws
- let connected = false
- const eventBus = new Vue({
- methods: {
- send (msg) {
- if (connected === false) {
- console.log('No connection, scheduling message')
- this.$on('open', () => {
- this.$emit('send', msg)
- })
- return
- }
- this.$emit('send', msg)
- },
- recv (cb) {
- this.$on('message', obj => cb(obj))
- }
- }
- })
- const connect = (loc) => {
- ws = new window.WebSocket(loc)
- ws.onopen = () => { connected = true; eventBus.$emit('open') }
- ws.onerror = (e) => { connected = false }
- ws.onclose = (e) => {
- // console.log('Disconnected', e)
- if (connected === true) { } // emit close
- connected = false
- setTimeout(() => connect(loc), 3000) // Reconnect
- }
- ws.onmessage = (e) => { // receiving message
- // console.log('Message received', e)
- eventBus.$emit('message', JSON.parse(e.data))
- }
- }
- connect(options.location)
- eventBus.$on('send', (msg) => {
- ws.send(JSON.stringify(msg))
- })
- Vue.prototype.$ws = eventBus
- }
- }
|