| 1 | = Attaching To Events = |
---|
| 2 | |
---|
| 3 | |
---|
| 4 | == Statically in RML == |
---|
| 5 | The easiest way to attach to events with python is to write your code directly into the RML files, using the on* attributes. When the event is fired three global variables are set up, ''document'', ''event'' and ''self''. |
---|
| 6 | |
---|
| 7 | ||self||The element thats currently being processed|| |
---|
| 8 | ||[wiki:documentation/PythonManual/Documents document]||The document the element thats currently being processed belongs to|| |
---|
| 9 | ||[wiki:documentation/PythonManual/Events event]||The event thats currently being processed|| |
---|
| 10 | |
---|
| 11 | Example: |
---|
| 12 | {{{ |
---|
| 13 | <button onclick="print('Clicked!')"/> |
---|
| 14 | }}} |
---|
| 15 | |
---|
| 16 | To aid in the coding of inline Python code, libRocket allows multiple lines of Python code can be put on one line, separated by a semicolon. The parser will then reformat this code before passing it to the Python interpreter. |
---|
| 17 | |
---|
| 18 | Example: |
---|
| 19 | {{{ |
---|
| 20 | <button onclick="print('Line 1');print('Line 2')"/> |
---|
| 21 | }}} |
---|
| 22 | |
---|
| 23 | |
---|
| 24 | == Dynamically from Python Code == |
---|
| 25 | |
---|
| 26 | The Python version of AddEventListener is modelled directly on Javascript. This allows you to bind any callable Python object (free function or method) or string to an event. |
---|
| 27 | |
---|
| 28 | Method 1: |
---|
| 29 | {{{ |
---|
| 30 | element = document.GetElementById('button') |
---|
| 31 | element.AddEventListener('onclick', "print('Line 1');print('Line 2')", True) |
---|
| 32 | }}} |
---|
| 33 | |
---|
| 34 | Method 2: |
---|
| 35 | {{{ |
---|
| 36 | def OnClick(): |
---|
| 37 | for i in range(10): |
---|
| 38 | print('Line ' + str(i)) |
---|
| 39 | |
---|
| 40 | element = document.GetElementById('button') |
---|
| 41 | element.AddEventListener('onclick', OnClick, True) |
---|
| 42 | }}} |
---|
| 43 | |