Instantly share code, notes, and snippets.

@jeffochoa /event.js
Last active Nov 19, 2018

Embed
What would you like to do?
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment