Skip to content

Instantly share code, notes, and snippets.

@martinklepsch
Last active January 4, 2016 10:28
Show Gist options
  • Save martinklepsch/8608540 to your computer and use it in GitHub Desktop.
Save martinklepsch/8608540 to your computer and use it in GitHub Desktop.
(ns chaf2.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[cljs.core.async :refer [put! chan]]))
(enable-console-print!)
(defn log [obj]
(.log js/console (pr-str obj)))
(def app-state
(atom
{:contacts
[{:first "Ben" :last "Bitdiddle" :email "[email protected]"}
{:first "Alyssa" :middle-initial "P" :last "Hacker" :email "[email protected]"}
{:first "Eva" :middle "Lu" :last "Ator" :email "[email protected]"}
{:first "Louis" :last "Reasoner" :email "[email protected]"}
{:first "Cy" :middle-initial "D" :last "Effect" :email "[email protected]"}
{:first "Lem" :middle-initial "E" :last "Tweakit" :email "[email protected]"}]}))
(def test-contact {:first "Arnold" :middle "Bert" :last "Schwarzenegger" :email "[email protected]"})
(defn middle-name [{:keys [middle middle-initial]}]
(cond
middle (str " " middle)
middle-initial (str " " middle-initial ".")))
(defn display-name [{:keys [first last] :as contact}]
(str last ", " first (middle-name contact)))
(defn contact-form [app owner]
(reify
om/IRenderState
(render-state [this {:keys [add]}]
(dom/input #js {:value "add contact here"})
(dom/button #js {:onClick (fn [e] (put! add test-contact))} "Add contact"))))
(defn contact-view [contact owner]
(reify
om/IRenderState
(render-state [this {:keys [delete]}]
(dom/li nil
(dom/span nil (display-name contact))
(dom/button #js {:onClick (fn [e] (put! delete @contact))} "Delete")))))
(defn contacts-view [app owner]
(reify
om/IInitState
(init-state [_]
{:delete (chan)})
om/IWillMount
(will-mount [_]
(let [delete (om/get-state owner :delete)]
(go (loop []
(let [contact (<! delete)]
(om/transact! app :contacts
(fn [xs] (into [] (remove #(= contact %) xs))))
(recur))))))
om/IRenderState
(render-state [this {:keys [delete]}]
(dom/div nil
(dom/h1 nil "Contact list")
(apply dom/ul nil
(om/build-all contact-view (:contacts app)
{:init-state {:delete delete}}))
(om/build contact-form app)))))
(om/root app-state contacts-view (. js/document (getElementById "contacts")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment