Can a JavaScript class have a property that returns an array?

To those more experienced in node red development, this may be obvious, but I'll ask anyway.

Within my node red flow, I have a function node containing a javascript class that only exposes static members. Here's an example:

class MeasurementsList {
    static INTERNAL_LIST_CONTEXT_NAME = "INTERNAL_LIST_CONTEXT_NAME";

    static get availableMeasurements() { //this is an array
        const tempMeasurementsInternalList = context.get(INTERNAL_LIST_CONTEXT_NAME);
        const measurementsInternalList = tempMeasurementsInternalList?.length ? tempMeasurementsInternalList : new Array();
        return measurementsInternalList;
    }
    ...
}

In short, I want to be able to manipulate the array like so:

MeasurementsList.availableMeasurements.push(newMeasurementObject);
. However, I'm struggling to make the availableMeasurements array persistent across different msg.payloads.

This is what I intend to achieve:

MeasurementsList.availableMeasurements.push(msg.payload1.newMeasurementObject);
...
MeasurementsList.availableMeasurements.push(msg.payload999.newMeasurementObject);
MeasurementsList.availableMeasurements.push(msg.payload1000.newMeasurementObject);
...

Is it possible to accomplish this in node-red with javascript? How should I handle the context variable?


Edit 1: I've refactored my former static member class to an instantiable one, located on the [On Start] tab: https://i.sstatic.net/S90Ti.png

// Code added here will be run once
// whenever the node is started.
class Measurement {
    constructor(time, device, temperatureC, maxAgeMs) {
        this.time = time;
        this.device = device;
        this.temperatureC = temperatureC;
        this.maxAgeMs = maxAgeMs;
    }
}

class MeasurementsList {

    constructor() {
        this.#measurementsList = new Array();
    }

    /**
    * @param {Measurement} measurement
    */
    refreshAndAdd(measurement) {
        this.#removeOutdatedValuesAndSortByTemperaturesAscending();
        this.#measurementsList.push(measurement);

        return {
            "maxMeasurement": this.#maxMeasurement(),
            "meanTemperatureC": this.#meanTemperatureC(),
            "minMeasurement": this.#minMeasurement()
        };
    }

    get length() {
        return this.#measurementsList.length;
    }

    #maxMeasurement() {
        const maxIndex = this.#measurementsList.length - 1;

        return this.#measurementsList[maxIndex];
    }

    #meanTemperatureC() {
        let sum = 0;

        this.#measurementsList
            .forEach((m) => {
                sum += m.temperatureC;
            });

        const mean = sum / this.#measurementsList.length;

        return mean;
    }

    #minMeasurement() {
        const minIndex = 0;

        return this.#measurementsList[minIndex];
    }

    #removeOutdatedValuesAndSortByTemperaturesAscending() {
        const currentTime = Date.now();
        this.#measurementsList = this.#measurementsList
            .filter((m) => {
                return (currentTime - m.time) < m.maxAgeMs;
            })
            .sort((m1, m2) => {
                return m1.temperatureC - m2.temperatureC
            });
    }
}

let measurementsList = new MeasurementsList();

However, there are certain aspects of scope that confuse me. I declared and instantiated my MeasurementsList class on the [On Start] tab as measurementsList. But I can't access measurementsList on the [On Message] tab, nor can I access the Message class. Did I misunderstand your answer, Mr. @hardillb? https://i.sstatic.net/2EdOn.png Question: What steps should I take to access my measurementsList on the [On Message] tab?

Answer №1

To ensure the longevity of objects (or classes), it is recommended to define them in the "Start Up" tab within the function node.

The reason for this is that the context of the "On Message" tab is cleared with each message received and does not retain any state.

Objects initialized in the "Start Up" tab will be preserved and passed into the context of the "On Message" tab.

Edit:

After initialization, any variables you plan to use in the "On Message" tab should be added to the context.

For example:

...

let measurementsList = new MeasurementsList();

context.set('ml', measurementsList)

Then, at the beginning of the "On Message" section:

const ml = context.get('ml')

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

Discovering a way to monitor keyup and keydown occurrences in JavaScript on an iPhone

Looking to track keyup/keydown events in JavaScript on iPhone browsers. My goal is to automatically move the focus to the next form element after the user has inputted the maximum number of characters in a text box. ...

Have you ever wondered why the expression `Number(new Boolean(false))` always returns `0

In the case of Boolean(new Boolean(...)) === true, it is because new Boolean(...) is treated as an object. However, why does Number(new Boolean(false)) === 0 (+new Boolean(false) === 0) and Number(new Boolean(true)) === 1? Instead of resulting in NaN. Wh ...

Show a Toast in React without relying on useEffect to manage the state

I have successfully implemented the Toast functionality from react-bootstrap into my application using the provided code. However, I am unsure if it is necessary to utilize useEffect to set show with setShow(items.length > 0);. Would it be simpler to ...

submit the JSON formatted data to the server

I am attempting to extract data from a form and transmit it to a remote server: Below is the code snippet: <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> </head> ...

Angular 6 component experiencing issues with animation functionality

I've implemented a Notification feature using a Notification component that displays notifications at the top of the screen. The goal is to make these notifications fade in and out smoothly. In my NotificationService, there's an array that holds ...

Having trouble with the line graph in Flot when a threshold is applied?

I'm currently working on a website where I am incorporating flot for data visualization. However, I'm facing an issue with setting a threshold on my line graph. Instead of coloring the data differently, it seems to be separating it at the thresho ...

JavaScript - A simple way to retrieve the dimensions of an image consistently

I'm currently working on a piece of Jquery code that is designed to display an image fitting within the screen's dimensions. These images are generated dynamically as needed. However, I am facing an issue where the height and width of the image a ...

I encountered an issue with route handlers in Next.js version 13.2. Sadly, they are not

I am trying to implement an API on my website with the endpoint /api/popular-movie. Here is an overview of my file structure: https://i.stack.imgur.com/e8Pf8.png Additionally, this is my route.ts code: import { NextResponse } from "next/server"; ...

Iterate through a loop to remove DOM elements

I'm working on creating a loop that will be responsible for deleting DOM elements (one or more lines within an HTML table): <tr class="entireLine><input type="checkbox"></tr> <tr class="entireLine><input type="checkbox" che ...

Whenever the page is refreshed, the vertical menu bar with an accordion feature hides the sub

I have designed a vertical accordion menu bar following the example at http://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_accordion_symbol However, I am encountering an issue where clicking on a button to display a submenu causes the page to refr ...

What are the steps to take in order to successfully deploy an Express server on GitHub Pages?

I heard that it's possible to host an Express server on GitHub Pages, but I'm not sure how to do it. Is the process similar to deploying a regular repository on GitHub Pages? ...

What impact does setting a variable equal to itself within a Dom Object have?

Within my code example, I encountered an issue with image sources and hrefs in a HTML String named tinymceToHTML. When downloading this html String, the paths were set incorrectly. The original image sources appeared as "/file/:id" in the String. However, ...

Trouble with Next.js App Router OG Image not appearing after deployment

I am facing an issue with my Nextjs project that uses the app router. Inside the app directory, there is a file named opengraph-image.png. I have set this file to be the OG Image for the landing page, but after deploying and checking, the OG image does not ...

Experiencing difficulties with node and asynchronous programming

I'm attempting to use async-waterfall in order to fetch data from an API, save it as JSON, and then store it in a database. Here is a snippet of the code I have so far. Can someone assist me with this process? async.waterfall([ function getBo ...

Adding a class to a Vue component using the $refs property

I am facing an issue where I need to add dynamic class names to various Vue components based on their reference names listed in a configuration file. Manually adding classes to each component is not feasible due to the large number of components. To addre ...

AngularJS $http get isn't functioning properly, but surprisingly $.ajax works perfectly

Recently delving into the world of AngularJS, I am facing a hurdle with $http functionality. In my factory setup below: app.factory('employeeFactory', function ($http) { var factory = {}; // Retrieving data from controller var emplo ...

Online Adventure - Saving Conversations

I am interested in developing an RPG using JavaScript. The game will involve a significant amount of dialog. While I have knowledge of PHP and MySQL, I am new to XML. My queries are: Would it be more efficient to store the dialog in a MySQL database and ...

Examining the appearance of react-hot-toast using jest testing

As I work on my application, I am facing a challenge in writing a test for the appearance of a react-hot-toast. Whenever a specific button is clicked, this toast pops up on the screen and disappears after a brief moment. Despite being visible both on the s ...

Display table rows that are hidden in an HTML/Angular toggle function

I am relatively new to Angular and I have a task of setting up a table. The dataset that I have is as follows:- data = [{rollno: 1,name: 'abc',subject: 'maths'}, {rollno: 4,name: 'xyz',subject: 'history'}, ...