Skip to content

Instantly share code, notes, and snippets.

@JonasDoebertin
Last active May 28, 2021 12:16
Show Gist options
  • Save JonasDoebertin/e87cb10df9393c3fb4c99731191cad23 to your computer and use it in GitHub Desktop.
Save JonasDoebertin/e87cb10df9393c3fb4c99731191cad23 to your computer and use it in GitHub Desktop.
Building a global event bus for Vue.js
// Using the most basic event bus
import Vue from 'vue';
import Bus from './basic';
Vue.component('my-first-component', {
methods: {
sampleClickAction() {
Bus.$emit('my-sample-event');
}
}
});
Vue.component('my-second-component', {
created() {
Bus.$on('my-sample-event', () => {
// Do something…
});
}
});
// The most basic event bus
// Imprt vue.js
import Vue from 'vue';
// Create empty vue.js instance to use as event bus
const Bus = new Vue({});
// Export event bus instance
export default Bus;
@FernandoBasso
Copy link

Nice. What about for unit testing this global event bus? How would one go about doing it?

@serdydev
Copy link

Do not forget the .$off in beforeDestroy to avoid memory leak

@blaskovicz
Copy link

blaskovicz commented Oct 14, 2018

Another example, using the bus in a slightly different way.

// events.ts
import { Component, Vue } from "vue-property-decorator";
import debounce from "debounce";

// b-img-lazy nested inside b-carousel issue
// see https://github.com/bootstrap-vue/bootstrap-vue/issues/1210
const updateCarouselImages = debounce(() => {
  window.dispatchEvent(new Event("scroll"));
}, 100);

@Component
class EventBus extends Vue {
  created() {
    this.$on("b:carousel:img:next", updateCarouselImages);
  }
  beforeDestroy() {
    this.$off("b:carousel:img:next", updateCarouselImages);
  }
}

export default new EventBus();
// thumbnail.ts
import { Component, Vue } from "vue-property-decorator";
import eventBus from "@/lib/events";
@Component
export default class Thumbnail extends Vue {
  mounted() {
    eventBus.$emit("b:carousel:img:next");
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment