简体   繁体   English

如何使用js_of_ocaml添加onclick方法?

[英]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: 嗨,假设我有一个id为form-submit的按钮,我的OCaml文件中有以下功能:

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

What is the right way to add a on_click method to the button? 向按钮添加on_click方法的正确方法是什么? 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. 我在文档中找不到它。

You can use the dom stuff manually, but it's not very convenient. 你可以手动使用dom东西,但这不是很方便。 The right way is to use the Lwt_js_events modules that builds up abstraction over event handlers using Lwt. 正确的方法是使用Lwt_js_events模块,使用Lwt_js_events构建对事件处理程序的抽象。

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). 这里的Lwt.async确保处理程序将在“好的时候”放置到位(在这种情况下,启动lwt调度程序时)。 It's better to use that than to ignore the result, as it ensures proper scheduling. 使用它比忽略结果更好,因为它可以确保正确的调度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM