Skip to content

Calling a jQuery component from Pyjs

bittner edited this page Jul 4, 2012 · 3 revisions

First some notes:

  • Loading jQuery in the .html puts the jQuery library in the top context. Directly accessing it via a JS call is not working, since the jQuery component can not be found.
  • Pyjs is creating the components in the top document too
  • so now we have jQuery in the top context, and the created component in the top context.
  • Since jQuery uses by the default the context in which it was loaded to look for components, we just need to use the top jQuery.
  • To do that, we need the top. prefix. Better yet, use the parent. prefix. Best, use $wnd in Pyjs code. -- This way the Pyjs code could be embedded in another iframe, and it would still work (for example, when using together with web2py).

The resulting code looks like this:

import pyjd # this is dummy in pyjs

from pyjamas.ui.HTML import HTML
from pyjamas.ui.RootPanel import RootPanel
from __pyjamas__ import JS

class jQueryTest:

    def onModuleLoad(self):
        html = HTML('<p><input type="hidden" id="aa10" style="width:300px" value="brown, red, green"/></p>')
        RootPanel().add(html)
        JS("""top.jQuery("#aa10").select2({tags:["red", "green", "blue"]});""")

if __name__ == '__main__':
    pyjd.setup("./public/jQueryTest.html")
    app = jQueryTest()
    app.onModuleLoad()
    pyjd.run()

And this is the related html file:

<html>
    <head>
        <script src="jquery-1.7.2.min.js"></script>
        <link rel="stylesheet" href="select2.css" />
        <script src="select2.js"></script>
        <meta name="pygwt:module" content="jQueryTest">
        <title>Test jQuery!</title>
    </head>
    <body bgcolor="white">
        <script language="javascript" src="bootstrap.js"></script>
        <iframe id='__pygwt_historyFrame' style='width:0;height:0;border:0'></iframe>
    </body>
</html>

Notes

  • This example depends on jQuery and Select2
  • Instead of including the JS libraries with script tags in the HTML head section jsimport() statements can be used. See the examplejs example for details.
  • iframe tag and script tag not necessary with recent versions (> 0.8) of Pyjs, as pyjsbuild injects both automatically

Alternative jQuery Use

  • Use $wnd to access the parent window, which is the scope where external libraries such as jQuery are accessible from
  • Use @{{myvar}} to access Python variables in JavaScript code (i.e. in a JS(...) statement)
def jQuery():
    """Provide jQuery from parent window ($wnd is parent of iframe)"""
    JS("return $wnd.jQuery;")

class foo:
    def bla(self):
        ...
        jQuery()(self.slider.getElement()).slider(sliderOpts)

    def final_setup(self, selected = '"red", "green", "blue"'):
        myid = str(self.myid)
        JS('''parent.jQuery(@{{myid}}).select2({tags:[@{{selected}}]});''')
Clone this wiki locally