1

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

jojo
  • 13,583
  • 35
  • 90
  • 123

2 Answers2

3

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.

1

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];
      }
   }
}
  • bare in mind that the only problem is that a namespace created in this way is only usable after calling this method. if the other files /script blocks that use the namespace are loaded together with the script block that contains this method it will cause an error, so something should be thought of to avoid that problem. – Daniel van Dommele Aug 09 '13 at 07:39