Move the values of the variables into a separate file

While working on coding the game blockly, I encountered a variable named lineCount within the lib-dialog.js file. This variable keeps track of the number of line breaks in the code. By inserting this variable's value using innerHTML, I was able to display the number of lines by creating a div element in the soy.js file (which is where I need to handle the output). However, I require this value in a variable so that I can use it in an if statement like if(lines == 6) { }

// Implementation of user's code.
if (BlocklyGames.workspace) {
    var linesText = document.getElementById('dialogLinesText');
    linesText.textContent = '';
    // The following line causes warnings during Puzzle compilation due to lack of JavaScript generator but is irrelevant for Puzzle.
    var code = Blockly.JavaScript.workspaceToCode(BlocklyGames.workspace);
    code = BlocklyInterface.stripCode(code);
    var noComments = code.replace(/\/\/[^\n]*/g, ''); // Removing inline comments.
    noComments = noComments.replace(/\/\*.*\*\//g, ''); /* Removing block comments. */
    noComments = noComments.replace(/[ \t]+\n/g, '\n'); // Trimming trailing spaces.
    noComments = noComments.replace(/\n+/g, '\n'); // Eliminating blank lines.
    noComments = noComments.trim();
    var lineCount = noComments.split('\n').length;
    var pre = document.getElementById('containerCode');
    pre.textContent = code;
    if (typeof prettyPrintOne == 'function') {
        code = pre.innerHTML;
        code = prettyPrintOne(code, 'js');
        pre.innerHTML = code;
    }
    if (lineCount == 1) {
        var text = BlocklyGames.getMsg('Games_linesOfCode1');
    } else {
        var text = BlocklyGames.getMsg('Games_linesOfCode2')
            .replace('%1', String(lineCount));
    }
    linesText.appendChild(document.createTextNode(text));

    document.getElementById("contarBloco").innerHTML = lineCount;
    var contandoBloco = lineCount;
}

I'm facing difficulties taking the lineCount variable and assigning its value to another js file. Currently, I am only able to insert it into a div using innerHTML.

Answer №1

If you want to store and retrieve data easily, consider using local storage. Set the value of 'localcount' in the local storage and access it whenever needed.

var lineCount = noComments.split('\n').length;

 localStorage.setItem("lineCount", lineCount); // save in first file

 var count = localStorage.getItem("lineCount")  // retrieve in second file

By following this method, you will receive the value as a string; if you need an integer, you can either directly use it as a string or convert it using the parseInt method.

parseInt(count);

This approach might be beneficial for your task. Thank you.

Answer №2

If you're uncertain about whether your Javascript files are modules, one way to handle this is by returning a function in your lib-dialog.js file.

Here's an example:

lib-dialog.js =

let Dialog = (function() {

   function SetLineCountVariable(LocalLineCount){
       LineCount = LocalLineCount;
   }

   return SetLineCountVariable

})();

In your soy.js file:

let Soy = (function() {

   Dialog.SetLineCountVariable(6);

})();

Don't forget to ensure that your JS files are called in the correct order in your HTML page.

Alternatively, if you only need the variable result in another JS file, display the result of LineCount in an HTML tag within your lib-dialog.js file and retrieve it in your other JS file using document.getElementById.

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

Is it acceptable for Single Page Web Apps to have multiple requests at startup?

I've been dedicated to developing a Single Page Web App (SPA) recently. The frontend is built with BackboneJS/Marionette, while the backend is powered by Java Spring :(. However, I've noticed that the application's start time could be sluggi ...

Converting human-readable dates into a Date object

How can I reliably convert human-entered dates into a Date() object for my project that utilizes a ML text extractor? Although seemingly straightforward, the issue lies in the wide variety of formats used by individuals when entering dates, ranging from " ...

selecting arrays within arrays according to their date values

With an array of 273 arrays, each containing data about a regular season NFL football game, I am looking to categorize the games by week. In total, there are 17 weeks in the NFL season that I want to represent using separate arrays. The format of my array ...

Display a fixed legend on Google Chart without showing percentage values

<script type="text/javascript"> // Loading the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Setting a callback to run when the Goo ...

Looking for a solution to the error message "React Native Splash Screen shows 'null is not an object

I have followed all the steps outlined in this guide: https://www.npmjs.com/package/react-native-splash-screen and also watched a YouTube tutorial covering the same process. Here is the code snippet that I have implemented: import * as React from 're ...

Connecting the value of one input to influence another input

There are two input boxes provided - one for current address and another for permanent address. When the checkbox is clicked, the value of the current address should be displayed in the permanent address box. However, I am facing an issue where when I unc ...

Updating parent array values within child components in React

Currently, I am working on a React application where I need to save the handlers for all windows opened from the app. Previously, before using React, I stored these windows in a global array attached to the parent window, although I understand that using J ...

JavaScript and PHP/HTML template engine technology

I've recently discovered the jQuery template engine and am intrigued by its potential. It seems to be very efficient for ajax calls, as the data exchange is minimized. However, when I initially load my application using only PHP and HTML to display ...

Angular $resource encounters a 400 Bad Request error when attempting a PUT request, triggering the $resolve and $promise

My service is structured as follows (with variables removed): angular .module('app') .factory('Employee', function($resource) { return $resource("https://api.mongolab.com/api/1/databases/:dbName/collections/:collectionN ...

Obtaining the clientID when the textbox name is stored in a string variable

I am struggling with the following code intended to check for a blank value in my textbox, but it is resulting in a compilation error. Can someone help me find a solution? Here is my code in JavaScript: function checkTextboxNotFilled(txtbox) { v ...

What led to the decision for the two distinct chart elements to merge into a single container?

In the process of creating a dashboard using React.js and d3.js, I encountered an interesting issue that perplexed me for quite some time. Below is the Scatterplot.js code written in d3.js: import React, { Component } from "react" import * as d3 from "d3 ...

Updating state: Removing a specific individual from an array of objects when a button is clicked

I am currently working on a code snippet where I aim to remove a specific person from an organizational chart once the delete button next to their name is clicked. However, I am encountering an issue where clicking any delete button results in all 5 people ...

How come the HTML page served by the express.js route isn't linked to a CSS stylesheet?

Recently, I've been working with a server.js file that imports a router const path = require("path"); const express = require("express"); const app = express(); const PORT = 8080; app.use(express.urlencoded({ extended: true })); app.use(express.jso ...

Tips for maintaining the original ng-click initialized value as the ng-init value after the page is refreshed

My ng-repeat feature includes buttons for liking and disliking images. The problem I'm facing is that each time the page refreshes, the count of likes and dislikes gets reset to the initial value set by ng-init. How can I maintain the incremented lik ...

html.hidden loses its value when the name attribute is modified

In my cshtml view, I have an @html.editorfor and an @html.hiddenfor element. When a button is clicked, I dynamically change the name attributes of both elements so that they can be posted in a separate list. The value of the editorfor element should be a ...

Enhancing Angular with Plotly: Implementing click events on bar chart legends

I'm currently working on implementing color pickers for my plotly-plot charts within an Angular template. I am looking to add a function that triggers when the chart legend is clicked. How can I achieve this and get a click event for the chart legends ...

Dynamic Checkbox Functionality in REACT

Motivation: My goal is to generate multiple rows with a variable number of checkboxes that will be managed by a useState hook. Challenge: The page freezes or displays constant loading, with no content visible. There are no console logs, and even the debug ...

Encountering an issue while trying to set up fs-ext with npm: error C3861: the 'fcntl' identifier cannot be

I encountered an error while trying to install fs-ext on my Windows 10 64-bit machine with Node.js v8.1.3 and npm v5.4.0. Any recommendations on how I can successfully complete the installation? PS C:\users\desktop\auth> npm install fs-e ...

When do Angular.js memory leaks become a cause for concern?

My application is quite large, built on angular with nested states, directives, and data tables. We recently decided to switch to a full single-page setup, which raised some performance concerns. While Chrome seems unaffected visually, Firefox appears to s ...

How do Polymer elements and AngularJS directives differ from each other?

Exploring the Polymer Getting Started guide reveals a practical example showcasing Polymer's capabilities: <html> <head> <!-- 1. Shim missing platform features --> <script src="polymer-all/platform/platform.js"></ ...