Version française
Home     About     Download     Resources     Contact us    
Browse thread
Re: Simple ocamljs example
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jake Donham <jake.donham@s...>
Subject: Re: Simple ocamljs example
Peter Gregory wrote:
> I've been trying to work through a very simple example just to try out 
> ocamljs.  Simply, I want to provide a function that changes the colour 
> of some text.

OK, there is no reason in principle that this shouldn't work but I 
should warn you that so far I have only used OCamljs for a Firefox 
extension, not for web pages.

> I expected that if I had function named f in the ocaml side then I would 
> be able to call it with f() in the JS side.

Not quite; names are mangled, values are wrapped up in modules, and the 
calling convention is different (to account for currying), so you should 
use the same mechanism you'd use for calling C code: on the ML side, 
register a value with Callback.register; and on the Javascript side, use 
caml_named_value to look up a registered value and caml_callback{,2,3,N} 
to call through the value. Sorry, I forgot to write this up in the docs.

> I also assumed that Mozilla.Document.d was the document.
> [...] Document.d  [... becomes ...] (oc$Mozilla$[29][0])

If you look back to the definitions of oc$Mozilla (and Document$553 or 
whatever it is called for you) you'll see that this boils down to 
"document" as you wanted. Modules are compiled as Javascript arrays 
containing their values.

There is one more problem: the Mozilla module tries to get references to 
a bunch of XPCOM interfaces and classes when it starts up, and this 
fails in an ordinary browser environment. Here is a version of your 
example that works for me (in Linux Firefox), not using the Mozilla module:

------ ocajs.ml

module Element =
struct
   type t
   external setAttribute : t -> string -> string -> unit = "#setAttribute"
end

module Document =
struct
   type t
   let (d : t) = Ocamljs.var "document"
   external getElementById : t -> string -> Element.t = "#getElementById"
end


let changecolour () =
   let e = Document.getElementById Document.d "myid" in
   Element.setAttribute e "color" "red"

;;

Callback.register "changecolour" changecolour;

------ index.html

<html>
<script type="text/javascript" src="ocajs.js"></script>
<body>

<p><font id="myid" color="blue"> HELLO WORLD </font></p>

<form>
<input type="button" value="Change Colour" 
onclick='caml_callback(caml_named_value("changecolour"), 0)'>
</form>

</body>
</html>

------

The 0 argument in caml_callback is the Javascript representation of the 
empty tuple (but for unit arguments it doesn't matter what you pass 
since they are never looked at).

Jake