1

I am Using Vue.js as the front-end framework.

I am adding the socket.io listener on a component using created life-cycle hook.

created () {
    // socket listener
    this.$socket.on('event', (response) => { .... })
}

Now if the component is unmounted and later remounted then two listener are created.

I tried using "once" in place of "on" but same problem.

How Can I make sure that only one Listener is active?

Note: The socket component is added to Vue as Instance Property.

Bert
  • 80,741
  • 17
  • 199
  • 164
sam23
  • 589
  • 2
  • 7
  • 23

1 Answers1

1

You don't say what $socket is, but the way you handle this is to remove the listener when the component is destroyed.

methods:{
  handleEvent(response) { ... }
},
created(){
  this.$socket.on('event', this.handleEvent)
},
beforeDestroy(){
  // using "removeListener" here, but this should be whatever $socket provides
  // for removing listeners
  this.$socket.removeListener('event', this.handleEvent)
}

I based the method removeListener off of this answer but it may be some other method for removing listeners depending on your library.

Bert
  • 80,741
  • 17
  • 199
  • 164
  • Thanks for the response. The $socket holds the IO Object created during connection. I will try your solution and mark it as correct if it works. – sam23 Dec 07 '17 at 15:27