I CAN HAS CODE?!?
May
20
Posted in Code Quickie by Michael at 00:40.
Tags: ,

So, yesterday I decided to play around with Adobe AIR, which I’m not familiar with, in conjunction with Ext JS, which I am familiar with.  Overall, if you are familiar with Ext JS on the web, you’re familiar with it in Adobe AIR … except for a number of unique issues due to Adobe AIR’s default sandbox, mostly revolving around the sandbox and what you can and can’t do in it.  Well, I ran into an issue tonight where I needed to use a JsonReader and use Record mappings with dot notation (i.e. binding a field to a child object in the JSON data).  My guess is that, as is the case with eval, new Function(…), which is what the default implementation of getJsonAccessor uses, is blocked by the sandbox.  I fixed it by extending the default JsonReader and providing a new implementation of getJsonAccessor using some code I created a while back for form binding in JavaScript.

JsonReader = Ext.extend(Ext.data.JsonReader, {
    exprToPath: function(expr) {
        var parts = expr.split(".");
        var path = [];
        Ext.each(parts, function(item, index, list) {
            var match = item.match(/([a-zA-Z0-9_]+)\[([^\]]+)\]/);
            if (match)
            {
                path.push(match[1]);
                if (/^\d+$/.test(match[2]))
                    path.push(parseInt(match[2]));
                else
                    path.push(match[2]);
            }
            else
            {
                path.push(item);
            }
        });
        return path;
    },  

    getDataValue: function(o, path) {
        var current = o;
        var rPath = path.slice().reverse();
        while (current && rPath.length > 0)
        {
            var key = rPath.pop();
            if (typeof current[key] !== 'undefined') current = current[key]; else return null;
        }

        return current;
    },

    getJsonAccessor: function(expr) {
        var self = this;
        var path = this.exprToPath(expr);
        return function(obj) {
            return self.getDataValue(obj, path);
        };
    }
});

It’s probably a bit of overkill for what is needed, but it does work well.

Both comments and pings are currently closed.

Comments are closed.