问题
I want to write a clojurescript function that returns a complex item like ["foo" "bar"] or (list "foo" "bar") and I want to be able to call this function from javascript and get at the parts of the return value. How can it be done? In my case, the number of items in the vector/list/collection that I'm returning is known beforehand, and the collection should remain ordered.
Here's my clojurescript function. I could do something differently here if it made things easier. Just don't know what that would be.
(defn myFn [] ["foo" "bar"])
Here's what it looks like after it has been compiled to javascript. This part is completely determined/generated by the previous bit of code. To make changes here, I'd have to know how to tweak the previous part in clojurescript.
my.ns.myFn = function myFn() {
return cljs.core.PersistentVector.fromArray(["foo", "bar"], true)
};
When I do the following in javascript, I see an alert box pop up with ["foo" "bar"]
alert(my.ns.myFn());
But if I try the following, the alert shows "undefined" instead of "foo".
var tmp = my.ns.myFn();
alert(tmp[0]);
What should I do differently to get the alert to show "foo" ? (Hmm. I guess I could write more clojurescript to use the value and see how that appears when compiled to javascript...)
回答1:
in clojurescript:
(ns foo.core)
(defn ^:export bar [x] (array 0 1 2))
in javascript:
var result_array = foo.core.bar(x);
... use result_array
as a normal javascript array.
回答2:
So I wrote more clojurescript to use myFn and its return value. The generated javascript looks like this:
var tmp = my.ns.myFn.call(null);
var first = cljs.core.first.call(null, tmp);
var second = cljs.core.nth.call(null, tmp, 1);
来源:https://stackoverflow.com/questions/12358954/how-to-use-a-complex-return-object-from-clojurescript-in-javascript