samedi 10 avril 2021

How to have a set of elements easily accessible by different functions without having to declare them in each scope and without using globals?

I have a form containing about 20 inputs, which I use to store values which are later to be manipulated by some Javascript functions:

<input id="input_1" value="x" type="hidden"/>
<input id="input_2" value="y" type="hidden"/>
<input id="input_3" value="z" type="hidden"/>
<!--- ... --->

I also have a number of Javascript functions, all of which make use of such values (some may use just a few, but most functions will use all of them), manipulating the values themselves and doing other stuff as well, for example changing some properties of the elements containing them:

function foo() {
    var input_input_1 = document.getElementById('input_1')
    var input_input_2 = document.getElementById('input_2')
    var input_input_3 = document.getElementById('input_3')

    input_input_3.value = input_input_1.value + input_input_2.value

    input_input_3.style.visibility = 'visible'

    // ...
}

Now the end result is that I ended up with a lot of functions redeclaring the very same elements at the top. Although this might be ok on a technical level, I'm concerned about how unmantainable this has become. The actual code is of course more complex, and I often have to introduce new elements to be handled within the functions, which in turn forces me to change a lot of functions and make them "fetch" the new elements at the start.

So I'd rather have a single snippet of code "preloading" all of the element within the scope of the functions needing them at once (somehow, somewhere), to keep things tidy and to make it easy to add new elements for the functions to use by allowing me to change a single snippet of code.

What I've tried:

  • Creating a function preload_elements(), "fetching" all of the elements I need to handle within the functions and declaring them as globals, calling the function itself using <body>'s onLoad() event. This puts all of the elements within the scope of each function of course, however research has told me that globals, much as in other languages, are discouraged in Javascript too.
  • I thought of having a function fetch_elements() returning an array containing all the elements I need to handle within the functions, and having each function retrieve the elements by calling fetch_elements() at the start of the function itself, however since there's no such thing as associative arrays in Javascript, and since having the elements stored within an indexed array would just make me go crazy referencing each element by number, this is a no-no too.

What would be a clever way of accomplishing what I'm after?

Aucun commentaire:

Enregistrer un commentaire