JavaScript API¶
Require the JavaScript API as
const pynwjs = require('pynwjs');
and use the functions offered by pynwjs to interact with the Python code
as described in the following.
-
pynwjs.on(event, callback)¶ Register a callback function for the specified event.
Arguments: - event (string) – Name of the custom event which will trigger the callback.
- callback (function) – Callback function for the event, should accept one argument which will contain the data for the event.
Example
Assume that we want to display some text sent from Python in an HTML element.
pynwjs.on('python_text', text => { var element = document.getElementById('my_text_display'); element.innerText = 'Python says: ' + text; });
-
pynwjs.emit(event, data)¶ Emit a custom event with the data.
Arguments: - event (string) – Name of the custom event.
- data (object) – Any event data to be sent to Python. The data will be serialized as JSON object.
Example
Notify Python about some event:
pynwjs.emit('hello', 'Hello Python World!');
-
pynwjs.eventHandler(event)¶ Register an event listener for built-it events of any HTML element. Do not call this function yourself, but set it as callback for the respective event.
Arguments: - event (Event) – The event object as provided by the triggered event.
Note
This is required to notify Python about the respective HTML event. Otherwise, registered event handlers in Python will not be triggered.
Example
Register the event handler for clicking on some button:
document.getElementById('my_button').addEventListener('click', pynwjs.eventHandler);