5

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);
                        }
                    }
                }
            }
        }
    }
}
2
  • I do not think a top-down search is possible. How will the search know when it's found its match unless I've provided it with the full path of show? And if I've provided it with the full path of show, that defeats the point of use a single function o get route values from inside any method like show I define. Commented Apr 27, 2012 at 19:06
  • you'd have to recursively fill the tree (just once) before ever calling the function. Commented Apr 27, 2012 at 19:11

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.