Archive

facebook graph javascript api library code review

In the Graph API Facebook has shown us what is possible to do with cross domain imbaded JavaScript. I wanted to poke through their library to see if I can find any cool new patterns. Here is the unminified JavaScript library file.

The code overall is nice showcase of functional programming using JavaScript the way it was mean to be used. In order to accomplish two way cross domain communication, data are fetched in JSONP, and send through hidden iframe so a lot of the code are utilities that provide these communication channels and later the widgets itself.

The Facebook Graph API library uses an nice inheritance pattern which I have not seen before. In order to add a method to the namespace, it uses the "provide" method, which adds the appropriate namespace object and also ensure and older one does not get overwritten. It is used like this. (example of the String utility class)

FB.provide('String', {
    trim: function(a) {
        return a.replace(/^\s*|\s*$/g, '');
    },
    format: function(a) {
        if (!FB.String.format._formatRE) FB.String.format._formatRE = /(\{[^\}^\{]+\})/g;
        var b = arguments;
        return a.replace(FB.String.format._formatRE, function(e, d) {
            var c = parseInt(d.substr(1), 10),
                f = b[c + 1];
            if (f === null || f === undefined) return '';
            return f.toString();
        });
    },
    escapeHTML: function(b) {
        var a = document.createElement('div');
        a.appendChild(document.createTextNode(b));
        return a.innerHTML.replace(/"/g, '"').replace(/'/g, ''');
    },
    quote: function(c) {
        var a = /["\\\x00-\x1f\x7f-\x9f]/g,
            b = {
                '\b': '\\b',
                '\t': '\\t',
                '\n': '\\n',
                '\f': '\\f',
                '\r': '\\r',
                '"': '\\"',
                '\\': '\\\\'
            };
        return a.test(c) ? '"' + c.replace(a, function(d) {
            var e = b[d];
            if (e) return e;
            e = d.charCodeAt();
            return '\\u00' + Math.floor(e / 16).toString(16) + (e % 16).toString(16);
        }) + '"' : '"' + c + '"';
    }
});

Here is the part of the code that does the class creation:

...
    copy: function(d, c, b, e) {
        for (var a in c) if (b || typeof d[a] === 'undefined') d[a] = e ? e(c[a]) : c[a];
        return d;
    },
    create: function(c, h) {
        var e = window.FB,
            d = c ? c.split('.') : [],
            a = d.length;
        for (var b = 0; b < a; b++) {
            var g = d[b];
            var f = e[g];
            if (!f) {
                f = (h && b + 1 == a) ? h : {};
                e[g] = f;
            }
            e = f;
        }
        return e;
    },
    provide: function(c, b, a) {
        return FB.copy(typeof c == 'string' ? FB.create(c) : c, b, a);
    }
...

Comments: