N
Nuxt7mo ago
BobSty

Event is triggered twice

I have a eventBus.js class which looks like this:
import emitter from 'tiny-emitter/instance'

export default {
$on: (...args) => emitter.on(...args),
$once: (...args) => emitter.once(...args),
$off: (...args) => emitter.off(...args),
$emit: (...args) => emitter.emit(...args)
}
import emitter from 'tiny-emitter/instance'

export default {
$on: (...args) => emitter.on(...args),
$once: (...args) => emitter.once(...args),
$off: (...args) => emitter.off(...args),
$emit: (...args) => emitter.emit(...args)
}
I also have the parent vue component from where I trigger the event, it looks like this:
<template>
<button id="username-button" @click="insertText('{username}')">Username</button>
</template>

<script>
import eventBus from '/eventBus';

export default {
methods: {
insertText(keyword) {
eventBus.$emit('insertKeywords', keyword);
}
}
}
</script>
<template>
<button id="username-button" @click="insertText('{username}')">Username</button>
</template>

<script>
import eventBus from '/eventBus';

export default {
methods: {
insertText(keyword) {
eventBus.$emit('insertKeywords', keyword);
}
}
}
</script>
And I have the child vue component where I listen to the event:
<script>
import eventBus from '/eventBus'
export default {
created() {
eventBus.$on('insertKeywords', (keyword) => {
console.log('why is this called twice???')
})
},
destroyed() {
eventBus.$off('insertKeywords')
}
};
</script>
<script>
import eventBus from '/eventBus'
export default {
created() {
eventBus.$on('insertKeywords', (keyword) => {
console.log('why is this called twice???')
})
},
destroyed() {
eventBus.$off('insertKeywords')
}
};
</script>
So far so good, but the event is always triggered twice for some reason. I checked the Function which is emitting the event, the function is only called once. But for some reason eventBus.$on(...) is always called twice, no matter how often I reload or navigate through pages. Does anyone know why this is happening?
1 Reply
BobSty
BobStyOP7mo ago
Okay, I'm kinda stupid on this one, so the solution is simply to check which instance of the input is currently in use and if the input is not the instance which I want to add the text to simply exit the function. I had 2 instances of the input in use so the event would be send to both of them and the input would always be added from both instances.
Want results from more Discord servers?
Add your server