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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With