Search code examples
pythontranscrypt

How to test undefined in transcrypt


I need to test if a javascript object attribute exists.

For example to see if a jquery extension is available. The next line returns undefined in the browser console :

$("#myid").toc

I want to test this value in transcrypt, I tried :

getattr(S ("#myid"), "toc") is None

but it doesn't work :-/


Solution

  • The following will work:

    HTML:

    <html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>    
        </head>
        <body>
            <div id="myid"></div>
            <script src="__javascript__/test.js"></script>
        </body>
    </html>
    

    Transcrypt:

    __pragma__ ('alias', 'S', '$')
    
    print (111, getattr (S ('#myid') [0], 'style') != None)
    print (222, getattr (S ('#myid') [0], 'toc') != None)
    
    console.dir (S ('#myid') [0])
    

    It prints:

    111 True
    222 False
    div#myid
    

    As an alternative you can always embed JS in Transcrypt:

    __pragma__ ('js', '{}', '''
       console.log (333, $("#myid")[0].style != undefined);
       console.log (444, $("#myid")[0].toc != undefined);
    ''')
    

    Which prints:

    333 true
    444 false
    

    I prefer the Python syntax, by the way. But in edge cases JS is always there as an escape, although you'll probably never need it.