Clojurescript: converting cljs map to a javascript hash

北战南征 提交于 2019-12-10 12:39:33

问题


The following code snippet does not work

     headerElement (goog.dom/createDom
                    "div" (.strobj {"style" "background-color:#EEE"})
                    (:title note))

Reason:

{ ... } creates a Clojurescript map. I need a javascript object/hash.

Question:

How do I make this trivial conversion?


回答1:


cljs.core/js-obj should help for this. Please notice that it takes normal array/list in (not a map).

headerElement (goog.dom/createDom
               "div" (js-obj "style" "background-color:#EEE")
               (:title note))



回答2:


You can also use #js reader literal to create JavaScript object or array.

You can write:

(def test1 #js {:foo 1 :bar false})

which creates JavaScript code:

namespace.test1 = {"bar":false, "foo":1};

For array:

(def test2 #js [1 2 3 false nil true])

creates:

namespace.test2 = [1, 2, 3, false, null, true];

You can also use clj->js function:

(clj->js :style "background-color:#EEE")

the nice thing about it is that it works recursively - converting nested data structures.

I made a post about it (if I can advertise myself)




回答3:


This macro will let you use js-obj with keywords:

Macro

(defmacro obj [& key-values]
(let [obj-def (apply concat (map #(list (name (first %)) (last %))
     (partition 2 key-values)))]
    `(cljs.core/js-obj ~@obj-def)
))

Usage

(obj 
    :key someVal
    :otherKey (fn [a b] a)
)


来源:https://stackoverflow.com/questions/11037755/clojurescript-converting-cljs-map-to-a-javascript-hash

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