Take a look at the snippet below. Is there any function I could write in replace of ...
to generate the route, that could reused in another function? Something like var route = this.show.fullyQualifiedName
perhaps?
var services = {
'github.com': {
api: {
v2: {
json: {
repos: {
show: function(username, fn) {
var route = ...;
// route now == 'github.com/api/v2/json/repos/show'
route += '/' + username;
return $.getJSON('http://' + route).done(fn);
}
}
}
}
}
}
}
No, there isn't, at least not using "reflection" style operations.
Objects have no knowledge of the name of the objects in which they're contained, not least because the same object (reference) could be contained within many objects.
The only way you could do it would be to start at the top object and work your way inwards, e.g.:
function fillRoutes(obj) {
var route = obj._route || '';
for (var key in obj) {
if (key === '_route') continue;
var next = obj[key];
next._route = route + '/' + key;
fillRoutes(next);
}
}
which will put a new _route
property in each object that contains that object's path.
See http://jsfiddle.net/alnitak/WbMfW/
You can't do a recursive search, like Alnitak said, but you could do a top-down search, although it could be somewhat slow depending on the size of your object. You'd loop through the object's properties, checking to see if it has children. If it does have a child, loop through that, etc. When you reach the end of a chain and you haven't found your function, move to the next child and continue the search.
Don't have the time to write up an example now, but hopefully you can piece something together from this.
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