Firing Vue.JS Events into Outer Space or How To Make My Legacy JS Code React on Vue JS Events

Sometimes (or even often) you'll want to emit your Vue app events outside of the scope of the app. For example, it may be useful when you want some legacy jQuery script to be notified about event happened in Vue app.

I found the following pattern to be the easiest solution: it's called "Event Bus" pattern.

What we need to do is to create an empty Vue app instance and assign it to a property of a global window object:

1
  1. window.eventBus = new Vue();

Take a note that this should happen before you init your original VUE app.

After doing this, you can now emit any event from any component of your app, but instead of doing something like: this.$emit('dataLoaded', data) which will be scoped within your VUE app, you send it into outter space (aka global variable) like this:

1
  1. window.eventBus.$emit('dataLoaded', data);

The remaining thing is just to catch the event in your legacy jQuery code, you can do it like this:

1
2
3
  1. window.eventBus.$on('dataLoaded', function(data) {
  2. // react on the event somehow
  3. });

That's it.