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 better 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?
You should be able to do this in a slightly more appealing manner using shift():
dpcom.library = function(name, func) {
var root = dpcom,
objects = name.split('.'),
elem;
while (elem = objects.shift()) {
if (objects.length) {
if (!root[elem])
root[elem] = {};
root = root[elem];
}
else
root[elem] = func;
}
}
This way, you can ditch the jQuery requirement. Also, don't forget to explicitly declare your vars with the var keyword.
Depending on your definition of sexy code, you could also replace this block:
if (objects.length) {
if (!root[elem])
root[elem] = {};
root = root[elem];
}
with:
if (objects.length)
root = !root[elem] ? root[elem] = {} : root[elem];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With