1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
== Events ==
Besides the functions provided by {{{Dom_html}}} to register event handlers
(mainly <<a_api subproject="js_of_ocaml"|val Js_of_ocaml.Dom_html.addEventListener>>)
using the usual Javascript way, js_of_ocaml provides another module to
program event handlers very easily and concisely, in the module
<<a_api subproject="js_of_ocaml-lwt"|module Js_of_ocaml_lwt.Lwt_js_events>>.
This module defines functions you can call on a DOM element to create
an Lwt thread that will return when the event occurs.
Example:
<<code language="ocaml"|
Lwt.ignore_result (Lwt_js_events.click target ~>>= handler);
>>
The handler receives the JS event as parameter.
Each of these functions has a version (same name with an ending "s")
that loops when the handler terminates. Example:
<<code language="ocaml"|
Lwt.ignore_result (Lwt_js_events.clicks target handler);
>>
To remove an event handler, cancel the Lwt threads using {{{Lwt.cancel}}}.
It is also possible to use {{{Lwt.pick}}}.
For example the following piece of code waits
for a click on one of t1 or t2:
<<code language="ocaml"|
Lwt.pick [Lwt_js_events.click t1 ~>>= handler1;
Lwt_js_events.click t2 ~>>= handler2]
>>
Warning: If you are using {{{Lwt.pick}}} and your handlers take time,
be aware that other events listeners will not be cancelled
before the handler has terminated. It is probably a better idea
to return immediately after having launched the long handlers.
Look at the <<a_api subproject="js_of_ocaml-lwt"|module Js_of_ocaml_lwt.Lwt_js_events>>
for more information.
|