Looking inside dojo…and patching

While developing a simple rest service I needed a simple web interface.

While a full-featured dojo is quite heavy, if you use dojo mobile without importing any dijit stuff you can speed up things a lot. And if you use an http cache for static contents thing will even get better!

I choose dojo mobile 1.7 because it has a nice Grid+Store implementation.

Grid+Store is a toy that renders the json output of an url into an html table or list. When the url response changes, the page is updated.

Moreover the Grid/List can bind each row to an action, so that if you click on a item, you’ll be directed to another page. In my case the main view shows a list of file, and clicking on one file you will see it’s attributes (size & co).

So, when clicking on a file I needed to issue an ajax request retrieving file info from the server.
Dojo implements this using the “callback” tag.

  • file.txt

  • The previous html is generated by a json string like the following, so with dojo Store you can dynamically build a list with actions connected to each item.

    { 'item' : {
    'label' : 'file.txt',
    'moveTo' : 'fileView',
    'callback' : 'function() {renderfile("/path/to/file.txt");}'

    In dojo 1.7 the callback stuff is broken, so after looking on dojo trac, I found and apply a patch. Still no way, but at least I got an error – while before the patch the callback parameter was simply ignorated.

    The error was something like

    Object "renderfile('/path/to/file.txt')" has no method apply

    The apply() method is a js method that a function must have. Better: if a js object hasn’t the apply() method, then it’s not a function!

    Using js console I found that the callback argument was interpreted as a string, and not as a function.

    So I start investingating on the json I used to populate the grid. And I noted that the issue was related to the quote sign around the callback function.

    In fact json encloses in string only strings, not numbers or functions. But the json was generated by the server, using python simplejson library. For that lib, a js function is a string, so it’s encosed in quote.

    The solution was to find the place where the function was called in dojo, and add a test: if the object supposed to contain a method is a string, then you evaluate the string to a method.

    +if (typeof(scope[method].apply) == "undefined" ) {
    + scope[method] = eval(scope[method]);
    return scope[method].apply(scope, arguments || []);

    +if (src.callback && typeof(src.callback.apply) == "undefined") {
    + src.callback = eval(src.callback);
    w.performTransition(moveTo, evt.detail.transitionDir, evt.detail.transition, src.callback && src, src.callback);

    Json and Django: mythe and music in the dojo

    Json have been already presented by Fabio Fucci on this blog. Django is a python framework for web application, which supports json thru a library.

    We’re going to create a simple request-response application:

    1. request is issued by dojo.xhrPost;
    2. response is managed by python.

    Creating a request means creating a json string to send to the server.

    /* create the variable to post */
    var arguments={'user':'ioggstream','status':'at work'};

    url: '/json/post',
    handleAs: "json",
    /* serialize the argument object to a json string*/
    postData: dojo.toJson(arguments),
    load: function(data) {
    error: function(error) {
    alert("An unexpected error occurred: " + error);

    Now that the request is issued, and the postData is a json string, we use python to de-serialize the string to a python object.
    The dict() python class – aka dictionary – is an associative array. The django.simplejson can serialize and deserialize object using dict().

    Let’s see the code

    from django.utils import simplejson
    from google.appengine.ext import webapp

    class JsonService(webapp.RequestHandler):
    def post(self):
    logging.info("manage a POST request")
    # parse request body to a python dict() object
    args = simplejson.loads(self.request.body)
    # returning request in a verbose mode
    # creating a dict() object with default message
    message = {'result':'The request misses user and/or       status'}
    if 'user' in args and 'status in args:
    message['result'] = "The request user %s status is %s " % (args['user'], args['status'])
    # return the serialized object message
    return simplejson.dumps(message)

    Perchè odiare IE

    Tutti sanno quanto è odioso il browser (??) di Microsoft… non rispetta gli standard ne per l’html ne per il javascript il che rende la programmazione web multi-browser veramente problematica…. ma c’è di più…

    Pochi sanno che il nostro amico IE ha introdotto limitazioni sul numero dei CSS caricabili per ogni pagina… in particolare questo numero è 32… ciò significa che se io ho 33 css l’ultimo è (SEMPLICEMENTE!!!!) ignorato…

    Ora Jmaki (il framework per la programmazione web di sun) prevede un CSS per ogni componente, che in media, su grandi applicazioni, saranno piu di 32… soluzione??? usare il framework solo per la parte script e html e ridurre il numero dei CSS il più possibile….perdendo comunque, in parte, il vantaggio dell’ordine offerto da jmaki….

    Ancora una volta non ci resta che ringraziare Internet Explorer!!!

    Javascript: setattribute bug

    In javascript fare setattribute sugli elementi del dom, non setta correttamente le proprietà su tutti i browser.

    A tal scopo ho fatto una piccola (MA UTILISSIMA) raccolta su quali property andrebbe usato il setAttribute mentre mostra l’alternativa sugli altri:

    Attributi Cosa fare
    class obj.className=”
    value obj.value=”
    for obj.setAttribute(‘htmlFor’,”)
    colspan obj.setAttribute(‘colSpan’,”)
    id obj.id=”
    type obj.setAttribute(‘type’,”)
    name obj.name=
    size obj.setAttribute(‘size’,”)
    title obj.setAttribute(‘title’,”)
    tabindex obj.setAttribute(‘tabIndex’,”)
    onclick ed altri eventi obj.onclick = function f(){g(parametri_di_g);};

    checked (del check)  check.checked = true; (NOTA FUNZIONA SOLO DOPO
    averlo appeso al dom)

    Per quelli non elencati dovrebbe essere valido il setAttribute.

    Per ulteriori info visitare http://webbugtrack.blogspot.com/2007/08/checkedbug-242-setattribute-doesnt-always-work.html

    how to de-obfuscate js code

    from http://tirania.org/blog/archive/2007/Nov-16-1.html

    the how-to follows, but I recommend to read the article..

    If .. you want to prepare for your interview at Google, Jeff Walden suggests a hard-core approach:
    …SpiderMonkey, Mozilla’s C JavaScript engine, … includes a decompiler which translates from SpiderMonkey bytecode to JavaScript (most people only use it the other way around). You can see it at work any time you convert a function to a string. … SpiderMonkey … decompiles the bytecode back to a JavaScript string representing the function as exactly as possible, while … formatting the decompiled source to be reasonably readable.
    How … to reformat obfuscated source?

    First, you get a copy of SpiderMonkey:

    export CVSROOT=:pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot
    cvs co mozilla/js/src
    cd mozilla/js/src
    make -f Makefile.ref clean && make -f Makefile.ref # work around broken dependency system
    ./Linux_All_DBG.OBJ/js # to run the interpreter

    Next, you dump the JS code you want to reformat into a function, and you have SpiderMonkey pretty-print it:

    echo “function container() {” > obfuscated.js
    cat file-to-clean-up.js >> obfuscated.js
    echo “} print(container.toString());” >> obfuscated.js
    path/to/js -f obfuscated.js

    SpiderMonkey will then print the container function’s string representation, adjusting indentation and such to create a readable, if still name-obfuscated, version.
    A couple things to know about this: first, SpiderMonkey doesn’t pretty-print functions found in expression context:

    (function() {
    print(“this won’t get cleaned up”);
    call_method(function() {
    print(“this will probably be crunched to one line”);
    print(“not pretty-printed”);

    These examples are converted (once stripped of the containing function) to:
    (function () {print(“this won’t get cleaned up”);}());
    call_method(function () {print(“this will probably be crunched to one line”);print(“not pretty-printed”);});