Skip to content

Instantly share code, notes, and snippets.

@joshfrench
Created November 17, 2015 16:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshfrench/3c83bc0f40348dfd528b to your computer and use it in GitHub Desktop.
Save joshfrench/3c83bc0f40348dfd528b to your computer and use it in GitHub Desktop.
(ns om-tutorial.core
(:require [goog.dom :as gdom]
[om.next :as om :refer-macros [defui]]
[om.dom :as dom]))
(enable-console-print!)
(def init-data
{:dashboard/items
[{:id 0
:type :post
:title "Ohai"}]})
(defui Post
static om/IQuery
(query [this]
[:id :type :title]))
(def post (om/factory Post))
(defui DashboardItem
static om/Ident
(ident [this {:keys [id type]}]
[type id])
static om/IQuery
(query [this]
{:post (om/get-query Post)}))
(def dashboard-item (om/factory DashboardItem))
(defui Dashboard
static om/IQuery
(query [this]
[{:dashboard/items (om/get-query DashboardItem)}]))
(defmulti read om/dispatch)
(defmethod read :dashboard/items
[{:keys [state query]} k _]
(let [st @state]
{:value (om/db->tree query (get-in st k) st)}))
(defmulti mutate om/dispatch)
(defmethod mutate 'item/add
[{:keys [state]} k {:keys [id type] :as params}]
(let [ident [type id]]
{:action (fn [] (swap! state (fn [st]
(-> st
(assoc-in ident params)
(update :dashboard/items conj ident)))))
:remote true}))
(defn api
[remotes cb]
(cb {'item/add {:tempids {[:post -1] [:post 99]}}}))
(def reconciler
(om/reconciler
{:state init-data
:parser (om/parser {:read read :mutate mutate})
:send api
:id-key :id}))
(om/add-root! reconciler Dashboard (gdom/getElement "app"))
(comment
(om/transact! reconciler '[(item/add {:id -1 :type :post :content "..."})])
(println @reconciler) ;; => {:dashboard/items [[nil nil] [nil nil]], nil {nil {}}, :om.next/tables #{nil}}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment