Vue Broadcasting (Part 1)

Broadcast across all Vue instances


Vue comes with the very handy feature of broadcasting events through the  $on  and $emit instance methods.

Generally this is used to communicate between parent and child components. However, often times developers will attach an instance to the global window object to be able to communicate across all Vue instances.

This is a great convenience but let's create a more scoped and portable solution by simply creating an exported VueEvent class:



class VueEvent {
    /**
     * Event broadcaster class constructor.
     *
     * @constructor
     */
    constructor () {
        this.vue = new Vue();
    }

    /**
     * This will emit a broadcast that can be utlized by an active Event listener.
     *
     * @param  Mixed  args The arguments passed to the method
     */
    broadcast (...args) {
        this.vue.$emit(...args);

        return this;
    }

    /**
     * This will instatiate a listener for a broadcast label.
     *
     * @param  String   event    The event label
     * @param  Function callback The passed callback function
     */
    listen (event, callback) {
        this.vue.$on(event, callback);

        return this;
    }
}




// This will be a singleton class
// so we instantiate the export
export default new VueEvent();


Now you can import the class anywhere you need to use the broadcasting event class to communicate between Vue instances!

Stay tuned for Part 2 to see how to implement this convenient helper class...

Comments

Popular posts from this blog

Vue.js: Automatically Import Components

Vue.js vs Angular 1.0 (Part 2)