Skip to content

Instantly share code, notes, and snippets.

@roryhow
Last active June 16, 2022 05:12
Show Gist options
  • Save roryhow/a700a79e1420c6a2b450f250abda9448 to your computer and use it in GitHub Desktop.
Save roryhow/a700a79e1420c6a2b450f250abda9448 to your computer and use it in GitHub Desktop.
;; Here we are importing re-frame.core (our SPA library and referring to it as rf for brevity)
(ns simple.core
(:require [re-frame.core :as rf]
[clojure.string :as str]))
;; Event Handler
(rf/reg-event-db ;; By calling the reg-event-db function we can register an event handler
:change-checkbox ;; for when the :change-checkbox event is dispatched
(fn [db [_ new-value]] ;; we then supply a function that takes the db and an event vector as 2 the 2 parameters
(assoc db :is-checked new-value))) ;; we update the DB map (think similar to a JS object) :is-checked value to the new value and return
;; Query
(rf/reg-sub ;; We register a subscription with the following key and function
:is-checked ;; The key is for what subscription we want to listen for
(fn [db _] ;; we supply a function that takes the DB atom as a parameter
(:is-checked db))) ;; We get the value stored from the :is-checked key
;; View (including dispatch)
(defn checkbox-input ;; Define a function
[] ;; that takes no parameters
(let [is-checked (rf/subscribe [:is-checked])] ;; create a variable that stores the atom from the subscription to :is-checked
[:div.checkbox ;; return a vector of keys and values, that gets evalutated to HTML (think how JSX is to HTML... but better)
"Checkbox button is: " (str @is-checked) ;; Dereference the atom and pull the value of the checkbox
[:div ;; Nested div
"Change input: "
[:input {:type "checkbox" ;; define an input -> <input type="checkbox" value={is-checked} on-change={() => dispatch(...) />
:value @is-checked
;; We supply a function to on-change that calls dispatch with a vector containing the dispatch key and the new value
:on-change #(rf/dispatch [:change-checkbox (not @is-checked)])}]]]))
@yellowbean
Copy link

yellowbean commented Jun 16, 2022

this will also helps

(rf/dispatch [    (.. % -target -checked)])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment