UBOS Community

AC
AC

Posted on • Updated on

Global Variables (storeValue)

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).

Image description

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.

Image description

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)}}  
Enter fullscreen mode Exit fullscreen mode

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.
Image description

To achieve this, we will write the following code in the text widget:

{{main.store.example}}
Enter fullscreen mode Exit fullscreen mode

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)}}
Enter fullscreen mode Exit fullscreen mode

Image description

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);
Enter fullscreen mode Exit fullscreen mode

This will ensure that the data is not stored in Local Storage when redirecting to other pages.

storeValue("name", {key: value}, false)
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

This will effectively remove the variable from the object.

Top comments (0)