Skip to content

Instantly share code, notes, and snippets.

@juliovedovatto
Created November 24, 2021 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliovedovatto/7fd583b1234002235597519d0feadf99 to your computer and use it in GitHub Desktop.
Save juliovedovatto/7fd583b1234002235597519d0feadf99 to your computer and use it in GitHub Desktop.
Vue 2 Event Bus, using mitt library
/**
* Vue 2 Plugin to add event bus support, using mitt library
* @see https://github.com/developit/mitt
*
* @author Julio Vedovartto <juliovedovatto@gmail.com>
* @license MIT
*/
import mitt from 'mitt'
const emitter = mitt()
// export emitter instance
export const EventEmitter = {
...emitter,
// inject $on, $off and $emit aliases to the created mitt object
$on: emitter.on,
$off: emitter.off,
$emit: emitter.emit,
// inject "$once" event handler, since mitt does not support it
$once(type, handler) {
const fn = (...args) => {
this.off(type, fn)
handler(args)
}
this.on(type, fn)
}
}
/**
* Add Vue support to use event bus
* Example: this.$bus.$on / this.$bus.$off / this.$bus.$emit / this.$bus.$once
*
* @param {Vue} instance
*/
function install(instance) {
Object.defineProperty(instance.prototype, '$bus', {
get() {
return EventEmitter
}
})
}
export default { install }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment