Search code examples
interopclojurescript

In ClojureScript, Set multiple properties of a javascript object at once


I am using doto to assign properties of a Dom element in ClojureScript, as below:

(let [img
          (doto (.createElement js/document "img")
            (set! -src "bunny-512.png")
            (set! -height 64)
            (set! -width 64))]
;...
)

Is there a way to do set all the properties at once via a map of properties+values instead?

Was thinking something like:

(let [img (.createElement js/document "img")]
  (set! img {:src "bunny-512.png" :height 64 :width 64})

But that does not work ...


Solution

  • Try something like this:

    (defn set-props [o property-map] 
      (doseq [[k v] property-map] 
        (.setAttribute o (name k) v)))
    

    Test:

    (def mg (.createElement js/document "img"))
    
    cljs.user=> (set-props mg {:src "foo.png" :height 128 :width 128})
    nil
    
    cljs.user=> (.-src mg)
    ".../foo.png"
    
    cljs.user=> (.-width mg)
    128
    
    cljs.user=> (.-height mg)
    128