dioxus icon indicating copy to clipboard operation
dioxus copied to clipboard

Registering custom events

Open CyberDomovoy opened this issue 2 years ago • 2 comments

Specific Demand

An easy way to add events to Dioxus without the need to mess with the source code.

Implement Suggestion

Something that would allow a usage like, for example:

register_event! {
  // attribute name
  onmyevent;
  // setup structure
  MyeventHandler;
  // elements on which it can be set
  div
  p
  header
}

struct MyeventHandler {
  ...
}

impl MyeventHandler {
  // Setup the event (create needed structures, hooks...)
  // should be called when dioxus starts
  fn new() -> Self {
    ...
  }

  // Connect a callback
  fn connect(element, callback) -> Result<...> {
    ...
  }

  // Disconnect a callback
  fn disconnect(element) -> Result<...> {
    ...
  }
}

fn App(cx: Scope) -> Element {
  render! {
    div {
      onmyevent: |event| {
        ...
      }
  }
}

CyberDomovoy avatar Aug 13 '23 02:08 CyberDomovoy

I have some web components that I integrate and this would be super helpful!

cawfeecoder avatar Dec 29 '23 07:12 cawfeecoder

This structure isn't compatible with how dioxus handles events currently. Dioxus uses a synthetic event system in javascript that attaches bubbling listeners to the root element and non-bubbling listeners to the element the listener is added to in rsx. Event handling happens in javascript because there is no rust code running on the client on some platforms like dioxus-liveview.

It would be much easier to allow custom event listeners like this with a set number of parameters we can pass off to some javascript code:

register_event! {
  // attribute name
  event: onmyevent;
  // Event Name
  js-event: "my-event";
  // Bubbles
  bubbles: false,
  // elements on which it can be set
  elements: [div, p, header]
}

fn App(cx: Scope) -> Element {
  render! {
    div {
      onmyevent: |event| {
        ...
      }
  }
}

ealmloff avatar Dec 29 '23 14:12 ealmloff