Events

Besides the functions provided by Dom_html to register event handlers (mainly 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 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 occures.

Example:

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:

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:

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 API documentation for more information.