⊗jsPmMCPPE 497 of 502 menu

Passing a parent element to module via closures in JavaScript

Let's say we have the following elements:

<div id="div1">1</div> <div id="div2">2</div> <div id="div3">3</div> <div id="res"></div> <button id="btn">click me</button>

Let the following module work with these elements:

;(function(selector1, selector2, selector3, selector4, selector5) { let div1 = document.querySelector(selector1); let div2 = document.querySelector(selector2); let div3 = document.querySelector(selector3); let res = document.querySelector(selector4); let btn = document.querySelector(selector5); btn.addEventListener('click', function() { let num1 = Number(div1.textContent); let num2 = Number(div2.textContent); let num3 = Number(div3.textContent); res.textContent = num1 + num2 + num3; }); })('#div1', '#div2', '#div3', '#res', '#btn');

As you can see, the number of parameters passed to the module is somewhat large and creates inconvenience. Usually, in this case, they proceed as follows: they pass to the module the common parent of all elements with which our module works, and already inside the module, various elements are obtained from this parent.

Let's make our tags have a common parent:

<div id="parent"> <div id="div1">1</div> <div id="div2">2</div> <div id="div3">3</div> <div id="res"></div> <button id="btn">click me</button> </div>

Let's change the module code now:

;(function(root) { let parent = document.querySelector(root); let div1 = parent.querySelector('#div1'); let div2 = parent.querySelector('#div2'); let div3 = parent.querySelector('#div3'); let res = parent.querySelector('#res'); let btn = parent.querySelector('#btn'); btn.addEventListener('click', function() { let num1 = Number(div1.textContent); let num2 = Number(div2.textContent); let num3 = Number(div3.textContent); res.textContent = num1 + num2 + num3; }); })('#parent');

Thus, it turns out that we pass the parent element to the module from the outside and can easily change it. And child elements are an internal matter of the module.

enru