external. Put the external functions in a file
foo.js, and add
function at the beginning of the line is included.
You can also use special
|function call for builtin function, not checked against primitives|
The object-related prefixes expect the object as the first argument. For example, if you declare
external foo : bar -> unit = "#foo" and call
foo b, that compiles to
Finally, there are several special
|symbol||expects args||compiles to|
|alist of ids and exps||object literal|
Identifiers are given as strings. The
$new id symbol uses the native name argument to external, e.g.
external "$new" "Foo" : unit ->
src/jscomp/jsgen.ml to see exactly what these do.
Most of these are available in the Ocamljs library, or you can declare them yourself with
external (sometimes that’s more convenient if you want more accurate types).
document#getElementById "foo" becomes
document.getElementById("foo"). You can also access the properties of an object with specially-named methods, e.g.
style#_set_background "#ffffff" become
style.background = "#ffffff".
There are some other special cases: a leading underscore is dropped so you can use capitalized method names (e.g.
obj#_QueryInterface); a trailing underscore or
canvas#createPattern_canvas_ both become
canvas.createPattern); you can use either of these to deal with reserved words (e.g.
To get these uses to typecheck, of course, you need to operate on an object of the appropriate type. It’s easiest to write down an interface as a
Dom.document#getElementById) and ascribe the type. See the Dom and Mozilla libraries for examples.
A final caveat is that partial application does not work for native methods; a partial application causes an immediate call to the method with the arguments you provide. (Partial application does work for functions called via
external, because the OCaml compiler wraps an OCaml function around them.)
_get_foo to generate a property
jslib.inline package, then open
Ocamljs.Inline to get the AST types. To get an inline expression use an
<:exp< >> or
<< >> quotation; for an inline statment use
<:stmt< >>. You can use antiquotations to refer to OCaml expressions. For example:
let concat s1 s2 = << $s1$ + $s2$ >>
There is no typechecking of quotations and antiquotations. You can see some other examples in
src/stdlib. Caveat: the Jslib parser is incomplete.
Dom.window#setTimeout takes a
(unit -> unit).
You can use the usual
ocamljs program exports a function
ocamljs$caml_named_value which you can use to look up registered values. You can also get access to OCaml values by stashing them in a global from inline code.
Ocamljs.is_null before using a value that might be null.