Child pages
  • Define a namespace and create a closure

Documentation for a historical release of Infusion: 1.4
Please view the Infusion Documentation site for the latest documentation, or the Infusion 1.3. Documentation for the previous release.
If you're looking for Fluid Project coordination, design, communication, etc, try the Fluid Project Wiki.

Skip to end of metadata
Go to start of metadata

Infusion code generally follows a few conventions that we recommend, and that we'll use in this tutorial. We'll start with two of them:

  1. namespacing, and
  2. closures

We define a namespace for our code: a single global variable that becomes the container for the code. This helps keep code contained, meaning there's less chance of bad interactions with other code: Anything we want to be public will be attached to this object, so all of our code will be qualified by the namespace.

By wrapping the rest of the code inside an anonymous function, we can separate private and public functions. Only objects or functions that are attached to the global namespace object will be publicly available. Anything else inside the anonymous function will be invisible to the rest of the world.

General Structure

So what does this look like in general?

// The global namespace
var mynamespace = mynamespace || {};

(function ($, fluid) {

    // a private function, only accessible to other things
    // inside this closure
    var privateFunc = function () {

    // a public function, attached to the namespace
    mynamespace.publicFunc = function () {

})(jQuery, fluid_1_4);

The parameters to the anonymous function, $ and fluid, will be used as shorthand for the arguments that were passed in: jQuery and fluid_1_4 respectively. This allow us, for example, to upgrade to the next version of Infusion (e.g. fluid_1_5) simply by changing the one argument, instead of having to change every single use of the word fluid.


So what might this look like in the real world? Well, for our bar graph example, we might call the global namespace visualizer and create a public function called barGraph that can be used by anyone to instantiate a bar graph component:

// The global namespace
var visualizer = visualizer || {};

(function ($, fluid) {

    // put any private things the bar graph will need here

    // the public bar graph creation function
    visualizer.barGraph = function () {

})(jQuery, fluid_1_4);
  • No labels