jojo
jojo

Reputation: 13843

how to define global namespace in javascript

is there a way to define global namespace, so that i can call function from this namespace from all my page?

e.g

// in one file i define below code

DefineNameSpace("my.namespace.api", { 
    addObject: function(obj) {
         // store obj into indexDB
    },
    readAllObject: function() {
         // return array of object from indexdb
    }
})

// so that in another javascript file i can do

my.namespace.api.addObject({name: "foo", desc: "bar"});

is there a way to implement "DefineNameSpace" method?

Thanks

Upvotes: 1

Views: 1552

Answers (2)

Daniel van Dommele
Daniel van Dommele

Reputation: 550

building a namespace dynamically can be done in the following way:

// the root of the namespace would still be handy to have declared here
var my = {};

function defineNamespace(namespaceStr) {
   var namespaceSegments = namespaceStr.split(".");
   var namespaceSoFar = null;

   // iterate through namespace parts
   for (var i = 0; i < namespaceSegments.length; i++) {
      var segment = namespaceSegments[i];

      if (i == 0) {
          // if namespace starts with my, use that
          if (segment == "my") { 
              // set pointer to my
              namespaceSoFar = my;
          }
          else {
          // create new root namespace (not tested this, but think this should work)
              var otherNamespace = eval(segment);
              if (typeof otherNamespace == "undefined") {
                 eval(segment + " = {};");
              }
              // set pointer to created root namespace
              namespaceSoFar = eval(segment);
          }  
      }
      else {
          // further build the namespace
          if (typeof namespaceSoFar[segment] == "undefined") {
              namespaceSoFar[segment] = {};
          }
          // update the pointer (my -> my.namespace) for use in the next iteration
          namespaceSoFar = namespaceSoFar[segment];
      }
   }
}

Upvotes: 1

Daniel van Dommele
Daniel van Dommele

Reputation: 550

one way to do it, which is very simple, is this:

my = {
   namespace: {
      api : {}
   }
}

my.namespace.api.addObject = function (obj) { }

you're actually creating objects but in this way it will function as a namespace just as well :)

hm it's not the method you're implementing. But building a namespace with a method would require the function to be called before the script files are loaded where the namespace is used like that, otherwise those lines of code are called before the DefineNamespace method is called and you will run into parts of namespaces that are undefined at that point. With above solution that won't be the case, although it is not dynamic unfortunately.

Upvotes: 3

Related Questions