General Interface is an open source project hosted by the Dojo Foundation

Protecting Application Code with Packages

The application namespace isn't the only namespace that needs to be protected from other General Interface applications. Project JavaScript code should also be placed in a unique namespace to avoid affecting and being affected by other applications. A JavaScript namespace is known in General Interface as a package.

In general, applications should not declare global JavaScript functions. The following code defines a global JavaScript function:

function doTest() {
   return 1;
}

This is equivalent to declaring the function as a member of the global window object:

window.doTest = function() {
   return 1;
};

Since all General Interface applications deployed in the same web page share the same global window object, any code placed in it isn't private to a particular application. If two different applications define a global doTest() method, one version is overridden by the other and one application will probably break.

To avoid any naming collisions in function and variable names, all code should be placed in packages. Using the reverse domain naming convention is a good choice for avoiding collisions. A package is essentially a nested data structure descending from the window object. The following code creates the com.tibco.gi package and defines the doTest() function in it.

window["com"] = new Object();
com.tibco = new Object();
com.tibco.gi = new Object();
com.tibco.gi.doTest = function() {
   return 1;
};

However, this code has a bug in it, because it will destroy any previously defined package descending from window.com, such as com.tibco.porta l. With this technique for creating a package, the nested objects should only be created if they do not already exist.

The jsx3.lang.Package class simplifies the task of creating a package greatly with the definePackage() method. The following code also defines the doTest() function in the com.tibco.gi package but without the bug in the previous code sample:

jsx3.lang.Package.definePackage("com.tibco.gi", function(gi) {
   gi.doTest = function() {
      return 1;
   };
});

Since JavaScript packages can be named using the reverse domain naming convention, they are very safe from naming collisions.

For more information, see the jsx3.lang. Package in General Interface API Reference.

Contents

Searching General Interface Docs

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.