I can't understand some notions in js_of_ocaml

Hi everyone
Can you explain me something in js_of_ocaml:
Js._true
CoerceTo

Thank you in advance.

Hi,

OCaml Booleans are not the same thing as JavaScript Booleans (represented by the type bool Js.t). Js._true is the JS version of true and differs from standard OCaml true. You can use Js._true for interacting with the JS world where JS Booleans are expected and standard bool values for mostly everything else.

You can use Dom_html.CoerceTo to convert a “general” HTML element to a specific kind of element. For example, Dom_html.CoerceTo.a elt will convert elt to an a, thus permitting you to call methods that are specific to a's and not available for other kinds of HTML DOM nodes. The result is wrapped in a Js.opt (analogous to standard OCaml options) and you thus need to use Js.Opt to see if the conversion is possible and obtain the value.

1 Like

Hi, Thanks a lot.
Can you give me some examples about Js._true?

Consider a checkbox <input>:

let checkbox : Dom_html.inputElement Js.t =
  Tyxml_js.To_dom.of_input @@
  Tyxml_js.Html.input ~a:[Tyxml_js.Html.a_input_type `Checkbox] ()

To programatically check it, we can do

let check_checkbox () = checkbox##.checked := Js._true

checkbox##.checked := true wouldn’t work, because the DOM property ##.checked expects a JS Boolean and not a standard OCaml one.

Similarly, DOM nodes frequently have methods that expect JS Booleans:

let checkbox_into_view () = checkbox##scrollIntoView(Js._true)

or if you have the Boolean value available as a standard OCaml bool, you can convert via Js.bool:

let checkbox_into_view' (b : bool) =
  let b' : bool Js.t = Js.bool b in
  checkbox##scrollIntoView(b')
1 Like

Thank you very much,now I understand

1 Like