Reputation: 1238
There is a function in vuex file like below.
When I run start function using 'Button' of Vue component,
socket.emit sends the data to socker of nodejs.
And it receives some result through socket.on by websocket of nodejs.
// In vuex.js
const actions = {
start(event) {
socket.emit("voice", {
msg: event.currentTarget.message
});
socket.on("voice-reply", result => {
console.log(result);
});
}
But when I run this start function with button of vuejs,
socket.on("voice-reply") is repeated one more time.
For example,
console.log(result)
after button click,
console.log(result)
console.log(result)
after button click,
console.log(result)
console.log(result)
console.log(result)
it runs like this. Could you explain why socket.on is run increasing one more time?
Thank you so much for reading it.
Upvotes: 1
Views: 526
Reputation: 63139
socket.on
creates an eventListener
which fires every time the event is emitted. By including socket.on
in your start
action, you are creating a new eventListener
every time you call start
(by clicking the button), and each one of those listeners logs to the console. You shouldn't be creating a listener in the same block of emitting the event.
Create a new action like setupListeners
and call that only once from somewhere else, maybe in your component (such as in the created
lifecycle hook) or from some other action:
const actions = {
start(event) {
socket.emit("voice", {
msg: event.currentTarget.message
});
},
setupListeners() {
socket.on("voice-reply", result => {
console.log(result);
});
}
}
Upvotes: 1