我正在尝试将IORef设置为三种类型,但我无法让它正常工作。在我的应用程序中,IORef本身会更复杂,而不是显示出来--但是这个例子说明了我认为的问题。
以下是我的尝试:
testIORef2 :: IORef String -> Window -> UI ()
testIORef2 ref window = void $ do
return window # set title "Test IORef"
inCell <- UI.input
outCell <- UI.input
getBody window #+ [
column [
grid [[string " In cell::", element inCell]
,[string "Out cell::" , element outCell ]]
, string "Cells should update while typing."
]]
-- When value changes write to IORef
on UI.valueChange inCell $ \_ -> do
inValue <- get value inCell
liftIO $ writeIORef ref inValue
-- Read the IORef
refVal <- liftIO $ readIORef ref
-- Behaviour which holds the string value in the input cell
inValue <- stepper "0" $ UI.valueChange inCell
-- Behaviour which holds the value in the ref
let outValue = (const refVal) <$> inValue
-- Set the value of the output cell to the outValue
element outCell # sink value outValue代码类型可以工作,但outValue并不完全是最新的。
我如何修复它,以便及时更新。此外,对代码的任何改进都将受到欢迎。
谢谢。
发布于 2015-05-02 08:37:38
您编写的代码可能不是您想要做的。线
let outValue = (const refVal) <$> inValue指定outValue是值为常数且等于refValue的Behavior。而后者的值则是从
refVal <- liftIO $ readIORef ref这意味着它是IORef在此时存储在UI monad中的值。
当使用IORef时,当某些内容发生变化时,您希望读取引用的值,并使用该值修改UI内容,例如:
on UI.valueChange inCell $ \_ -> do
inValue <- get value inCell
liftIO $ writeIORef ref inValue
outValue <- liftIO $ readIORef ref
element outCell # set value outValue出于一致性(操作顺序)的原因,使用IORef作为Behavior的源是不可取的--它要么是后者,要么是前者。
发布于 2015-05-01 12:07:01
我不是三部曲专家,但我猜是这样的。
在on事件处理程序之外编写的代码只执行一次。因此,您希望在所述处理程序中包含outValue更新,例如,
-- When value changes write to IORef
on UI.valueChange inCell $ \_ -> do
inValue <- get value inCell
liftIO $ writeIORef ref inValue
... -- compute outValue
element outCell # sink value outValuehttps://stackoverflow.com/questions/29986175
复制相似问题