Using Vue.js and JavaScript to access a single variable across multiple class methods

I am working on organizing my custom channel logic into its own class. During the created lifecycle method, I am executing each method in the class I created. However, I am facing a challenge in retaining the instance of the socket that was created in the init() method for use in other methods.

Main.vue

import CustomClass from './CustomClass';

created() {

    const customClass = new CustomClass();
    customClass.init();
    customClass.subscribe();
}

CustomClass.js

import Socket from 'Socket';

class CustomClass {

    init() {
        const socket = new Socket(key: XXXXX);
    }
    subscribe() {
       // How can I access `socket` here after it was created in init?
        socket.subscribe(channel: 'xxxx');
    }

}

Answer №1

In order to properly integrate the socket functionality into your CustomClass, you must first define it as a property of the class and access it using the keyword this

import Socket from 'Socket';

class CustomClass {
  
  initialize() {
      // Declare the socket as a property of the CustomClass instance
      // Consider moving this to a constructor for better organization

      this.socket = new Socket(key: XXXXX);
  }
  subscribeToChannel() {
     // Utilize the `this` keyword to access the socket
      this.socket.subscribe(channel: 'xxxx');
  }

}

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

Strategies for Resolving Table Alignment Problems using HTML and JavaScript

I am struggling to figure out how this dashboard will function as it is not a live website, but rather a tool that pulls data from a chemical analysis program and displays it in a browser view. My main issue is aligning two tables at the top of the page ...

Transferring an object from one inventory to another

I'm in the process of developing a task manager that enables users to add and remove tasks. I am also working on enabling the ability for users to transfer tasks from one list to another. The current code I have written doesn't seem to be functio ...

Submit simple text via XMLHttpRequest to an Express server

I am currently facing an issue with making a post XMLHttpRequest to my Express server. Despite attempting to send a string, it seems that I am missing something crucial in my implementation. Client: const sendMessage = () => { const message = "This ...

Instructions for automatically sending SMS when there is a change in MySQL database data using PHP

Is it possible to trigger an SMS using Twillo as the gateway when there is a change in data in a MySQL database with PHP? ...

Is there a way to modify the Javascript for this Contact Form to trigger a different action if a specific key is pressed instead?

I have been working on a Contact Form that integrates Google Scripts. Everything seems to be functioning well as it successfully sends emails and formats them properly in my inbox. However, there are two issues that I am encountering: -I want to exclude t ...

Issues with Select2 Ajax functionality not functioning as intended

I am currently using the select2 library to create a dropdown menu with ajax functionality, but I am encountering some issues. Below is my code: $("#guests").select2({ multiple: true, minimumInputLength: 1, formatInputTooShort: fun ...

What is causing the error when using Interfaces and Observable together?

I created a ToDoApp and integrated Firebase into my project, but I am encountering an error. ERROR in src/app/todo-component/todo-component.component.ts(25,7): error TS2740: Type 'DocumentChangeAction<{}>[]' is missing the following proper ...

What is the best way to invoke a Rest API within a Vue component?

As a newcomer to VueJS, my goal is to create a basic page featuring a pie chart displaying some data. Currently, I have successfully displayed the chart using example data. However, I now wish to populate the chart with data fetched from an API call on my ...

How do I use Vue.js to capture keypress events and update the input value in real-time?

Here is the scenario I am facing: https://codepen.io/anon/pen/WYJopq I have implemented a functionality to track key presses and duplicate the input into another field with the following code snippet: [![methods: { clone: function() { this.m ...

Using Paper Checkbox to Toggle the Visibility of a Div in Polymer

Having experience with Meteor, I typically used JQuery to toggle the display of a div along with paper-checkbox: HTML: <paper-checkbox name="remoteLocation" id="remote-chk" checked>Remote Location</paper-checkbox> <div id="autoUpdate" clas ...

Unable to find component: "wrestler-choice-box". If this is a built-in custom element, please ensure it is not included in component resolution

In my attempt to achieve a specific goal, I have an array of data that I want to incorporate into my HTML document along with a Vue component containing a template. My intention is to utilize list rendering so that the names and images from this array bind ...

Display a dropdown menu when hovering over with a delay

I recently created a basic navigation menu with dropdown functionality using CSS3 initially, but I decided to enhance it by incorporating jQuery to display the dropdown after a set timeframe. However, I am facing an issue where all dropdowns appear when ho ...

Dynamic styling based on conditions in Next.js

After a lengthy hiatus, I'm diving back in and feeling somewhat disconnected. In short, I have encountered a minor challenge. I successfully created a navigation menu pop-out that toggles classname based on the isActive condition in React. However, I& ...

finding the initial element within an object using lodash in javascript

Recently, I came across some data in the form of an array of objects. For instance, let me share a sample dataset with you: "data": [ { "name": "name", "mockupImages": "http://test.com/image1.png,http://test.com/image2.png" }] ========================== ...

iPhone 6 (iOS) users may face compatibility issues with iframe and fancy box features

I am currently learning how to use jQuery and the fancybox library. In my Angular 1 and Ionic project, I have successfully implemented fancybox with an iframe. Everything works perfectly on browsers and Android devices, but on iOS, a loader icon appears an ...

Why is the autocomplete minlength and maxheight not functioning properly in MVC?

After entering a value in the text field, data from the database appears but adjusting the height and width of the list box seems to be a challenge. I have set the parameters like minLength: 0, maxItem: 5, but it doesn't seem to make a difference. ...

"Utilizing Vue.js to make an AJAX request and trigger another method within a

How can I include another method within a jQuery ajax call? methods : { calert(type,msg="",error=""){ console.log("call me"); }, getData(){ $.ajax({ type: "GET", success: function(data){ / ...

Adding a type declaration to the severity property in React Alert - A guide to Typescript

I've developed a type declaration object for the incoming data, but no matter what I try to define as the type for the property "severity", it's not happy. The options it wants (as displayed below) don't seem feasible. I'm curious if th ...

Stop the default drag behavior on an input range element in VueJS

Is there a way to disable the default drag functionality of an input range element without affecting the click feature? Users should be able to change values by clicking instead of dragging. <input type="range" min="0" max=& ...

Error encountered: A syntax error occurred due to an unexpected token ":" found in the file path D:practise odejs odejs-demoviewsindex.html

Attempting to switch the engine view from .ejs to .html resulted in an error. After searching online, I was unable to find a solution for the following problems: Express 500 SyntaxError: Unexpected token : in D:\practise\nodejs\nodejs-demo& ...