A
A
antimodern2019-02-19 22:20:24
Socket.io
antimodern, 2019-02-19 22:20:24

How to get rid of duplicate socket subscriptions? How to use socket.io in SPA?

A simple Vue application. Two routes: subscription occurs on one route

beforeMount () {
    socket.emit('subscribeToTimer', 1000)
    socket.on('timer', timestamp => {
      this.timestamp = timestamp
      this.countEvents++
    })
  }

The connection itself is moved to App.vueso as not to duplicate it again in each component.
beforeMount () {
    console.log('socket work')
    socket.on('connect', () => {
      console.log('CONNECTION STATUS:', socket.connected)
      console.log('SOCKET:', socket.id)
    })
    socket.on('disconnect', () => {
      console.log('DISCONNECTION STATUS:', socket.disconnected)
    })
    socket.open()
  }

And here the problem begins - if you come to this route again, then the subscription occurs again. And so every time. It turns out that the websocket connection hangs open and the client subscribes many times to the same event. As a result, I get not one update per second of the timer, but 100500.
How should I?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
grinat, 2019-02-19
@grinat

You must also have a subscription in one place, or you must unsubscribe after the person leaves the route.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question