I have a couple options, but both seem a bit laggy, and I'm thinking that there should be a better alternative. I just would like to be able to create forms, even dynamically create them (eg adding rows to a form from within my app), and have reagent/re-frame/react-appropriate access to the values of the different inputs.
Not sure if either of these are the best alternative though, since they both run functions after every :on-change
...
Option #1 - update :on-change
into the global atom
[:input {:value @new-job-form
:on-change #(dispatch [:new-job-form (-> % .-target .-value)])}]
(reg-event-db
:new-job-form
(fn [db [_ v]]
(assoc db :new-job-form v)))
Option #2 - update some local state, that only dispatches to the global atom :on-blur
(defn text-input
"adapted from:
https://yogthos.net/posts/2016-09-25-ReagentComponents.html
The big idea is this holds local state, and pushes it to the global
state only when necessary"
[{:keys [sub-path disp]}]
(r/with-let [value (r/atom nil)
focused? (r/atom false)]
[:div
[:input
{:type :text
:on-focus #(do (reset! value @(subscribe sub-path))
(reset! focused? true))
:on-blur #(do (dispatch (conj disp @value))
(reset! focused? false))
:value (if @focused? @value @(subscribe sub-path))
:on-change #(reset! value (-> % .-target .-value))}]]))
The second option is slightly less laggy, but more laggy than just a raw text input...
EDIT:
Option #3 - for completeness, a slightly different flavor adapted from re-frame's TODOMVC
(defn text-input
"adapted from re-frame's TODOMVC:
https://github.com/Day8/re-frame/blob/master/examples/todomvc/src/todomvc/views.cljs
note: this is one-way bound to the global atom, it doesn't subscribe to it"
[{:keys [on-save on-stop props]}]
(let [inner (r/atom "")]
(fn [] [:input (merge props
{:type "text"
:value @inner
:on-blur (on-save @inner)
:on-change #(reset! inner (-> % .-target .-value))
:on-key-down #(case (.-which %)
13 (on-save @inner) ; enter
27 (on-stop) ; esc
nil)})])))
[text-input {:on-save #(dispatch [:new-job-form {:path [:a]
:v %}])
:on-stop #(js/console.log "stopp")
:props {:placeholder "url"}}]