Skip to content

Instantly share code, notes, and snippets.

@jeffochoa
Last active April 13, 2023 19:55
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffochoa/1140c58f1548adff37672c26f76b2a89 to your computer and use it in GitHub Desktop.
Save jeffochoa/1140c58f1548adff37672c26f76b2a89 to your computer and use it in GitHub Desktop.
VueJs global event dispatcher

Use Example

const GlobalEvent = require('./event');
window.Event = new GlobalEvent();

Then you can listen for events from other Vue components

export default {
    methods: {
        myHandler() {
            alert('Do something');
        }
    },
    created() {
        Event.listen('myEvent', (data) => this.myHandler(data));
    }
}

Also you can fire those events from anywhere

Event.fire('myEvent', {foo: "bar"});

Learn more

This was taken from laracasts: Component Communication Example #2: Event Dispatcher

class Event {
constructor() {
this.vue = new Vue();
}
fire(event, data = null) {
this.vue.$emit(event, data);
}
listen(event, callback) {
this.vue.$on(event, callback);
}
}
module.exports = Event;
@bolatk
Copy link

bolatk commented Mar 4, 2021

Hi @jeffochoa. Thank you for a gist. Where should I paste const GlobalEvent = require('./event'); ?

@ahmad-moussawi
Copy link

@bolatk anyplace global to the application, like the initial app.js file

@islem41
Copy link

islem41 commented Apr 13, 2023

Thx, simple and clean, good job !!!

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