Skip to content

Instantly share code, notes, and snippets.

@yavuztas yavuztas/vue-event-bus.js
Last active Nov 24, 2019

Embed
What would you like to do?
add handler method this scope capability
/**
* A Simple EventBus Plugin for Vue
*/
export default {
$eventBus: null,
install (Vue) {
this.$eventBus = new Vue()
},
listen (eventClass, handler, scope) {
if (scope) {
handler.$scoped = event => handler.call(scope, event)
this.$eventBus.$on(eventClass.name, handler.$scoped)
} else {
this.$eventBus.$on(eventClass.name, handler)
}
},
listenOnce (eventClass, handler, scope) {
if (scope) {
handler.$scoped = event => handler.call(scope, event)
this.$eventBus.$once(eventClass.name, handler.$scoped)
} else {
this.$eventBus.$once(eventClass.name, handler)
}
},
remove (eventClass, handler) {
if (handler) {
let callback = (handler.$scoped)?handler.$scoped:handler
this.$eventBus.$off(eventClass.name, callback)
} else {
this.$eventBus.$off(eventClass.name)
}
},
removeAll () {
this.$eventBus.$off()
},
publish (event) {
this.$eventBus.$emit(event.constructor.name, event)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.