1

I want to access variables by using

MyNamespace.variable1

that are globally accessible. I believe Drupal does something similar, no?

Shamoon
  • 41,293
  • 91
  • 306
  • 570
  • possible duplicate of [Javascript Namespace Declaration](http://stackoverflow.com/questions/881515/javascript-namespace-declaration) – haylem May 31 '11 at 23:04

4 Answers4

4
var MyNamespace = {};
MyNamespace.variable1 = value1;

It's just an object really.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
3

Also, if you have many JS files that each add a "namespace" or Object into a top level package you can do stuff like this:

ModuleA.js

// if Modules is null, create a new object, else use the currently defined instance
var Modules = Modules || {}; 

Modules.A = {};

// sample instance variable
Modules.A.instanceVar; 

// sample function
Modules.A.myFunc = function(param1, param2) {
   // do something
}

ModuleB.js

// if Modules is null, create a new object, else use the currently defined instance
var Modules = Modules || {};

Modules.B = {};

// sample instance variable
Modules.B.instanceVar; 

// sample function
Modules.B.myFunc = function(param1, param2) {
   // do something
}

Then you can of course just call them as you need them Modules.A.myFunc() or Modules.B.myFunc() or Modules.B.instnaceVar = 20;. So you can encapsulate functions as well as variables.

For my code I like to have a root Object, (i.e ) and then added "classes" (objects) to it so that everything has a nice "package like", "OOP" structure to it.

Kenny Cason
  • 12,109
  • 11
  • 47
  • 72
3

What Drupal does is using the following code:

var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'locale': {} };

Drupal.attachBehaviors = function (context, settings) {
  context = context || document;
  settings = settings || Drupal.settings;
  // Execute all of them.
  $.each(Drupal.behaviors, function () {
    if ($.isFunction(this.attach)) {
      this.attach(context, settings);
    }
  });
};

Drupal.detachBehaviors = function (context, settings, trigger) {
  context = context || document;
  settings = settings || Drupal.settings;
  trigger = trigger || 'unload';
  // Execute all of them.
  $.each(Drupal.behaviors, function () {
    if ($.isFunction(this.detach)) {
      this.detach(context, settings, trigger);
    }
  });
};

// …

Using similar code, you can emulate namespaces using JavaScript.

apaderno
  • 28,547
  • 16
  • 75
  • 90
2

Just create an object. E.g.:

var MyNamespace = {};
MyNamespace.variable1 = ...
Matt
  • 43,482
  • 6
  • 101
  • 102
  • Where do I declare this... in a global space? – Shamoon May 31 '11 at 22:58
  • You can force global from anywhere by assigning it to `window` e.g. `window.MyNamespace = {}` – Matt May 31 '11 at 22:59
  • Just to be complete. JavaScript can run in environments where there is no DOM or `window` so don't always assume you can use it. I would just define it in global space without the `window.` – Halcyon May 31 '11 at 23:09