views:

115

answers:

1

I've been looking for a replacement for Python's __getattr__ in JavaScript, and a couple answers here mentioned Firefox's __defineGetter__. Not only is that not cross-browser compatible but it doesn't really allow for you to do anything really useful like this pseudo-code does:

var api = function()
{
    var __getattr__ = function(attr, args)
    {
        var api_method = attr;
        $post(url, api_method, args, function(response){alert(response)});
    }
}

// Now api.getprofile('foo', 'spam'); would call the following code behind the scenes:
$post(url, 'getprofile', ['foo', 'spam'], function(response){alert(response)});

Obviously this is pseudo code but is there any known way to do this for real in JavaScript? I understand I could very well use the manual version (the last line of code) but when you get to about 30 functions, this becomes very tedious.

+1  A: 
var api = {
    getAttr:function(attr) {
        var args = [];
        for (var i = 1; i < arguments.length; i++) {
            args.push(arguments[i]);
        }
        $post(url, attr, args, function(response){alert(response)});
    }
};

It's not the prettiest thing and doesn't act quite the same, but it should work. You'd have to call it like this: api.getAttr('getprofile', 'foo', 'spam');

Bob
My current version is similar to that (except in a jQuery plugin that I wrote). It'll still save loads of time but I wish there was a method for direct `.` access to all methods, and then I could throw an exception if they try to call one that doesn't exist.
orokusaki