Skip to content

Instantly share code, notes, and snippets.

@yavuztas
Last active January 7, 2021 22:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yavuztas/d1300752057de9314c8614d6a82ccc39 to your computer and use it in GitHub Desktop.
Save yavuztas/d1300752057de9314c8614d6a82ccc39 to your computer and use it in GitHub Desktop.
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)
}
}
@yavuztas
Copy link
Author

yavuztas commented Jan 7, 2021

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