Skip to content

Instantly share code, notes, and snippets.

@geraldodev
Created January 21, 2014 01:34
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 geraldodev/8532811 to your computer and use it in GitHub Desktop.
Save geraldodev/8532811 to your computer and use it in GitHub Desktop.
Attempt to centralize state when you are relying on get-state set-state!
(defn concat-korks
"Takes two sequentials and concats them. Respects the type of the first sequential.
Favors vector in none is a sequential"
[korks k2orks]
(if-not (sequential? korks)
(if-not (sequential? k2orks)
[korks k2orks]
(if (list? k2orks)
(conj k2orks korks)
(into [korks] k2orks)))
(if (list? korks)
(if-not (sequential? k2orks)
(into (list k2orks) korks)
(if (list? k2orks)
(into k2orks korks)
(into (seq k2orks) korks)))
(if-not (sequential? k2orks)
(conj korks k2orks)
(into korks k2orks)))))
(defn get-state-fn
"Takes an owning pure node and the keys where to retrieve state
and returns a function that takes just the remaining keys and
invokes om/get-state concatenating the keys"
[owner ks]
(fn
([] (om/get-state owner))
([remaining-ks]
(om/get-state owner (concat-korks ks remaining-ks)))))
(defn set-state-fn
"Takes an owning pure node and the keys where to save state
and returns a function that takes just the remaining keys and
invokes om/set-state concatenating the keys"
[owner ks]
(fn [remaining-ks v]
(om/set-state! owner (concat-korks ks remaining-ks) v)))
(defn get-set-state-map
"Sugar over get-state-fn and set-state-fn that generates a map with
the result of those functions, accessible with :get-state and :set-state!
keys.
It's meant to be passed as opts to components down the tree. Like this:
(om/build yourcomponent yourcusor {:opts {(get-set-state-map owner :wheretosavestate)}})
In this case you don't want to save state in 'yourcomponent' because
the component that is declaring it is aggregating state in it's own
'owning pure node' in which we want the state of 'yourcomponent' be saved at
:wheretosavestate.
In the called component all you have to do is, receive the get-state and set-state!
by destructuring the third parameter:
(defn yourcomponent [{} _ {:keys [get-state set-state!]}])
As you see this functions are now locally scoped in your component, and calling
them will get/set state at the place the calling component asked, making state
more centralized and manageable
"
[owner keys-path]
{:get-state (get-state-fn owner keys-path)
:set-state! (set-state-fn owner keys-path)})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment