JSXGraph, with more than one board on a page, what is recommended to avoid name-collision?

213 Views Asked by At

About having more than one board on a page:

When coding a graph it is convenient to use name conventions for the variables, such as the name for a slider. By default Javascript presents a global namespace, so if you have more than one board on a page you would have to avoid name-collision. What is the recommended way to do that?

1

There are 1 best solutions below

0
Cleonis On

[Note: stackoverflow endorses Q&A style self-answering. This is an intended answer-your-own-question]

This is a general Javascript question.

While Javascript was originally designed to offer only a global namespace for each webpage, fortuitously its feature set offers a way around that.

In the context of Javascript the common way this workaround is implemented is called an Immediately Invoked Function Expression (IIFE).

(function() {
  var board = JXG.JSXGraph.initBoard('jxgbox1' {/* ... */});
  var a = board.create('point', [0, 0]);
})();

Javascript has function scope. Using an IIFE capitalizes on that feature: the IIFE creates a scope. The functions inside that scope can reach out to the page (so the board will be placed in the div with the identifier 'jsxbox1'), but the variables inside the IIFE are separate from the global namespace.

In talking about programming languages in general this pattern of creating separate scopes is called 'closures'.


Minimal example for two boards

 (function() {
     var board = JXG.JSXGraph.initBoard('jxgbox1' {/* ... */});
     var a = board.create('point', [0, 0]);
 })();
 (function() {
     var board = JXG.JSXGraph.initBoard('jxgbox2' {/* ... */});
     var a = board.create('point', [0, 0]);
 })();

Noteworthy:
The option to pass parameters is equally available for IIFE's:

Minimal example:

 (function(divID) {
     var board = JXG.JSXGraph.initBoard(divID, {/* ... */});
     var a = board.create('point', [0, 0]);
 })('jxgbox1');
 (function(divID) {
     var board = JXG.JSXGraph.initBoard(divID, {/* ... */});
     var a = board.create('point', [0, 0]);
 })('jxgbox2');


The keyword 'var'

Here the keyword 'var' is necessary. When a variable is created without using the keyword 'var' the Javascript engine will traverse the scope chain. If the variable is not found anywhere in the scope chain the variable will be created in the global namespace. If the Javascript engine does find the variable in the scope chain it will use the existing variable. When the keyword 'var' is used the scope chain is not traversed.