brython: Function calls from element onclick results in error
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/brython@3.11.1/brython.min.js"></script>
</head>
<body onload="brython ()">
<script type="text/python">
from browser import document, html, window
def foo ():
print ("bar")
window.foo = foo
document <= html.BUTTON ("Foo", type = "button", onclick = "foo ();")
</script>
</body>
</html>
Expected behaviour: “bar” is printed when “Foo” button is clicked
Behaviour on Brython 3.11.0: Same as expected
Behaviour on Brython 3.11.1 and later: Raises TypeError: f is not a function and does not run the function
Tested on macOS Ventura 13.1 with Chrome 117 and Safari 16.2
About this issue
- Original URL
- State: closed
- Created 9 months ago
- Comments: 15 (14 by maintainers)
Commits related to this issue
- Change handling of "element.onclick = f". Related to issue #2254. — committed to brython-dev/brython by deleted user 9 months ago
- Change setting of attribute "onXXX" to DOMNode instances. Related to issue #2254. — committed to brython-dev/brython by deleted user 9 months ago
Hi,
The following code is working :
EDIT: I seems
onclickis implemented usingbind()? Indeed, it seems we can remove the listener by usingunbind()later.That would explain why it doesn’t accept a
str(and in my mind shouldn’t accept astr).Note : In JS it is often considered unsafe to use
onXXXXand is often preferred to useaddEventListener()(bind()in Brython).Indeed, the listener you add through
onclickand be removed by other code trying to add their own listener throughonclick. UsingaddEventListener()(bind()in Brython) enables to register many listeners (not just one), you can later remove withremoveEventListener()(unbind()in Brython).Imma test some stuff ^^.