-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathbindings.py
97 lines (74 loc) · 2.88 KB
/
bindings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""Decorator function for UI elements to bind events to buttons."""
from functools import wraps
from pyodide.ffi import create_proxy
from js import document
def bind(event, id, iterations=0):
"""Bind a function to an event for a buttton.
Args:
event (str): Event to bind to eg: click
id (str): ID of the element to bind to.
iterations (int, optional): If we want to run this function multiple times with an increasing iteration. Defaults to 0.
"""
def real_decorator(function):
"""Return the main decorator back this is the main response.
Args:
function (func): The original function.
Returns:
func: The original function to return.
"""
function = create_proxy(function)
if iterations == 0:
if document.getElementById(id) is not None:
try:
document.getElementById(id).addEventListener(event, function, False)
except Exception:
pass
else:
for i in range(0, iterations):
if document.getElementById(id) is not None:
try:
document.getElementById(id + str(i)).addEventListener(event, function)
except Exception:
pass
@wraps(function)
def wrapper(*args, **kwargs):
"""Wrap our existing function with our passed function.
Returns:
func: The function to wrap.
"""
retval = function(*args, **kwargs)
return retval
return wrapper
return real_decorator
def bindList(event, idList, *, prefix="", suffix=""):
"""Bind a function to an event for a list of buttons.
Args:
event (str): Event to bind to eg: click
idList (str[]): A list of IDs of the elements to bind to.
prefix (str, optional): A string prefix to add to the start of each ID.
suffix (str, optional): A string suffix to add to the end of each ID.
"""
def real_decorator(function):
"""Return the main decorator back this is the main response.
Args:
function (func): The original function.
Returns:
func: The original function to return.
"""
function = create_proxy(function)
for id in idList:
try:
elementName = prefix + id + suffix
document.getElementById(elementName).addEventListener(event, function)
except Exception:
pass
@wraps(function)
def wrapper(*args, **kwargs):
"""Wrap our existing function with our passed function.
Returns:
func: The function to wrap.
"""
retval = function(*args, **kwargs)
return retval
return wrapper
return real_decorator