Skip to content

Instantly share code, notes, and snippets.

@snichme
Created January 12, 2016 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snichme/bad850bdbd33f6cd3a81 to your computer and use it in GitHub Desktop.
Save snichme/bad850bdbd33f6cd3a81 to your computer and use it in GitHub Desktop.
(ns om-tutorial.mini
(:require [goog.dom :as gdom]
[om.next :as om :refer-macros [defui]]
[om.dom :as dom]))
(enable-console-print!)
(def init-data
{:cards [{:id 1 :title "Title 1"}
{:id 2 :title "Title 2"}
{:id 3 :title "Title 3"}]})
(defmulti read om/dispatch)
(defmethod read :default
[{:keys [state query]} key _]
(let [st @state]
{:value (om/db->tree query (get st key) st)}))
(defmethod read :card/by-id
[{:keys [state query-root query]} _ _]
(let [st @state]
{:value (om/db->tree query (get-in st query-root) st)}))
(def parser (om/parser {:read read}))
(def reconciler (om/reconciler {:state init-data
:parser parser}))
(defui Card
static om/Ident
(ident [_ {:keys [id]}]
[:card/by-id id])
static om/IQuery
(query [_]
`[:id :title])
Object
(render [this]
(let [{:keys [id title]} (om/props this)
on-click (-> this om/get-computed :on-click)]
(dom/div nil
(if (nil? on-click)
(dom/h5 nil (str id "-" title))
(dom/a #js {:href "#"
:onClick #(on-click id)} (str id "-" title)))))))
(def card (om/factory Card {:key-fn :id}))
(defui RootView
static om/IQueryParams
(params [_]
{:card-id 1})
static om/IQuery
(query [_]
(let [card-fields (om/get-query Card)]
`[{[:card/by-id ?card-id] ~card-fields}
{:cards ~card-fields}
]))
Object
(render [this]
(let [{:keys [cards] :as props} (om/props this)
params (om/get-params this)
key [:card/by-id (:card-id params)]]
(dom/div nil
(dom/h3 nil "Card by id")
(card (get props key))
(dom/h3 nil "List of cards")
(map #(card (om/computed % {:on-click (fn [id] (om/set-query! this {:params {:card-id id}}))})) cards)))))
(om/add-root! reconciler RootView (gdom/getElement "app"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment