【发布时间】:2017-05-25 08:18:58
【问题描述】:
作为 elm 的学习示例,我想用 elm 架构创建一个简单的蛇游戏。
这里是到目前为止的完整代码: https://gist.github.com/DanEEStar/b11509514d72eaafb640378fc7c93b44
程序的一部分是由单击按钮生成的UpdateWorld 消息和在用户按下空格键时调用的updateWorld 函数。
这导致以下编译和工作代码(sn-ps 形成完整代码):
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
UpdateWorld ->
( updateWorld model, Cmd.none )
KeyPress keyCode ->
( handleInput keyCode model, Cmd.none )
handleInput : Int -> Model -> Model
handleInput keyCode model =
case Char.fromCode keyCode of
' ' ->
updateWorld model
_ ->
model
updateWorld : Model -> Model
updateWorld model =
{ model | snake = updateSnake model.snake }
subscriptions : Model -> Sub Msg
subscriptions model =
Keyboard.presses KeyPress
view : Model -> Html Msg
view model =
div []
-- here I can simply tell `onClick` to generate the `UpdateWorld` command
[ button [ onClick UpdateWorld ] [ text "tick" ]
]
在这段代码 sn-ps 中,很明显onClick 事件生成了UpdateWorld 命令。
但在handleInput 函数中,我必须“手动”调用updateWorld 函数。
我宁愿从我的handleInput 函数“生成”一个新的UpdateWorld 命令。我认为这将澄清代码。比如:
handleInput keyCode =
case Char.fromCode keyCode of
' ' ->
-- how can I generate this command in my code
UpdateWorld
我该怎么做?
这是一个好主意,还是更好的模式?
【问题讨论】:
标签: elm