Created
August 26, 2018 14:44
-
-
Save sveitser/861de594a827be0c27c07a1ef1a9030c to your computer and use it in GitHub Desktop.
cljs shopping cart example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns cart.main | |
(:require [reagent.core :as reagent] | |
[re-frame.core :as rf] | |
[clojure.string :as str])) | |
;; -- Domino 1 - Event Dispatch ----------------------------------------------- | |
(defn dispatch-add-to-cart | |
[item] | |
(rf/dispatch [:add-to-cart item])) | |
;; -- Domino 2 - Event Handlers ----------------------------------------------- | |
(rf/reg-event-db | |
:initialize | |
(fn [db _] | |
;; XXX to keep the state for figwheel.main reloads, is there a better way? | |
(or db {:cart {}}))) | |
(rf/reg-event-db | |
:add-to-cart | |
(fn [db [_ item]] | |
(let [new-val (inc (or (item (:cart db)) 0))] | |
(assoc-in db [:cart item] new-val)))) | |
;; -- Domino 4 - Query ------------------------------------------------------- | |
(rf/reg-sub | |
:cart | |
(fn [db _] | |
(:cart db))) | |
;; -- Domino 5 - View Functions ---------------------------------------------- | |
(defn cart [] | |
[:table [:thead [:tr [:th {:colSpan 2} "Cart"]]] | |
[:tbody (map (fn [[item count]] | |
^{:key item} [:tr [:td item] [:td count]]) | |
(sort @(rf/subscribe [:cart])))]]) | |
(defn mk-shop-item [kind] | |
^{:key kind} | |
[:tr [:td kind] | |
[:td [:input.btn {:type "button" :value "buy" | |
:on-click #(dispatch-add-to-cart (keyword kind))}]]]) | |
(defn items [] | |
[:table | |
[:thead [:tr [:th {:colSpan 2} "Items"]]] | |
[:tbody (map mk-shop-item ["apple" "banana" "orange", "kiwi"])]]) | |
(defn cart-and-items [] | |
[:table [:tbody [:tr [:td (items)] [:td (cart)]]]]) | |
(defn ui | |
[] | |
[:div | |
[:h1 "Not Silkroad"] | |
[cart-and-items]]) | |
;; -- Entry Point ------------------------------------------------------------- | |
(defn ^:export run | |
[] | |
(rf/dispatch-sync [:initialize]) | |
(reagent/render [ui] | |
(js/document.getElementById "app"))) | |
(run) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment