22

How to call ClojureScript code from Javascript (not the other way around !).

It is already possible to call Clojure from Java, but I don't know how to do the equivalent in ClojureScript.

Community
  • 1
  • 1
nha
  • 17,623
  • 13
  • 87
  • 133

2 Answers2

31

Export the functions you want to have available in js by using ^:export, then simply call it as my.ns.fn()

cljs:

(ns hello-world.core)

(defn ^:export greet [] "Hello world!")

js:

hello_world.core.greet()

See the accepted answer to "Clojurescript interoperability with JavaScript" for detailed info.

Community
  • 1
  • 1
nberger
  • 3,659
  • 17
  • 19
8

Clojurescript compiles to Javascript so you can use it as is.

Datascript is a great source of inspiration to learn this, it is written in Clojurescript and is used via vanilla javascript javascript as is.

In pseudo code that gives:

<script src="https://github.com/tonsky/datascript/releases/download/0.11.6/datascript-0.11.6.min.js"></script>
...
...
var d = require('datascript');
// or 
// var d = datascript.js;

var db = d.empty_db();
var db1 = d.db_with(db, [[":db/add", 1, "name", "Ivan"],
                       [":db/add", 1, "age", 17]]);
var db2 = d.db_with(db1, [{":db/id": 2,
                        "name": "Igor",
                        "age": 35}]);

var q = '[:find ?n ?a :where [?e "name" ?n] [?e "age" ?a]]'; 
assert_eq_set([["Ivan", 17]], d.q(q, db1));
assert_eq_set([["Ivan", 17], ["Igor", 35]], d.q(q, db2));

You can see the interop section of this blog entry.

Lastly, go through the datascript javascript-based test suite.

Nicolas Modrzyk
  • 13,961
  • 2
  • 36
  • 40
  • Thank you that was useful, especially this: https://github.com/tonsky/datascript/blob/18ab268d4682f2ef0c75ce42548494726009f82f/src/datascript/js.cljs#L62 – nha Jul 27 '15 at 07:10