I'm trying to make a way to add functions under a specific namespace (dpcom). This may be in dot notation depending on what the user did in their javascript file. So basically, what I want them to do is something like this:
dpcom.library('something.foo.funcName', function() {
// Code goes here.
}
They can then call their stuff later like:
dpcom.something.foo.funcName();
Which will execute the code they defined above. The code I want help with in making it sexier is here (it's using 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 dot notation and create objects inside of my namespace if they don't already exist (I don't want to overwrite any already declared objects).
The code I have above seems to work great, but I have a feeling I can make it better but my brain isn't telling me where... Anyone want to take a stab at it?