1

I want to access variables by using

MyNamespace.variable1

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

1

4 Answers 4

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

It's just an object really.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

2

Just create an object. E.g.:

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

3 Comments

Where do I declare this... in a global space?
You can force global from anywhere by assigning it to window e.g. window.MyNamespace = {}
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.