How to pass a component to a javascript function?

Is there a way to pass a component to a javascript function in the form_show event?

I have tried with anvil.js.call_js('myFunction', self), but it didn’t like it at all.

In this post David suggests to add a div with a known ID and use jQuery to find it, but I was able to use this technique only with a custom html form.

How do I use other form templates, call javascript and get a Python call back?

What’s the goal here - what do you want to do with the component? The component itself is a Python object, so not directly manipulable from Javascript.

I am trying to manage keyboard events using the Mousetrap library as suggested by David here.

My goal is to have one keyboard event handler on the main form and one keyboard handler on any other form that might be either loaded on a container of the main form or on an alert. Each handler should process its keystrokes and leave the unprocessed ones bubbling up to the parent forms.

I found a way that allows a javascript function to identify a form: put an invisible label with a unique text inside a form, then use:

component = $('span:contains(' + uniqueText + ')')[0];
anvil.call(component, callbackName, keyInfo);

Unfortunately this trick works if the label is inside a form with the HTML property, but doesn’t work with templates without HTML property.

I think I am giving up, too many problems:

  • Javascript can only call methods of the main form
  • If the same keystroke is handled by two forms, the result is unpredictable (sometimes the parent’s event handler is executed, sometimes the child’s)
  • Difficult to know which component has the focus
  • Form methods executed from javascript can’t use the print function (not a big deal, just annoying)

I will go the less fancy way: use Mousetrap only from the main form and use some global status variable to keep track of where is the focus and tell MainForm.keypress what’s going on.

Any plan to add keyboard events?

Here is another reply to the same question with another use case: I created javascript functions getSelectionPosition(placeHolderText) and setSelectionPosition(placeHolderText, selStart, selEnd).

I used the placeholder property to identify the textbox. This is the definition of the function:

# Python
sel_start, sel_end = self.call_js('getSelectionPosition', 'unique text in the placeholder')

// javascript
function getSelectionPosition(placeHolderText) {
  element = $('[placeholder="' + placeHolderText + '"]');
  return [element.prop("selectionStart"), element.prop("selectionEnd")];
}

It would be nicer if I could do:

# Python
sel_start, sel_end = self.call_js('getSelectionPosition', self.tex_tbox_1)

// javascript
function getSelectionPosition(element) {
  return [element.prop("selectionStart"), element.prop("selectionEnd")];
}