Skip to content Skip to sidebar Skip to footer

How To Listen To All Custom Events In Vuejs?

In my VueJS app I have a Vue instance which I'm using as an event bus for sending data between components. It's just this: import Vue from 'vue'; export const EventBus = new Vue();

Solution 1:

If you're in an ES6 context, you could take either of below approaches. I explain through comments.

Override through inheritance

'use strict'importVuefrom'vue'exportclassEventBusextendsVue {
  // Register a custom callback as meddler that gets called upon each event emission.// It can be bound to $on as well. 
  $meddle (callback) {
    this.meddler = callback
  }

  // Override Vue's $emit to call the custom meddler callback upon each event emission.
  $emit (event, ...args) {
    if (this.meddler && typeofthis.meddler.call === 'function') {
      this.meddler(event, ...args)
    }

    returnsuper.$emit(event, ...args)
  }

  // We can also override $on() to listen to callbacks being registered.
}

exportdefaultnewEventBus()

Override through hijacking

Or using a "hijacking" factory class in case you don't want your Vue event bus to be wrapped. The logic is basically the same, however, in this approach we hijack, or in other words, monkey patch the methods instead of overriding them directly.

'use strict'importVuefrom'vue'classEventBusFactory {
  static create () {
    returnthis.hijack(newVue())
  }

  static hijack (bus) {
    bus.$meddle = callback => {
      bus.meddler = callback
    }

    const orig$emit = bus.$emit
    bus.$emit = (event, ...args) => {
      if (bus.meddler && typeof bus.meddler.call === 'function') {
        bus.meddler(event, ...args)
      }

      orig$emit.call(bus, event, ...args)
    }

    return bus
  }
}

exportdefaultEventBusFactory.create()

Solution 2:

The author of VueJS provided a hacky solution for listening to all events:

var oldEmit = this.compiler.emitter.emitthis.compiler.emitter.emit = function () {
    console.log('got event: ' + arguments[0])
    oldEmit.apply(this, arguments)
}

Another solution (which is said to also work on v1.0):

const old_on = this.$on;
this.$on = (...args) => {
  // custom logic here like pushing to a callback array or something
  old_on.apply(this, args);
};

Post a Comment for "How To Listen To All Custom Events In Vuejs?"