ocamljs-of-ocaml

Check if a field exists in an object in js_of_ocaml


In my wrap.ml, I have a function as follows:

  Js.Unsafe.global##.test := Js.wrap_callback (
    fun params -> 
      print_endline "params##.a:";
      print_endline (Js.to_string params##.a);
      print_endline "params##.b:";
      print_endline (Js.to_string params##.b);
      Js.string ((Js.to_string params##.a) ^ (Js.to_string params##.b))
  );

As a result, in a JavaScript file, I could call e.g., test({a: "abc", b:"efg"}).

I would like to know in the OCaml file, is there a way to check if the field b exists in the object params, before evaluating Js.to_string params##.b?


Solution

  • You can see how to do this at the bottom of this page:

    https://ocsigen.org/js_of_ocaml/latest/manual/bindings

    For this code:

    let () =
        if Js.Optdef.test ((Js.Unsafe.coerce Dom_html.document)##.URL) then
            Printf.printf "document.URL exists\n"
        else
            Printf.printf "document.URL does not exist\n";
        if Js.Optdef.test ((Js.Unsafe.coerce Dom_html.document)##.XXX) then
            Printf.printf "document.XXX exists\n"
        else
            Printf.printf "document.XXX does not exist\n";
    

    I see the following on the Javascript console:

    document.URL exists
    document.XXX does not exist