Skip to content

Instantly share code, notes, and snippets.

@joelash
Forked from manicolosi/reagent-lifecycle-async.cljs
Last active November 3, 2015 18:04

Revisions

  1. joelash revised this gist Nov 3, 2015. 1 changed file with 22 additions and 6 deletions.
    28 changes: 22 additions & 6 deletions reagent-lifecycle-async.cljs
    Original file line number Diff line number Diff line change
    @@ -1,26 +1,42 @@
    ;; Async Lifecycle

    (defn lifecycle-channel [component]
    (.-lifecycleChannel component))
    (let [tap-ch (async/chan)]
    (-> (.-lifecycleChannel component)
    :mult
    (async/tap tap-ch))
    tap-ch))

    (defn with-lifecycle [klass]
    (let [ch (async/chan)
    handle (fn [event]
    mult (async/mult ch)
    tap-ch (async/chan)
    handle (fn [event & extra-args]
    (fn [& args]
    (async/put! ch event)
    (when-let [f (event klass)]
    (apply f args))))]
    (apply f (concat extra-args args)))))]
    (async/tap mult tap-ch)
    (into
    {:component-will-mount
    (fn [this]
    (set! (.-lifecycleChannel this) ch)
    (set! (.-lifecycleChannel this) {:ch ch :mult mult})
    ((handle :component-will-mount) this))
    :component-will-unmount
    (fn [this]
    ((handle :component-will-unmount) this)
    (async/close! (lifecycle-channel this))) }
    (async/untap-all mult)
    (async/close! ch))
    :reagent-render
    (fn [& args]
    (async/put! ch :reagent-render)
    (when-let [f (or (:reagent-render-with-lifecycle klass)
    (:reagent-render klass))]
    (apply f (cond->> args
    (:reagent-render-with-lifecycle klass)
    (cons tap-ch)))))}
    (for [event [:get-initial-state :component-will-receive-props
    :should-component-update :component-did-mount
    :component-will-update :component-did-update :reagent-render]]
    :component-will-update :component-did-update]]
    [event (handle event)]))))

  2. @manicolosi manicolosi created this gist Nov 2, 2015.
    26 changes: 26 additions & 0 deletions reagent-lifecycle-async.cljs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    ;; Async Lifecycle

    (defn lifecycle-channel [component]
    (.-lifecycleChannel component))

    (defn with-lifecycle [klass]
    (let [ch (async/chan)
    handle (fn [event]
    (fn [& args]
    (async/put! ch event)
    (when-let [f (event klass)]
    (apply f args))))]
    (into
    {:component-will-mount
    (fn [this]
    (set! (.-lifecycleChannel this) ch)
    ((handle :component-will-mount) this))
    :component-will-unmount
    (fn [this]
    ((handle :component-will-unmount) this)
    (async/close! (lifecycle-channel this))) }
    (for [event [:get-initial-state :component-will-receive-props
    :should-component-update :component-did-mount
    :component-will-update :component-did-update :reagent-render]]
    [event (handle event)]))))