2012-12-01 27 views

回答

9

如果您希望每個按鈕被點擊時要添加的文本字段,這意味着你要顯示的文本字段的數量等於次按鈕被點擊數。我們可以通過按鈕的clicked信號¹上的countIf id創建一個信號,告訴我們按鈕被點擊的頻率。

如果我們的輸入列表,我們可以使用flow到下面(或除)顯示它們彼此。編寫一個函數需要編號n並生成一個包含按鈕和文本字段的列表。

所以現在我們可以只使用lift掛鉤這個函數達到我們的信號,計數按鈕的點擊數,結合起來,與該flow功能,瞧,我們有一個按鈕,動態創建的投入。

(btn, clicked) = Input.button "Click me!" 

-- Count how often the clicked signal is true 
clicks = countIf id clicked 

main = lift2 flow (constant down) $ lift nInputs clicks 

nInputs n = 
    let helper n acc = 
    if n<=0 then btn : acc 
    else 
     -- Input.textField returns a pair containing the field as well as a signal 
     -- that you can use to access the field's contents. Since I don't actually 
     -- ever do anything with the contents, I just ignore the signal here. 
     -- In your real code, you'd probably want to keep the signal around as well. 
     let (field, _) = Input.textField $ "input " ++ (show n) 
     in helper (n-1) $ field : acc 
    in helper n [] 

¹只要使用count就可以計算信號改變的頻率。由於每次點擊都會導致信號值變爲true,然後又回到false,那麼每次點擊就會計數2次更改。通過使用countIf id,我們只計算信號爲真的次數,從而計算點擊次數。

+3

請注意,Elm不支持信號信號。如果要存儲文本字段的輸入信號,可以使用Automaton庫:http://elm-lang.org/docs/Automaton.elm – thSoft