Trouble calling javascript function during app initialization

However, it will not work for me if its just called by itself:

anvil.call(this, 'submit_clicked', formData);

Ah, yes - That’s because Anvil doesn’t know which Form instance you’re talking about!

anvil.call() calls a method on the Python object representing your form. But you can have multiple forms, or multiple instances of the same form, visible on your page at once. How does it know which one to call?

The answer is the first parameter to anvil.call(). The first parameter must be a DOM node inside a form (eg a <div> inside your custom HTML). Anvil looks at all the parents of that DOM node, until it finds a form instance. Then it knows which Python object to call the method on!

In your first example (the one that works), you make a jQuery click handler. In a jQuery click handler, this is the DOM element that got clicked on. The element that got clicked on is inside your form, so anvil.call(this, ...) works perfectly!

However, in your second example, you’re calling anvil.call() on its own. For that line of code, “this” is something totally irrelevant like the Window object. Anvil can’t tell which form to invoke, so the call never happens.

(PS: I’ve added a TODO item to improve our error reporting when this happens.)