Created
February 9, 2015 16:40
-
-
Save tatut/e7e5e7e2becf56b8ef7b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns bug | |
(:require [reagent.core :refer [atom] :as reagent])) | |
;; This version does not work: changed values of all-selections or | |
;; selected atoms are not reflected in the markup. | |
;; The open swap! works as expected. | |
(defn pulldown [selected format-fn select-fn selections] | |
(let [open (atom false)] | |
(fn [] | |
[:div.pulldown-menu | |
[:button {:on-click #(swap! open not)} | |
(format-fn selected)] | |
(when @open | |
[:ul | |
(for [item selections] | |
[:li {:on-click #(select-fn item)} | |
(format-fn item)])])]))) | |
;; This version "works", the changed values are reflected, but | |
;; it does not have the internal state for the open | |
(comment | |
(defn pulldown [selected format-fn select-fn selections] | |
[:div.pulldown-menu | |
[:button {:on-click #(.log js/console "no open state")} | |
(format-fn selected)] | |
[:ul | |
(for [item selections] | |
[:li {:on-click #(select-fn item)} | |
(format-fn item)])]]) | |
) | |
;; This version uses return-create-class-trick from | |
;; https://github.com/reagent-project/reagent/issues/47 | |
;; and both the local state and outer state work, yay! :) | |
(comment | |
(defn pulldown [] | |
(let [open (atom false)] | |
(reagent/create-class | |
{:component-function | |
(fn [selected format-fn select-fn selections] | |
[:div.pulldown-menu | |
[:button {:on-click #(swap! open not)} | |
(format-fn selected)] | |
(when @open | |
[:ul | |
(for [item selections] | |
[:li {:on-click #(select-fn item)} | |
(format-fn item)])])])}))) | |
) | |
(def all-selections (atom [{:name "Foo"}])) | |
(def selected (atom nil)) | |
;; add watchers so that both atom's changes are logged | |
(add-watch all-selections ::debug | |
(fn [_ _ old new] | |
(.log js/console "all-selections: " (pr-str old) " => " (pr-str new)))) | |
(add-watch selected ::debug | |
(fn [_ _ old new] | |
(.log js/console "selected: " (pr-str old) " => " (pr-str new)))) | |
(defn change-selection [s] | |
(reset! selected s)) | |
(defn container [] | |
[:span | |
"Pulldown below, should update when all-selections or selected atoms change:" | |
[:hr] | |
[pulldown @selected #(if % (:name %) "No selection") | |
change-selection @all-selections] | |
[:hr] | |
[:button {:on-click #(swap! all-selections conj {:name "Bar"})} | |
"this button should add selection Bar"]]) | |
(defn #^:export main [] | |
(reagent/render [container] (.getElementById js/document "bug1"))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment