My event bus is responsible for passing the socket.io object back from the main instance to the component where I need specific information, such as the socket id. However, after emitting the related event and receiving the reply in the component, I am unable to access the socket object's properties. Is there a solution to this issue?
Main Vue Instance
import Vue from 'vue'
import { EventBus } from './event-bus'
import App from './App'
import router from './router'
import SocketIO from 'socket.io-client'
// Initialization of Socket.io
const socket = SocketIO('https://host-notification.herokuapp.com/', {
autoConnect: false
});
/* eslint-disable no-new */
new Vue({
el: '#inbox',
data: {},
router,
render: h => h(App),
watch: {
$route(to, from ){
console.log(to, from);
}
},
created() {
this.$router.push({ path: 'inbox' });
},
mounted() {
console.log('mounted');
EventBus.$on('open-connection', (data) => {
console.log('connected');
socket.open()
EventBus.$emit('connected', socket)
})
}
})
Component File
<script>
import { EventBus } from '../../event-bus';
export default {
data () {
return {
socket: null,
isRegistered: false,
isConnected: false,
username: null,
message: '',
}
},
created() {
},
mounted() {
EventBus.$on('connected', (socket) => {
// Log the socket object passed from the main Vue instance
console.log(socket)
this.socket = socket;
this.isConnected = true;
// This will result in an undefined message in the console
console.log(this.socket.id)
})
},
methods: {
connect(){
if( this.isRegistered === false){
this.username = this.username;
this.isRegistered = true;
EventBus.$emit('open-connection')
return this.username;
}
}
}
}
</script>