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 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) | |
} | |
} |
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:
const APP_START_EVENT = new AppStartEvent()
//...
EventBus.publish(APP_START_EVENT)
Thus, we can keep the benefit of layering and easily intercept event calls. An example use-case would be localization:
export class TerminateResultEvent {
constructor(success, message = ""){
this.success = success
this.message = Locale.getMessage(message)
}
}
EventBus.publish(new TerminateResultEvent(false, "app.error.msg1"))
By the way, I guess you mean the publish
method when you write listen
. Otherwise, listening an object instance doesn't make sense to me.
Cheers!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What do you think of:
and with that we have two options to listen to an event:
EventBus.listen(new CodeChangeEvent(editor, "some code here..."))
when we really want to pass an instance of that event or...
EventBus.listen(AppStartEvent)
when we DON'T want to pass an event instance, but only the imported function (in this case, only the name matters), instead of using
EventBus.listen(new AppStartEvent())