2015-12-03 118 views
4

按鈕,我想是這樣的:點擊「回車」按鍵

on UI.keydown textfield $ \c -> when (c == 13) $ void $ do 
    trigger UI.click button 

也就是說,是有什麼,它如同trigger功能我剛插入?

回答

1

爲了讓輸入按鍵處理就好像它們是按鈕點擊一樣,您不需要直接觸發點擊。相反,您需要一個無論何時發生按鍵或點擊都會觸發的事件。最簡單的方法是,特別是如果您已經使用Threepenny的玻璃鋼組合器(我衷心推薦),通過unionWith。與一些其他Reactive.Threepenny組合程序,代碼可能是這樣的:

-- I'm giving separate names to the events for extra clarity. 
let eClick = UI.click button 
    eEnter = void $ filterE (== 13) (UI.keydown textfield) 
    -- This event is fired whenever `eClick` or `eEnter` happen. 
    eGo = unionWith const eClick eEnter 

然後你只需處理eGo,使用onEvent,在你處理click事件的方式。

注意的是,在你的問題的僞精神的另一種解決辦法是通過newEvent定義eGo然後使用觸發功能你能火中的點擊和按鍵的on處理事件:

-- Assuming you are in an `UI` do-block, thus the `liftIO`. 
(eGo, fireGo) <- liftIO newEvent 
on UI.click button $ \_ -> fireGo() 
on UI.keydown textfield $ \c -> when (c == 13) (fireGo()) 
-- Alternatively, you might define an `eEnter` with `filterE`, 
-- as in the first example, instead of using `on` and `when`. 

這不像第一種解決方案那麼好,因爲它有點混亂,並且不能像FRP碼一樣順暢地播放。我不會推薦它,除非你可能根本不使用FRP組合器。

+0

如何爲eGo添加2個以上的活動? 你能舉一個newEvent構造的例子嗎?謝謝! – allidoiswin

+1

@allidoiswin(1)多次使用'unionWith'(例如'unionWith const eA(unionWith const eB eC)')或['union'](https://hackage.haskell.org/package/threepenny-gui-0.6 .0.3/docs/Reactive-Threepenny.html#v:union)(例如'void(union [eA,eB,eC])')。 (2)我增加了一個替代方案的例子。 – duplode