Getting current component event_handler

Hi,

The set_event_handler the documentation provides a mechanism to assign a function to the component event_handler. Is it possible to get retrieve that event_handler? (i.e. get_event_handler)? I’ve run dir on my component and it’s not clear to me if or how that event_handler function is related to the component object.

What I’m trying to do:
I have a button that responds to some click event, generated using the short-cut from the Designer pane and called my_button_click. I want to do something else in addition to that behavior. For example, say I wanted to record that button was clicked, so I had some other function, on_click, that printed the fact that that button was clicked. I’d like to be able to assign that second handler to the button, for example:

def assign_second_handler(component, event, new_event_handler):
    fns = [component.get_event_handler, new_event_handler]
    def on_event(**event_args):
        for f in fns:
            f(**event_args)

    component.set_event_handler(event, on_event)

and in the init:

class Form1(Form1Template):
    def __init__(self, **properties):
        assign_second_handler(self.button_1, 'click', on_click)

Here’s a clone of an example:
https://anvil.works/build#clone:O7UOQYRIGGWHF6BD=WMN5IUBQ5BFMN5RTWKKLIW4P

I recognize that I could just add the second function call in the handler. This is just a contrived example, and in the situation I’m actually dealing with that is not possible.

Thanks,

Dan

Have you considered using a decorator to decorate the handler?

def assign_handlers(*handlers):
  def wrapper(fn):
      def wrapped_handler(self, **event_args):
        fn(self, **event_args)
        for handler in handlers:
          handler(**event_args)
      wrapped_handler.__name__ = fn.__name__
      return wrapped_handler
  return wrapper


And then your function would look like

  @assign_handlers(do_first_thing, on_click)
  def button_1_click(self, **event_args):
    """This method is called when the button is clicked"""
    alert("HI!", dismissible=True)

https://anvil.works/build#clone:LPVDIZMYG2NF45AX=SY6XX3HA5CQONC52GZVSPAGY

1 Like

If anyone ends up here: Anvil implemented an add_event_handler method, which allows for adding a function to an event handler without over-writing the behavior designed in the editor. Exactly what I was looking for originally…

See (and seach for add_event_handler):
https://anvil.works/docs/client/components#events

4 Likes