EN VI

Holding a large variable in JavaScript?

2024-03-13 07:00:06
How to Holding a large variable in JavaScript

I have some JavaScript that finds all the checked items and arranges the data in memory.

I need to display a modal popup. And, when that popup is closed, I will again need the data I created above.

I'm trying to determine the best way to store that data so I won't need to recreate it. I used to think I could store it in an element using a data-xxx attribute. But I've found you cannot read and write these like a variable.

I supposed another approach is to create a variable at a page-level scope. But JavaScript isn't my main language and I'm not sure where a variable will live through different events.

What is a super reliable way to store data so that it will be available later?

Solution:

You can create a global variable let app = {...} and store all program data in there (this is how I usually organize programs). Then, store the state of your items under app.data.checkboxState or somewhere like that.

Below is an example program showing how to apply that:

const app = { // variable to hold info about program
  data : {
    checkboxState : {} // store checkbox state here
  }
}

app.getState = function() { // method to get state and save it in memory

  // get all elements with the class 'checkbox'
  // you can use any class you like instead, just
  // make sure all your checkbox elements have that class
  let checkboxes = document.getElementsByClassName("checkbox");
  
  for (let i=0; i<checkboxes.length; i++) { // loop through them
    let checkbox = checkboxes[i];
    app.data.checkboxState[checkbox.id] = checkbox.checked; // save this checkboxs' state
  }
}

// helper function to get state of a
// certain element by its id
app.getElementState = function(elementId) {
  return app.data.checkboxState[elementId]
}

// method to show user the state of memory.
// you can replace it with whatever you want,
// just remeber to use app.getElementState(idOfElementYouWantToCheckStateOf)
// to get the state of an element
app.showState = function() {

  // generate message with data
  let msg = JSON.stringify(app.data.checkboxState);
  
  // you dont have to understand this, it's just
  // formatting to make the message easier to read
  let formattedMsg = msg.replaceAll('{', '')
                        .replaceAll('}','')
                        .replaceAll('true', ' checked ')
                        .replaceAll('false', ' unchecked ')
                        .replaceAll(':', ' : ')
                        .replaceAll('"', '')
                        .replaceAll(',', '\n   ');
  
  // open window with message
  alert("App state is: \n   " + formattedMsg);
}

app.run = function() { // method to execute program (save & show message)
  app.getState(); // save state
  app.showState(); // show message
}
html, body {
  font-family:arial;
}
h2 {
  color:turquoise;
}
button {
  color:black;
  background:turquoise;
  border:none;
  padding:5px 10px;
  border-radius:2px;
  width:100px;
  cursor:pointer;
  margin:5px 0px;
}
button:hover {
  box-shadow: 1px 1px 4px 0px black;
}
<!DOCTYPE html>
<html>
<head>

</head>
<body>
  <h2> Check options below: </h2>
  
  <p>
  <input class="checkbox" id="op1" type="checkbox"></input><span>Option 1</span><br>
  <input class="checkbox" id="op2" type="checkbox"></input><span>Option 2</span><br>
  <input class="checkbox" id="op3" type="checkbox"></input><span>Option 3</span><br>
  <input class="checkbox" id="op4" type="checkbox"></input><span>Option 4</span><br>
  <input class="checkbox" id="op5" type="checkbox"></input><span>Option 5</span><br>
  </p>
  
  <button onclick="app.run()">OK</button><br>
  <button onclick="app.getState()">Save state</button><br>
  <button onclick="app.showState()">Show state</button><br>
</body>
</html>

Click "Run code snippet" (above) to run the code. If you click "OK", the state will be saved and a message will be shown showing the saved data. Click "Save state" to save without showing a message, and "Show state" to show the message without saving. Notice how when you click "Show state" without clicking "Save state" first, the message is not updated (even if you check or uncheck a box)

Just a reminder-- for such a small program, it is probably not necessary to do this and might just make it more complicated, but when you create larger programs, organizing your code like this really makes it easier to maintain :).

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login