Reputation: 599
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.
Upvotes: 1
Views: 2124
Reputation: 82489
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.
Upvotes: 1