简体   繁体   English

如何调用js_of_ocaml生成的函数?

[英]How to invoke a function generated by js_of_ocaml?

I am new to JavaScript, I am trying to use js_of_ocaml . 我是JavaScript的新手,我正在尝试使用js_of_ocaml

I first wrote a very simple cubes.ml : 我先写了一个非常简单的cubes.ml

let simple (a: int) =
  a + 1234

Then complied it: 然后遵守它:

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

then generated the JavaScript file: 然后生成JavaScript文件:

js_of_ocaml cubes.byte

Here is the generated cubes.js . 这是生成的cubes.js Note that we could not find 1234 or function name simple in that file. 需要注意的是,我们无法找到1234或函数的名称simple在该文件中。

I have another JavaScript file Home.js , where I want the function callSimple to call what was generated in cubes.js . 我有另一个JavaScript文件Home.js ,我希望函数callSimple调用在cubes.js中生成的cubes.js But I don't know how to write it. 但我不知道如何写它。 Could anyone help? 有人可以帮忙吗?

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

Edit 1: 编辑1:

I tried the solution proposed by @EdgarAroutiounian : 我尝试了@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 did compile, but it did not return the right output: 它确实编译了,但它没有返回正确的输出: 在此输入图像描述

If I write in home.js : 如果我在home.js写:

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

the first line returns function (a){return p(c,aM(b,a))} , and the second line returns 0 . 第一行返回function (a){return p(c,aM(b,a))} ,第二行返回0 They are not what I expect. 它们不是我所期望的。

Here's one possible way to do it. 这是一种可行的方法。

In our OCaml code intended to be exposed to JavaScript: 在我们旨在暴露给JavaScript的OCaml代码中:

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)

Notice that I'm using the ppx extension, I recommend you do so as well: this means no more camlp4 . 请注意,我正在使用ppx扩展名,我建议您也这样做:这意味着不再使用camlp4 You can compile that code with: 您可以使用以下代码编译该代码

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

Then in your other file, home.js 然后在你的另一个文件home.js

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

and an index.html of: index.html

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

And that should work. 那应该有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM