nha
nha

Reputation: 18005

call ClojureScript from Javascript

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.

Upvotes: 22

Views: 5678

Answers (2)

nberger
nberger

Reputation: 3659

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.

Upvotes: 32

Nicolas Modrzyk
Nicolas Modrzyk

Reputation: 14197

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.

Upvotes: 8

Related Questions