Mahmud Adam Mahmud Adam - 5 months ago 345
Javascript Question

Vue.js global event bus

I am trying to create a global event bus so that two sibling components can communicate with each other. I have searched around; however, I cannot find any examples of how to implement one. This is what I have so far:

var bus = new Vue();

Vue.component('Increment', {
template: "#inc",
data: function() {
return ({count: 0})
},
methods: {
increment: function(){
var increment = this.count++
bus.$emit('inc', increment)
}
}
})

Vue.component('Display', {
template: "#display",
data: function(){
return({count: 0})
},
created: function(){
bus.$on('inc', function(num){
alert(num)
this.count = num;
});
}
})


vm = new Vue({
el: "#example",
})


I created my templates like so: http://codepen.io/p-adams/pen/PzpZBg

I'd like the
Increment
component to communicate the count to the
Display
component. I am not sure what I am doing wrong in
bus.$on()
.

Answer

The problem is that within your bus.$on function, this refers to the bus. You just need to bind the current Vue instance to that function using .bind():

bus.$on('inc', function(num){
 alert(num)
 this.count = num;
}.bind(this));

You should also check out https://github.com/vuejs/vuex if you want to manage global application states