4

我在 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"))})

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

上面代码中的更新:

(swap! app-state assoc :location (last @item))

确实有效,但树没有正确更新。

我怀疑我需要使用 om/update!或 OM/交易!但他们有一个光标,我在菜单项视图中唯一的光标是当前菜单项,而不是完整的应用程序状态。所以我无法访问:location。

这是如何处理的?

如果可能的话,我宁愿暂时避免 core.async 和频道。

4

2 回答 2

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"))})

这只是一个想法——我还没有实际测试过。

于 2014-10-21T17:05:37.417 回答
2

是的,所有更新都应该通过 om/transact 进行!或 OM/更新!

您可以将主光标传递给 :init-state 或 :state 中的控件状态。这将使您可以访问它以进行更新。

或者,您可以避免使用 om/build-all 并直接使用 build 将多个游标传递给此处指定的控件。

只需调用以下命令:

(map #(om/build menu-item-view {:main-cursor app :menu-cursor %}) (:menuitems app)) 
于 2014-10-15T11:47:09.500 回答