How to call the function generated by js_of_ocaml?

I am new to JavaScript, I am trying to use js_of_ocaml.

At first, I wrote a very simple one cubes.ml:

let simple (a: int) =
  a + 1234

Then executed this:

ocamlfind ocamlc -package js_of_ocaml -package js_of_ocaml.syntax \
          -syntax camlp4o -linkpkg -o cubes.byte cubes.ml

then generated a JavaScript file:

js_of_ocaml cubes.byte

Here is the generated cubes.js . Please note that we could not find 1234or function name simplein this file.

I have another javascript file Home.jswhere I want the function to callSimplecall what was created in cubes.js. But I do not know how to write it. Can anyone help?

(function () {
    ...
    function callSimple(a) {
        return ???;
    };
    ...
})();

Change 1:

I tried the solution suggested by @EdgarAroutiounian:

(* cubes.ml *)
let () =
  Js.Unsafe.global##.jscode := (object%js
    val simple = Js.wrap_meth_callback
        (fun a -> a + 1234)
    val speak = Js.wrap_meth_callback
        (fun () -> print_endline "hello")
  end)

It compiled, but did not return the correct result: enter image description here

If I write to Home.js:

confirm(jscode.simple(10)); // 1244 is expected
confirm(jscode.speak()); // "hello" as string is expected

function (a){return p(c,aM(b,a))}, 0. , .

+4
1

.

OCaml, JavaScript:

let () =
  Js.Unsafe.global##.jscode := (object%js
    val simple = Js.wrap_meth_callback
        (fun a -> a + 1234)
    val speak = Js.wrap_meth_callback
        (fun () -> print_endline "hello")
  end)

, ppx, : camlp4. :

ocamlfind ocamlc -package js_of_ocaml.ppx -linkpkg cubes.ml -o T
js_of_ocaml T -o cubes.js

home.js

console.log(jscode.simple(10));
console.log(jscode.speak());

index.html of:

<!DOCTYPE html>
<meta charset="utf-8">
<body>
  <script src="cubes.js"></script>
  <script src="home.js"></script>
</body>

.

+4

All Articles