问题
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