Skip to content

Instantly share code, notes, and snippets.

@frou
Forked from dwest/DOMStringMap IEncodeClojure
Last active November 29, 2022 14:29
Show Gist options
  • Save frou/f860a0b1d701d179e9c66e4f23f2a6db to your computer and use it in GitHub Desktop.
Save frou/f860a0b1d701d179e9c66e4f23f2a6db to your computer and use it in GitHub Desktop.
Convert a HTMLElement's dataset property into a ClojureScript map
;; DOMStringMap is the type of `HTMLElement.dataset` and contains the element's `data-*` attributes.
;; Implement the protocol used by the `cljs.core/js->clj` function.
(extend-type js/DOMStringMap
IEncodeClojure
(-js->clj [x {:keys [keywordize-keys]}]
(let [keyfn (if keywordize-keys keyword identity)]
(->> (.entries js/Object x)
(reduce
(fn [m [k v]] (assoc m (keyfn k) v))
{})))))
;; Example uses:
(def some-element (.querySelector js/document "#foo"))
(js->clj (.-dataset some-element))
(js->clj (.-dataset some-element) :keywordize-keys true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment