如何在javascript中使用clojurescript中的复杂返回对象 [英] how to use a complex return object from clojurescript in javascript

查看:155
本文介绍了如何在javascript中使用clojurescript中的复杂返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个clojurescript函数,它返回一个复杂的项目,如[foobar]或(listfoobar),我希望能够从javascript中调用此函数并获取部分返回值。怎么做到呢?在我的情况下,我正在返回的vector / list / collection中的项目数量是预先知道的,并且该集合应保持有序。

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.

这是我的clojurescript函数。如果它让事情变得更容易,我可以在这里做些不同的事只是不知道会是什么。

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"])

以下是编译成javascript后的样子。该部分完全由前一位代码确定/生成。要在此处进行更改,我必须知道如何调整clojurescript中的上一部分。

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)
};

当我在javascript中执行以下操作时,我会看到一个警告框弹出[[foo bar]

When I do the following in javascript, I see an alert box pop up with ["foo" "bar"]

alert(my.ns.myFn());

但如果我尝试以下操作,警报会显示未定义而不是foo。

But if I try the following, the alert shows "undefined" instead of "foo".

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

我应该采取哪些不同的方式来获取显示foo的警报? (嗯。我想我可以写更多的clojurescript来使用这个值,看看在编译成javascript时会出现这种情况......)

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...)

推荐答案

in clojurescript:

in clojurescript:

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

在javascript中:

in javascript:

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

...使用 result_array 作为一个普通的javascript数组。

... use result_array as a normal javascript array.

这篇关于如何在javascript中使用clojurescript中的复杂返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆