简体   繁体   English

如何在javascript中使用clojurescript中的复杂返回对象

[英]how to use a complex return object from clojurescript in javascript

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. 我想编写一个clojurescript函数,该函数返回一个复杂的项目,例如[“ foo”“ bar”]或(列表“ foo”“ bar”),并且我希望能够从javascript调用此函数并获得返回值。 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. 这是我的clojurescript函数。 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. 这是编译为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. 要在此处进行更改,我必须知道如何调整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"] 当我在javascript中执行以下操作时,我看到一个带有[“ foo”“ bar”]的警报框

alert(my.ns.myFn());

But if I try the following, the alert shows "undefined" instead of "foo". 但是,如果我尝试以下操作,则警报显示“未定义”而不是“ foo”。

var tmp = my.ns.myFn();
alert(tmp[0]);

What should I do differently to get the alert to show "foo" ? 我应该怎样做才能使警报显示“ foo”? (Hmm. I guess I could write more clojurescript to use the value and see how that appears when compiled to javascript...) (嗯。我想我可以编写更多clojurescript来使用该值,并查看编译为javascript时的样子。)

in clojurescript: 在clojurescript中:

(ns foo.core) (defn ^:export bar [x] (array 0 1 2))

in javascript: 在javascript中:

var result_array = foo.core.bar(x);

... use result_array as a normal javascript array. ...将result_array用作普通的javascript数组。

So I wrote more clojurescript to use myFn and its return value. 因此,我编写了更多clojurescript以使用myFn及其返回值。 The generated javascript looks like this: 生成的javascript如下所示:

var tmp = my.ns.myFn.call(null);
var first = cljs.core.first.call(null, tmp);
var second = cljs.core.nth.call(null, tmp, 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM