Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 866
nha Avatar asked Jul 26 '15 19:07

nha


2 Answers

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.

like image 97
nberger Avatar answered Nov 18 '22 00:11

nberger


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.

like image 43
Nicolas Modrzyk Avatar answered Nov 17 '22 23:11

Nicolas Modrzyk