### Web Services - Sample 08: Using the JavaScript API

view page source quit pymol (FireFox only: view page source)

As you saw in Sample 06, the PyMOL JavaScript API re-exposes PyMOL's Python programming interface directly to the JavaScript layer in an object-oriented way. However, there are some performance issues (and in some cases, reliability issues) associated with sending hundreds or perhaps thousands of HTTP requests in a very short period of time.

We have implemented a buffering system into the PyMOL JavaScript API which enables many requests to be combined into a single compound request, provided of course, that only one return value (the final result value) is required by the client.

The API is used as before, except that we enable the buffering option by passing 'on' as the third argument of the constructor

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

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

The trick to using buffering in the same origin scenario is to remember two things:

1. PyMOL API calls are not actually invoked until you call pymol.flush()
2. The value returned from the final invocation is the result from pymol.flush()

Python (inside PyMOL) |  | JavaScript (inside Browser)
--- | --- | ---
    cmd.reinitialize()
    cmd.load("$PYMOL_PATH/test/dat/1tii.pdb")
    cmd.color("white")

    count = cmd.count_atoms()

    for i in range(1,count+1):
        cmd.color("auto","index "+str(i))
    cmd.reinitialize();
    cmd.load("$PYMOL_PATH/test/dat/1tii.pdb");
    cmd.color("white")

    cmd.count_atoms()
    count = pymol.flush()

    for(var i=1;i<=count;i++) {
        cmd.color("auto","index "+i);
    }
    pymol.flush()
Run this program

Note that you can turn buffering on or off at any time with the setBufferMode method of the pymol object:

    pymol.setBufferMode('off') // disables buffering

    list = cmd.get_chains('1tii')  // immediate calls can now be made, with results returned

    pymol.setBufferMode('on') // restores buffering (must call flush to force execution)