Vue.js does not receive the MQTT response message

I am a beginner with Vue and I'm currently working on a project where I need to set a default value for Vue data return(). Right now, when the code runs, it logs

console.log('INSIDE CLIENT ON MESSAGE")
. However, the value defined as this.room1status = 1 doesn't seem to be passed or updated in data return room1status. Is there a way that I can assign the value of 1 to room1status in Vue when inside
client.on('message', function (topic, message) 
?

Script

  data(){
    return{
      room1status: ''
      }
   },

  mounted: function(){
    var mqtt = require('mqtt')
    var client  = mqtt.connect('ws://myUrl/')

    client.on('connect', function () {
      client.subscribe('route_status', function (err) {
        if (!err) {
          client.publish('presence', 'Hello mqtt')
        }
      })
    })

    client.on('message', function (topic, message) {

      var filterData = message;
      var x = JSON.parse(filterData);
      console.log('INSIDE CLIENT ON MESSAGE"); /** prints this out succesfully **/
      this.room1status = 1; /** but this does not get passed or updated to data return room1status **/
    }
 }

Answer №1

this in the callback of the on function does not refer to the component instance, so it is recommended to assign this to a variable like vm before calling that callback and then use vm inside it:

  var vm = this;
  client.on('message', function (topic, message) {

      var filterData = message;
      var x = JSON.parse(filterData);
      console.log('INSIDE CLIENT ON MESSAGE"); 
      vm.room1status = 1; 
    }

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

Prevent users from navigating back after logging in on a Reactjs application

Is there a way to prevent users from using the browser's back button after redirecting them to another application in ReactJS? In my scenario, I have two applications running simultaneously. Upon successful login, I check the user type. If the conditi ...

Is it possible to execute the .push() method on an array a specific number of times without using a for loop?

Currently, I am tackling the "Move Zeroes" Leetcode challenge. The task requires moving all zeroes to the end of the array without altering the sequence of non-zero elements. My strategy involves iterating through the array, splicing out each zero encounte ...

One class seems to be causing issues with hover functionality while the other works perfectly fine

HTML: <div class="channellist"></div> Through the use of Ajax, I am able to dynamically retrieve channels when the page loads and then append them within the channellist container. Once appended, my HTML structure appears as follows: <div ...

Exploring the Fundamentals of Skinning Animation in WebGL using Three.js

I've been exploring various demos on skinning in Three.js, but I'm struggling to understand if the imported model itself needs to be animated or if it's already animating from the modeling software and we just manipulate it? For example, ta ...

Removing Embedded Json Element from a Collection in AngularJS HTML

In my JSON Collection, I want to display the Email ID that is marked as IsPreffered = TRUE using AngularJS HTML without using JavaScript. This is my JSON Collection: { "user" : [ { "Name" : "B. Balamanigandan", "Email": [ ...

Teaching jQuery selectors to detect recently-added HTML elements

Unable to find a solution in the jQuery documentation, I am seeking help here for my specific issue. Embracing the DRY principle, I aim to utilize JavaScript to include a character countdown helper to any textarea element with maxlength and aria-described ...

Ways to verify if element has been loaded through AJAX request

I am trying to determine if an element has already been loaded. HTML <button>load</button> JS $(document).on('click','button',function () { $.ajax({ url: 'additional.html', context: document ...

How can you annotate and inherit a class method that returns an array of itself?

In the following example, I present a simplistic representation of code that may not align with standard HTML or front-end conventions. Please excuse any confusion this may cause. TL, DR I am facing challenges in specifying a return type for a method tha ...

Node.js scheduler library for triggering events based on time in a cron-like fashion

Currently, I am utilizing Node.js to develop a web application. My aim is to trigger events at specific times. While I am aware of using setTimeout and computing the time difference from the present moment, this method does not account for various timezone ...

Use the accelerometer in JavaScript and Cordova to control the movement of an object, such as a ball

Having trouble figuring out how to move a ball using the accelerometer. Any tips on combining the accelerometer values with the ball movement? Waiting for accelerometer... <div id="heading">Waiting for heading...</div> <div id="ball" ...

Secure a RESTful API with a Keycloak access token in a Node.js environment

I have implemented a REST API in Node.js and integrated the keycloak-connect npm package for security. I have configured the Node.js middleware to work with the keycloak middleware. var express = require('express'); var router = express.Router(); ...

The inconsistency of Selenium's StaleElementReferenceException error and the variability of pageload completion codes is causing issues with clicking on elements

Big shoutout to the amazing stackoverflow community for always providing assistance. Lately, I've been grappling with the frustrating "StaleElementReferenceException" issue and haven't found a universal solution yet. Some helpful members have rec ...

What is the best method for transferring properties to the parent component using Vue router?

I have a multi-step form that each step has a different header structure. The only variation in the header among the steps is the wording, which changes as you progress through the steps. I am looking for a way to achieve this using Vue Router: pa ...

Updating class with jQuery based on dynamically changing content

I am using countdown.js to create a custom countdown timer. My goal is to replicate the countdown timer seen on the homepage, but with the ability to change the target date (which I have already accomplished). Here is an example of what I currently have f ...

Tips for transferring client-side data to the server-side in Angular, Node.js, and Express

Seeking a straightforward solution to a seemingly basic question. I am utilizing Angular's $http method with a GET request for a promise from a specific URL (URL_OF_INTEREST). My server runs an express script server.js capable of handling GET reques ...

The type 'Event' argument cannot be assigned to the 'InfiniteScrollCustomEvent' parameter

I'm facing an issue with Ionic Angular. Here is my movies.page.html: <ion-header> <ion-toolbar color="primary"> <ion-title>Trending Movies</ion-title> </ion-toolbar> </ion-header> <ion-content ...

Javascript detecting key press event only firing once when a key is continuously held down

I have implemented the code below to redirect to a specific page when the w, s, a, d keys are pressed. <script> document.addEventListener('keydown', function(e){ e = e || window.event; key = e.keyCode || e.charCode; var keys = { 87: &ap ...

Is it sufficient to only capture 4xx errors?

Is it necessary to catch both 4xx and 5xx errors, or is catching just 4xx errors sufficient? In regular testing of my code, when would a 5xx error even occur? ...

Personalized configurations from the environment in the config.json file

I need to dynamically populate a setting object in my config.json file based on environment variables. The settings should vary depending on the environment. "somesetting": { "setting1": "%S1%", "setting2": "%S2%" } I am currently working on Wind ...