Skip to content

Instantly share code, notes, and snippets.

@yavuztas
Last active January 7, 2021 22:17
Show Gist options
  • 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)
}
}
@dumedeiros
Copy link

What do you think of:

  publish (event) {
    if (event instanceof Function) {
      this.$eventBus.$emit(event.name)
    }else{
      this.$eventBus.$emit(event.constructor.name, event)
    }
  }

and with that we have two options to listen to an event:

  1. EventBus.listen(new CodeChangeEvent(editor, "some code here..."))
    when we really want to pass an instance of that event or...

  2. 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())

@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