guggio
guggio

Reputation: 211

How to access object properties passed by vue event global bus

I have an event bus that will pass the socket.io object back from main instance to the component where I need some information like the socket id. After the related event I've created is emitted, on the component, when the reply is recived, I get the socket object, but I don't know why, I'm not able to use it's properties inside the component. Is there any fix to this?

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'

// Before you create app
//Vue.config.devtools = true;

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) => {
    //this will log the socket object passed from the main vue instance 
      console.log(socket)
      this.socket = socket;
      this.isConnected = true;
    //this will not log anything and result in an undefined message in 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>

Upvotes: 0

Views: 180

Answers (1)

Radu Diță
Radu Diță

Reputation: 14171

Your socket is not yet connected, and doesn't have an id yet.

You should wait for the connect event on the socket and then trigger the EventBus event.

mounted() {
 console.log('mounted');
 EventBus.$on('open-connection', (data) => {
   console.log('connected');
   socket.on('connect', () => {
      EventBus.$emit('connected', socket)
   });
   socket.open()
  })
}

Upvotes: 1

Related Questions