使用 om 时
(在 om-next 之前(,我在尝试在渲染阶段之外进行更新时遇到错误:
cljs.user=> (require '[om.core :as om :include-macros true])
cljs.user=> (def state (atom {:foo {:bar true}}))
#'cljs.user/state
cljs.user=> (def state-cursor (om/root-cursor state))
#'cljs.user/state-cursor
cljs.user=> (om/update! state-cursor [:foo :bar] false)
#object[Error Error: No protocol method INotify.-notify! defined for type cljs.core/Atom: [object Object]]
Error: No protocol method INotify.-notify! defined for type cljs.core/Atom: [object Object]
at cljs$core$missing_protocol (http://localhost:10555/js/out/cljs/core.js:290:9)
at om$core$_notify_BANG_ (http://localhost:10555/js/out/om/core.js:841:34)
at om$core$notify_STAR_ (http://localhost:10555/js/out/om/core.js:2518:30)
at om$core$transact_STAR_ (http://localhost:10555/js/out/om/core.js:1070:29)
at om.core.MapCursor.om$core$ITransact$_transact_BANG_$arity$4 (http://localhost:10555/js/out/om/core.js:2042:31)
at om$core$_transact_BANG_ (http://localhost:10555/js/out/om/core.js:770:15)
at Function.om.core.transact_BANG_.cljs$core$IFn$_invoke$arity$4 (http://localhost:10555/js/out/om/core.js:4074:32)
at om$core$transact_BANG_ (http://localhost:10555/js/out/om/core.js:4044:31)
at Function.om.core.update_BANG_.cljs$core$IFn$_invoke$arity$3 (http://localhost:10555/js/out/om/core.js:4135:31)
at om$core$update_BANG_ (http://localhost:10555/js/out/om/core.js:4105:29)
而不是错误:Error: No protocol method INotify.-notify! defined for type cljs.core/Atom
,我希望这会将state
原子更新为(atom {:foo {:bar false}})
。我该如何解决这个问题?
问题是我需要在根游标上调用(om/ref-cursor)
,然后再将其传递给om/transact!
或om/update!
。这样做解决了我的问题:
cljs.user=> (def state (atom {:foo {:bar true}}))
#'cljs.user/state
cljs.user=> (def state-cursor (om/root-cursor state))
#'cljs.user/state-cursor
cljs.user=> (om/update! (om/ref-cursor state-cursor) [:foo :bar] false)
nil
cljs.user=> state
#object [cljs.core.Atom {:val {:foo {:bar false}}}]