Global variables are useful because they are accessible on all pages. Their data is stored in the browser's LocalStorage, allowing them to be used for exchanging information both between all pages and within a single page.
For example, let's create 3 widgets: 2 buttons and 1 text (to see what's inside the global object).
When the "Submit" button is clicked, we will create an object. We can add any type and amount of data to it. For this example, I will use the boolean (true/false) type.
Let's create a global variable by calling the function storeValue('name', {key: value})
. The first parameter is a string that will serve as the name of the global variable, which we will use to refer to it. The second parameter is the value we want to store.
In the button
widget, on the onClick
event, we select JavaScript and write the code to store a variable named example
with a value of true
.
{{storeValue('example', true)}}
When the button is clicked, a global variable will be created. To verify that it has been created successfully, we will display its value in the text widget. All global variables are stored in the store
object, which is located within the main variable.
To achieve this, we will write the following code in the text widget:
{{main.store.example}}
To overwrite the data of the global variable, we call storeValue
with the name of the variable we want to overwrite. We will write this code in the second button. Let's replace the value true
with false
and press the button to overwrite it.
{{storeValue('example', false)}}
Everything stored in storeValue
is added to the Local Storage. If you open the DevTools in your browser and select Local Storage (usually found in the Application section), you will see the data that has been added.
If you want to prevent Local Storage from persisting data when redirecting to other pages, you can pass false
as the third parameter in storeValue
:
storeValue('name', value, false);
This will ensure that the data is not stored in Local Storage when redirecting to other pages.
storeValue("name", {key: value}, false)
It's worth noting that when the third parameter is set, it should be used for subsequent operations such as updating the value or deleting it. Otherwise, the variable will become inaccessible.
To delete a variable from the object, you can assign it the value of "undefined":
storeValue('name', undefined, false);
This will effectively remove the variable from the object.
Top comments (0)