Om应用程序状态和应用程序结构

Dre*_*wes 4 clojurescript om

我在Om中显示一个菜单,使用这样的组件和子组件:

(def app-state (atom {:location ""
                      :menuitems [["Pages" "/pages/"]
                                  ["Images" "/images/"]]}))

(defn menu-item-view [parent-cursor item owner]
  (reify
    om/IRender
    (render [this]
      (dom/li #js {:className (if (= (:location @app-state) (last item)) "active" "inactive")} 
        (dom/a #js 
               {:onClick (fn [_] (swap! app-state assoc :location (last @item)))} 
               (first item))))))

(defn menu-view [app owner]
  (reify
    om/IRender
    (render [this]
      (dom/li #js {:className "has-dropdown not-click"}
        (dom/a nil "Menu")
        (apply dom/ul #js {:className "dropdown"}
          (om/build-all (partial menu-item-view app) 
                        (:menuitems app)))))))

(om/root menu-view app-state
  {:target (. js/document (getElementById "menu"))})
Run Code Online (Sandbox Code Playgroud)

我的问题是如何更新(@ app-state:location)并正确地重新呈现菜单?

上面代码中的更新:

(swap! app-state assoc :location (last @item))
Run Code Online (Sandbox Code Playgroud)

确实有效,但树没有更新.

我怀疑我需要使用om/update!或者om/transact!但它们采用光标,我在菜单项视图中唯一的光标是当前菜单项,而不是完整的应用程序状态.所以我无法访问:位置.

这是怎么处理的?

如果可能的话,我宁愿暂时使用core.async和channel.

Ann*_*cka 6

既然我们有参考游标你可能会做这样的事情:

(def app-state (atom {:location ""
                      :menuitems [["Pages" "/pages/"]
                                  ["Images" "/images/"]]}))

(defn location []
  (om/ref-cursor (:location (om/root-cursor app-state))))

(defn menu-item-view [item owner]
  (reify
    om/IRender
    (render [this]
      (let [x (location)]
        (dom/li #js {:className (if (= x (last item)) "active" "inactive")}
                (dom/a #js
                       {:onClick (fn [_] (om/update! x (last @item)))}
                       (first item)))))))

(defn menu-view [app owner]
  (reify
    om/IRender
    (render [this]
      (dom/li #js {:className "has-dropdown not-click"}
              (dom/a nil "Menu")
              (apply dom/ul #js {:className "dropdown"}
                     (om/build-all menu-item-view (:menuitems app)))))))

(om/root menu-view app-state
  {:target (. js/document (getElementById "menu"))})
Run Code Online (Sandbox Code Playgroud)

这只是一个想法 - 我还没有真正测试过它.