One of the challenges with V8 compared to Rhino is that you can’t be sure of the order of global variable initialization. Personally this is not an issue for me, as I avoid any such use of global space, but it is an issue for some. A nice way of dealing with global space is to use namespaces and IEF as I described in Apps Script V8: Multiple script files, classes and namespaces but another, perhaps less obvious way, is put all the variables (and even functions) you need to access from multiple functions in a keystore. This comes with a few other goodies that I’ll go through in this article.

Redux, Vuex, Mobx etc

Managing user state in client side apps can be a mess, which is why many developers use some of these ‘state containers’ to hold what is essentially volatile global data. We don’t really need that in apps script, but a keystore can do a similar job in a basic way.

The KeyStore class

We’ll start with this very simple class, the code for it is at the end of this article

Any variables that you would consider putting in global (for example settings, user states) and so on are good candidates for a key store instead. But first, lets look at how it works

check for existence

add something

add an object

By reference

objects are by reference, so don’t need to be reset if modified

Default value

You can set a default value to use if the item is not already in the store

Default function

It’s better to use a function for this, so it only gets executed the first time you reference the key

Key passed to default function

Sometimes its handy to have the key in the default value constructor

The global space problem

Here’s how to apply it to solving the global space problem.

A wrapper

I generally create an IEF wrapper for each store I want to create – you may want more than one.

So far then, this would only put the variable ‘store’ in global space, but it would be defined before anything gets executed, so therefore would be visible in any function in any file.

Initialization

In your main script, say App.gs

Now you can share data between any functions in any files

and App.gs

Keystore class code

Summary

This approach lends itself very well to dealing with the global space problem, but it also abstracts away where the data comes from. One store could be using the KeyStore in memory class, but another could use say, the property store for more permanent storage, or cache or even a database, yet the mechanism for accessing it would remain exactly the same. You could even build a small rudimentary nosql database easily using this approach.  Key abstraction is something I’ll cover  in a later post.