pypyjs / pypyjs.github.io

PyPy.js website
4 stars 6 forks source link

collect some example snippets? Where? #3

Closed jedie closed 9 years ago

jedie commented 9 years ago

IMHO it makes sense to collect some example code snippets... Especial for the usage of the js module.

Snippets like this:


import js
navigator = js.globals["navigator"]
for js_string in dir(navigator):
    attr_name = str(js_string) # FIXME
    attr = getattr(navigator, attr_name, "-")
    if not isinstance(attr, (js.String, js.Array, js.Boolean)):
        continue
    print "%20s: %s" % (attr_name, attr)

from __future__ import print_function
import js # https://github.com/pypyjs/pypy/tree/pypyjs/pypy/module/js

def pprint_js_object(obj):
    print("Object:", obj, type(obj), obj.__doc__)
    print("dir:", dir(obj))
    print("Existing object attributes:")
    for attr_name in obj:
        attr_name = str(attr_name) # convert js.String https://github.com/pypyjs/pypy/issues/2
        print("%30s:" % attr_name, end="")
        try:
            value = getattr(obj, attr_name)
        except Exception as err:
            print("[Error: %s]" % err)
        else:
            value = str(value) # evaluate js.Handle
            value = repr(value) # e.g. escape newlines
            if len(value)>70:
                value = "%s..." % value[:70]
            print(value)

window = js.globals.window
pprint_js_object(window)
print(" --- END --- ")

import js # https://github.com/pypyjs/pypy/tree/pypyjs/pypy/module/js

jquery = js.globals["$"]
for i in range(10):
    jquery("#editor").before('<button id="button_%i">Click me %i!</button>' % (i,i))

@js.Function
def click_handler(event):
    print "You clicked on button with ID:", 
    print event.target.id

jquery("button").click(click_handler)

print "Please click on new button above!"

Snippets that are more a missing documentation ;)

I can create a simple django-app for this. But a public paste service is a other story.

EDIT: add another snippets...

jedie commented 9 years ago

Also a other story is: https://github.com/jedie/pypyjs-examples

What's about to transfer this repro to https://github.com/pypyjs/pypyjs-examples as a first step ?!? pypyjs-examples is more a playground for a "PyPy.js-App"

rfk commented 9 years ago

Yep, I like your 'examples' repo and it seems like a great low-friction starting point. I'll fork it into the pypyjs org.

jedie commented 9 years ago

@rfk i have no pull access on https://github.com/pypyjs/pypyjs-examples ;)

I have add the snippets from above here: https://github.com/jedie/pypyjs-examples#small-snippets

rfk commented 9 years ago

whoops, sorry, you should have access now

jedie commented 9 years ago

OK, the examples are pushed here: https://github.com/pypyjs/pypyjs-examples#small-snippets