Last active
January 7, 2021 22:17
-
-
Save yavuztas/d1300752057de9314c8614d6a82ccc39 to your computer and use it in GitHub Desktop.
add handler method this scope capability
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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
I got the purpose of your doing. But, instead of modifying the
publish
method I would define a constant (somewhere proper) in my application and re-use it:Thus, we can keep the benefit of layering and easily intercept event calls. An example use-case would be localization:
By the way, I guess you mean the
publish
method when you writelisten
. Otherwise, listening an object instance doesn't make sense to me.Cheers!