10

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?

3 Answers 3

13

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Awesome. Relatively quick way to do this using a map: (apply js-obj (apply concat (seq map))))
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.