Javascript function pattern
--
We all know the problem lots of javascript functions and a polluted global namespace. To manage this I have built a pattern for anonymous functions as variables to use client side in an application.
The basic requirement is that it is easy to stack the functions for initialisation calls and the functions within this function are effectively namespace protected from each other.
I am assuming you are familiar with the basic use of an anonymous function as the value of a variable:
var functionName = (() => { }) ();
To this we add some initialisation management:
var functionName = (() => {
let initDone = false;
let loadPrevious;
let init = () = {
if (!initDone) {
initDone = true;
…
if (functionName.loadPrevious) functionName.loadPrevious();
}}
Add a return to the function to expose internal variables:
return {init: init, loadPrevious:loadPrevious)
And after the function definition:
functionName.loadPrevious = window.onload; window.onload = functionName.init;
Replace the … with anything that needs to be done to initialise. Any asynchronous calls should have a callback function. You can sort of get some callback hell from this but there are ways to manage that (not the subject of this). Calling loadPrevious should be inside a callback function if you have async calls.
Of course other functions can be defined (as variables to avoid hoisting) within the function and exposed using the return value.
This simple and effective pattern has allowed us to build an extensive managed functional programming environment.