English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

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: 2007-11-26 (18:33)
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 =
   type t
   external setAttribute : t -> string -> string -> unit = "#setAttribute"

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

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


Callback.register "changecolour" changecolour;

------ index.html

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

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

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



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).