I am trying to make a way to add functions under a specific namespace (dpcom). This may be in dotted notation depending on what the user has done in his javascript file. So basically, what I want them to do is something like this:
dpcom.library('something.foo.funcName', function() {
Then they can later call their things the following:
dpcom.something.foo.funcName();
What will execute the code that they defined above. The code in which I want to help make it sexier is here (it uses jQuery):
dpcom.library = function(name, func) { root = dpcom; objects = name.split('.'); lastElement = objects[objects.length - 1]; $(objects).each(function(idx, elem) { if (elem == lastElement) { root[elem] = func; } else if (!root[elem]) { root[elem] = {} } root = root[elem]; }); }
This should handle the possible dotted notation and create objects inside my namespace if they don't already exist (I don't want to overwrite any already declared objects).
The code that I have above seems to work fine, but I have a feeling that I can do it better, but my brain is not telling me where ... Does anyone want to hit it?
source share