Skip to content

Instantly share code, notes, and snippets.

@ThomasDeutsch
Created October 25, 2015 13:47
Show Gist options
  • Save ThomasDeutsch/c8b0226de255b6b884d3 to your computer and use it in GitHub Desktop.
Save ThomasDeutsch/c8b0226de255b6b884d3 to your computer and use it in GitHub Desktop.
(ns scheduler.main.core
(:require [goog.dom :as gdom]
[om.next :as om :refer-macros [defui]]
[om.dom :as dom]
[datascript.core :as d]))
(enable-console-print!)
;; TASK:
;; render ItemOne <OR> ItemTwo, based on the ":selected" ref of entity 0
(def schema {:selected {:db/valueType :db.type/ref}})
(def conn (d/create-conn schema))
(d/transact! conn
[{:db/id -1
:type :one
:item-one/title "ITEM 1"}
{:db/id -2
:type :two
:item-two/title "ITEM 2"}
{:db/id 0
:selected -2}])
(defmulti read om/dispatch)
(defmethod read :selected-item [{:keys [state selector]} _ _]
(println "selector: " selector)
(let [x (map (fn [[k v]]
(->> (d/pull @state [{:selected v}] 0)
(:selected))) selector)]
(println "read result: " (into {} x))
{:value (into {} x)}))
(defmulti mutate om/dispatch)
(defmethod mutate 'app/item-switch [{:keys [state]} _ {new-id :prop}]
{:value [:selected-item]
:action (fn [] (d/transact! state [[:db/add 0 :selected new-id]]))})
(defui ItemOne
static om/IQuery
(query [this]
[:type :item-one/title])
Object
(render [this]
(println "render ItemOne")
(let [{:keys [item-one/title]} (om/props this)]
(dom/div nil
(dom/h2 nil title)
(dom/button
#js {:onClick
(fn [e]
(om/transact! this
`[(app/item-switch {:prop 2})]))}
"switch to item 2")))))
(def item-one (om/factory ItemOne))
(defui ItemTwo
static om/IQuery
(query [this]
[:type :item-two/title])
Object
(render [this]
(println "render ItemTwo")
(let [{:keys [item-two/title]} (om/props this)]
(dom/div nil
(dom/h2 nil title)
(dom/button
#js {:onClick
(fn [e]
(om/transact! this
`[(app/item-switch {:prop 1})]))}
"switch to item 1")))))
(def item-two (om/factory ItemTwo))
(defui Root
static om/IQuery
(query [this]
[{:selected-item {:one (om/get-query ItemOne)
:two (om/get-query ItemTwo)}}])
Object
(render [this]
(println "render root")
(let [{:keys [type] :as props} (-> this om/props :selected-item)]
(dom/div nil
(if (= type :one) (item-one props))
(if (= type :two) (item-two props))))))
(def reconciler
(om/reconciler
{:state conn
:parser (om/parser {:read read :mutate mutate})}))
(om/add-root! reconciler
Root (gdom/getElement "app"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment