Bob Fang
Bob Fang

Reputation: 7381

How can I add a onclick method using js_of_ocaml?

Hi suppose I have a button with id form-submit and I have the following function in my OCaml file:

let () =
   let form_submit = Dom_html.getElementById "form-submit" in
   ...

What is the right way to add a on_click method to the button? Should I just do something like this?

  form_submit##onclick <- ...

But whats the type of the handler function? I cannot find it in the documentation.

Upvotes: 4

Views: 548

Answers (1)

Drup
Drup

Reputation: 3739

You can use the dom stuff manually, but it's not very convenient. The right way is to use the Lwt_js_events modules that builds up abstraction over event handlers using Lwt.

Here is a minimal example:

Lwt.async (fun () ->
  Lwt_js_events.clicks form_submit
    (fun _ev _thread -> Lwt.return () )
  )

First parameter is the event object, second is the loop thread. You can tweak the behavior of the handler quite finely using the general construct at the beginning.

Lwt.async here ensure that the handler will be put in place "when it's good" (in this case, when the lwt scheduler is launched). It's better to use that than to ignore the result, as it ensures proper scheduling.

Upvotes: 5

Related Questions