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

Most upvoted comments

Hi,

The following code is working :

<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
        def foo (ev):
           print ("bar")
        document <= html.BUTTON ("Foo", type = "button", onclick = foo)
    </script>
</body>
</html>

EDIT: I seems onclick is implemented using bind() ? Indeed, it seems we can remove the listener by using unbind() later.

That would explain why it doesn’t accept a str (and in my mind shouldn’t accept a str).

Note : In JS it is often considered unsafe to use onXXXX and is often preferred to use addEventListener() (bind() in Brython).

Indeed, the listener you add through onclick and be removed by other code trying to add their own listener through onclick. Using addEventListener() (bind() in Brython) enables to register many listeners (not just one), you can later remove with removeEventListener() (unbind() in Brython).

Imma test some stuff ^^.