### Web Services - Sample 14: Multi-Origin with JavaScript API buffered commands

quit pymol (FireFox only: view page source)

PyMOL should open up automatically when this page is loaded because we have an hidden IFRAME referencing a PWG file which tells PyMOL to launch and listen on port 8084.

As usual in the multi-origin scenario, the host and port of the PyMOL server must be specified when creating the PyMOL object inside JavaScript. However, to enable buffering, we also add a third argument: 'on'.

    var pymol = new PyMOL('localhost', 8084, 'on'); // create PyMOL object with buffering enabled

    var cmd = pymol.cmd; // assign a global symbol for the PyMOL cmd API

Enabling buffering prevents the problem where all PyMOL requests run in an undefined order (in certain browsers). However, requests must still of course run asynchrously in order to work around the same-origin policy.

The trick to using buffering in the multi-origin (cross-domain) scenario is to remember three things:

1. PyMOL API calls are not actually invoked unless you provide a callback function or call pymol.flush().
2. The value returned from the final method call is the argument provided to the callback function.
3. Method invocation is asynchronous, but will be in-order and completed by the time the callback is called.

So when you need to flush the buffer and force execution, you simply provide a callback function, which will be called after all of the prior requests have been evaluated. This enables us to simplify the burdensome example from Sample 12 with its four cascading functions into just two functions.

    function part2(list) {
        for(var i=0;i<list.length;i++) {
            cmd.color("auto","chain "+list[i]);
        }
        pymol.flush()
    }

    function part1() {
        cmd.reinitialize();
        cmd.load("$PYMOL_PATH/test/dat/1tii.pdb");
        cmd.show_as("cartoon");
        cmd.get_chains(part2, "polymer");
    }

    Start the cascade with a call to part1()

Note that we are considering adding a buffered mode to the PyMOL JavaScript interface which would improve performance by reducing the number of independent HTTP requests and provide an in-order-execution guarantee for multiple requests even when running asynchronously (under the multi-origin scenario).

Also, exceptions which occur in PyMOL are not presently returned to the JavaScript layer (though this may change).