how to use a complex return object from clojurescript in javascript

喜夏-厌秋 提交于 2019-12-08 00:37:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!