Question

OK, so let's say I have a web app(Javascript) that is set up in the "Revealing Module Pattern" and I have two modules that use the exact same data.

example:

(Lets pretend there is a reason for these two functions to be in separate modules. It's just an example after all)

var modOne = (function () {
  var foos = document.getElementsByClassName("foo");

  var hideFoos function () {
    var i;
    for (i=0; i < foos.length ; i++) {
      foos[i].style.visibility = "hidden";
    }
  }

  return {
    hideFoos: hideFoos
  };
})();

var modTwo = (function () {
  var foos = document.getElementsByClassName("foo");

  var showFoos function () {
    var i;
    for (i=0; i < foos.length ; i++) {
      foos[i].style.visibility = "visible";
    }
  }

  return {
    showFoos: showFoos
  };
})();

As you can see an identical variable (var foos) is declared in each module. This seems redundant, but referencing the variable in another variable would make one module reliant on the other. So you might as well just combine them. The third option I see would be to just create the shared variable as a global, which sort of defeats the purpose of having modules.

So based on these three options I would say that defining the variable separately in each module would be the best option.

Is this correct?

Was it helpful?

Solution

There is no one-size-fit-all answer here. There are benefits to all approaches.

In your particular example, it seems that both modOne and modTwo do some things with a DOM element (have methods that show/hide the child nodes). Both modules are very linked to the DOM elements they work on, meaning that you can't reuse the module to work on other elements. When you think about it that way, it becomes apparent that the Elements they act on (the data the module acts on) should be provided by an outside source, so having a global variable that gets passed to each module seems better. What might be even better would be a data service module that passes the data the modules need.

Continuing on this path you can see how a simple show/hider turns into a monstruous multi-layered architecture that is too complex to tackle without a thorough understanding of the whole system.

With that in mind, the answer is that you should go for whatever makes your code clearer. Complex applications call for complex solutions, simple applications should get simple solutions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top