Exploring ways to retrieve object properties transmitted through the Vue event global bus

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>

Answer №1

It appears that your socket has not been connected yet and lacks an identifier.

Be sure to wait for the connect event on the socket before triggering the EventBus event.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain element by selecting a specific class using Javascript

<select class="tmcp-field tillagg-width tm-epo-field tmcp-select" name="tmcp_select_30" data-price="" data-rules="" data-original-rules="" id="tmcp_select_ ...

Managing multiple arrays in asynchronous functions in node.js

I am facing an issue with a large array (10K) that I need to split. I tried following this method: and it worked perfectly. However, I now need to pass the separated arrays to a request function and await the response before passing it to savetodb. Could ...

In the event that you encounter various version formats during your work

Suppose I have a number in the format Example "1.0.0.0". If I want to increase it to the next version, it would be "1.0.0.1" By using the following regex code snippet, we can achieve this perfect result of incrementing the version to "1.0.0.1": let ver ...

Having trouble with JQuery blur and enter key functionality not working properly

I'm currently utilizing the code below for inline editing. I am looking to trigger ajax when either the enter key is pressed or the user clicks away (blur). While everything works fine when the enter key is pressed, the AJAX call does not fire on bl ...

Limit express to only allow AJAX requests

Currently working on an Express app where I aim to restrict access to the routes exclusively through AJAX requests. Aware that this involves using the X-Requested-With header, but uncertain of how to globally block other request types. Any suggestions or ...

Tailwind Component Grid in Action

I'm trying to arrange a list of JavaScript components in a grid with one row and twelve columns. I want to use only six columns for the actual elements, while having three columns of padding on each side of the grid. My goal is to place three elements ...

Arranging HTML elements using JavaScript or jQuery

Something seems off. The sorting doesn't work as expected. Check out the JavaScript code below: function sortDescending(a, b) { var date1 = $(a).data('date'); var date2 = $(b).data('date'); return date1 > date2; } ...

Retrieve the id for the chosen user name within a function that contains an array of objects

const userList = [ {name:"jonh" ,id:EAD1234}, {name:"peter" ,id:EAD1235}, {name:"matt" ,id:EAD1236}, {name:"henry" ,id:EAD1237}, ] In the array above, there are various users with their respective IDs. The goal is t ...

How can I create spacing between squares in an HTML div element?

Currently, I am working on my project using Laravel 5. I retrieve some integer values from a database and use them to create square divs in HTML. Below is the current output of my work. https://i.stack.imgur.com/sy2ru.png You may notice that there is spa ...

Is it possible to extract the value displayed on a Typography component in Material UI and store it in a state variable?

I'm currently facing an issue with mapping a data array onto material-ui Typography elements. Here's the code snippet: { array.map((item, id)=> <Typography key={id} value={item.name} />) } While this code successfully displays the val ...

Changing p tags to br tags on tinyMCE

I need assistance with using tinyMCE as an inline editor. I want it so that when a user is in edit mode and presses enter, <br /> is inserted instead of <p>. I have gone through the manual and FAQ but have not been able to achieve this successf ...

Iterating through a jQuery function to increment value

I have encountered an issue while trying to calculate the total value from an array of form fields. The problem lies in how the final value is being calculated on Keyup; it seems that only the last inputted value is being added instead of considering all t ...

Does Vue.js have its own version of Angular's named templates feature?

Check out this snippet of Angular code: <ng-container *ngIf="someCondition; else spinner"> Show Data </ng-container> <ng-template #spinner> Show Spinner </ng-template> Do you know if there is a similar vue.js equ ...

Having trouble getting getStaticProps to display JSX in Next.JS

I'm currently facing an issue with rendering basic data from a locally hosted Strapi API in my Next.js project. Although the data is successfully logged in the console, I am unable to map it into JSX. Below is the API get function: export async func ...

Delete items from several arrays on a click event in React

I'm working with an array of objects that contain multiple arrays. My goal is to remove the item when a button is clicked, but I keep getting undefined as a result. JSON Data [ { "services": [ { "id": "1b9 ...

Display or conceal component based on specific URL in React.js navigation bar

Hey there, I'm facing an issue with hiding certain links in the navbar when users visit specific pages. For instance, on the Landing page, I want to hide the Orders and Basket links and only show the Login link. I'm having trouble figuring out ho ...

Accessing props in setup function in Vue 3

I am encountering issues when trying to access the props value (an array) in my composition API setup. The component I have is called DropDown, and I am passing it an array of objects. Here's what I need to achieve: export default { emits: ['up ...

JavaScript functioning exclusively for specific list items within an unordered list

After implementing JavaScript on my website, I noticed that it only works when clicking on certain list items (li's) and not on others. Specifically, the functionalities for Specialties, Contact Us, and Referral Schemes are not working correctly. ...

Is there a way to retrieve the chosen selection from a select dropdown element using JavaScript?

As someone who is still learning JavaScript, I've come across a particular issue. Within a webpage, there is a select dropdown as shown below: <select id="selTipoRap" class="form-control" th:field="*{tipoRappresentante}&qu ...

When an express pre-remove signal initiates another pre-remove action during the removal process

Imagine having 4 different models structured like this: ┌────────────┐ ┌────────────┐ │ User │ │ Goal │ ├────────────┤ 1 ├───── ...