Skip to content

Instantly share code, notes, and snippets.

@mkrcah
Created January 28, 2025 15:07
Show Gist options
  • Save mkrcah/832dfd9b6db15cb6269e6f908254facf to your computer and use it in GitHub Desktop.
Save mkrcah/832dfd9b6db15cb6269e6f908254facf to your computer and use it in GitHub Desktop.
TomSelect + DataStar + Clojure
(ns web.components.select
(:require [hiccup2.core :as h]))
(defn globalInit []
[:script
{:type "text/javascript"}
(h/raw
"function initializeTomSelect(selector, options = {}) {
var input = document.querySelector(selector);
var value = input.value
var control = input.tomselect;
control && control.destroy();
control = new TomSelect(selector, options)
control && control.setValue(value);
}
function updateTomSelectFromSignal(selector, signalVal) {
var input = document.querySelector(selector);
var control = input.tomselect;
control && control.setValue(signalVal);
}
")])
(defn final-attrs [html-attrs]
(def html-attrs html-attrs)
(cond->
html-attrs
true
(assoc :data-on-load
(format "initializeTomSelect('#%s', {})" (:id html-attrs)))
(-> html-attrs :data-bind)
(assoc :data-on-signals-change
(format "updateTomSelectFromSignal('#%s', $%s)"
(:id html-attrs)
(-> html-attrs :data-bind)))))
(defn Select
":placeholder and :id html attrs are required"
[options html-attrs]
{:pre [(and (contains? html-attrs :id) "Required to initialize with js")]}
[:span
[:select (final-attrs html-attrs)
[:option {:value ""} (:placeholder html-attrs)]
(conj
(for [{:keys [text value]} options]
[:option {:value value} text])
[:option])]])
(comment
(Select [{:text "Trip 1" :value 1}
{:text "Trip 2" :value 2}]
{:id "select-a-trip"
:placeholder "Select a trip"
:data-bind "trip-id"}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment