OClosure Library

OClosure logo

OClosure library is a binding of the Google Closure Javascript library in OCaml using Js_of_ocaml.

You can now write dynamic user interfaces for web pages in OCaml.

To find your way in the hundreds of class types, you may take a look at the API reference but you might also appreciate the Google Closure documentation.


To compile the library, you need:

  • Js_of_ocaml : generate Javascript code from OCaml bytecode

Hello world

1. First, write an OCaml program using OClosure objects:

open Js

let my_alert s =
  let dialog = jsnew Goog.Ui.dialog(Js.null, Js.null, Js.null) in
  dialog##setContent(Js.string s);
  dialog##setVisible(Js._true)

let onload evt =
  let click = Goog.Ui.ControlContent.string (Js.string "Click") in
  let button = jsnew Goog.Ui.button(click, Js.null, Js.null) in
  ignore
    (Goog.Events.listen
       (Goog.Tools.Union.i1 button)
       (Js.string "action")
       (Js.wrap_callback (fun _ -> my_alert "Hello world!"))
       Js.null);
  button##render(Js.some Dom_html.document##body);
  Js._true

let _ = Dom_html.window##onload <- Dom_html.handler onload

2. Compile it with OCaml to obtain an byte-code executable:

ocamlfind ocamlc -package oclosure,js_of_ocaml.syntax -syntax camlp4o -linkpkg test.ml -o test.byte

3. Generate the javascript program from the byte-code executable with the Js_of_ocaml compiler:

js_of_ocaml test.byte -pretty

4. Extract the fragment of the closure library required by your program:

oclosure_req test.js

5. You obtain a test.js and a test_oclosure.js file that you may include in your web page:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/dialog.css">
    <script type="text/javascript" src="test_oclosure.js"></script>
    <script type="text/javascript" src="test.js"></script>
    <title>Test OClosure</title>
  </head>
  <body>
  </body>
</html>

You may found the css in the google-closure/closure/goog/css directory from the the OClosure distribution.