Search code examples
vue.jsvue-componentevent-bus

Aliases for event bus $emit


I would like to create aliases for the commonly used event bus methods $emit, $on, etc...

so that I could reference the event bus object like so: EventBus.publish(...)

I tried:

import Vue from 'vue'
const EventBus = new Vue()

export const publish = EventBus.$emit
export const subscribe = EventBus.$on

and then:

import * as EventBus from '@/utils/eventBus.js'

but i'm getting $emit is not a function

What am I doing wrong?

thanks


Solution

  • Make sure you bind to the object otherwise the method won't work:

    import Vue from 'vue'
    const EventBus = new Vue()
    
    export const publish = EventBus.$emit.bind(EventBus)
    export const subscribe = EventBus.$on.bind(EventBus)
    export const unsubscribe = EventBus.$off.bind(EventBus)
    

    or more explicitly:

    export function publish(name, ...args) {
      EventBus.$emit(name, ...args)
    }
    
    export function subscribe(name, fn) {
      EventBus.$on(name, fn)
    }
    
    export function unsubscribe(name, fn) {
      EventBus.$off(name, fn)
    }
    

    You import it like this:

    import * as EventBus from './eventBus.js'
    
    EventBus.subscribe('event', handler)