Skip to content

Event Bus Plugin

File Information

  • Path: plugins/event-bus.js
  • Purpose: Standalone Vue instance for event bus functionality

Overview

The Event Bus plugin exports a standalone Vue instance that can be imported and used as an event bus. Unlike the Bus plugin which attaches to Vue prototype, this plugin provides a direct import for more explicit usage.

Key Features

  1. Standalone Instance

    • Direct import
    • Explicit usage
    • No prototype pollution
  2. Event Bus API

    • $emit - Emit events
    • $on - Listen to events
    • $off - Remove listeners
    • $once - Listen once

Usage Examples

Import and Use

javascript
// In component
import { EventBus } from '~/plugins/event-bus'

export default {
  methods: {
    handleAction() {
      EventBus.$emit('action-performed', data)
    }
  }
}

Listen to Events

javascript
// In component
import { EventBus } from '~/plugins/event-bus'

export default {
  mounted() {
    EventBus.$on('action-performed', this.handleEvent)
  },
  beforeDestroy() {
    EventBus.$off('action-performed', this.handleEvent)
  },
  methods: {
    handleEvent(data) {
      // Handle event
    }
  }
}

In Mixins

javascript
// In mixin
import { EventBus } from '~/plugins/event-bus'

export default {
  methods: {
    emitAnalyticsEvent(data) {
      EventBus.$emit('analytics-event', data)
    }
  }
}

Differences from Bus Plugin

  • Import-based: Requires explicit import
  • No prototype: Doesn't attach to Vue prototype
  • Explicit: More explicit usage pattern
  • Standalone: Independent Vue instance

When to Use

  • When you want explicit imports
  • When avoiding prototype pollution
  • When using in mixins/utilities
  • When you need multiple event buses

Integration Points

  • Components: Event communication
  • Mixins: Event emission
  • Utils: Utility event handling

Notes for Development

  • Plugin exports EventBus instance
  • Must be imported to use
  • More explicit than $bus
  • Same API as Vue events
  • Remember to cleanup listeners