Version 2 (modified by lloydw, 10 years ago)
--

Attaching To Events

Statically in RML

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.

selfThe element thats currently being processed
documentThe document the element thats currently being processed belongs to
eventThe event thats currently being processed

Example:

<button onclick="print('Clicked!')"/>

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.

Example:

<button onclick="print('Line 1');print('Line 2')"/>

Dynamically from Python Code

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.

Method 1:

element = document.GetElementById('button')
element.AddEventListener('onclick', "print('Line 1');print('Line 2')", True)

Method 2:

def OnClick():
  for i in range(10):
    print('Line ' + str(i))

element = document.GetElementById('button')
element.AddEventListener('onclick', OnClick, True)

Attaching Globally to Contexts

Global Listeners are not encouraged, however sometimes they're useful - mainly for debug tools that need to process key/mouse events across the entire system. When attaching globally from Python you are required to provide an element context from which the event will fire. So that the event can correctly have its document and element states set up.

Example:

context = rocket.GetContext('main')
context.AddEventListener('click', "print('Global Click!')", context.GetDocument('debugger').GetElementById('window'), False)

NOTE: If you're trying to add a listener to receive clicks for the Game World, rather than attaching globally, make a special document, with an element the size of the screen and lock it to the background. You can then attach mouse/key events to that element and you'll only receive events when the user is not interacting with the foreground interface screens