2017-03-09 52 views
5

我试图修改elm-lang tutorial中的一个简单应用程序以首先更新模型,然后触发另一个更新。Elm - 将Msg转为Cmd Msg

update msg model = 
    case msg of 
    MorePlease -> 
     (model, getRandomGif model.topic) 

    NewGif (Ok newUrl) -> 
     ({ model | gifUrl = newUrl }, Cmd.none) 

    NewGif (Err _) -> 
     (model, Cmd.none) 

    -- my addition 
    NewTopic newTopic -> 
     ({ model | topic = newTopic}, MorePlease) 

这失败的编译器,因为NewTopic分支:

The 3rd branch has this type: 

({ gifUrl : String, topic : String }, Cmd Msg) 

But the 4th is: 

({ gifUrl : String, topic : String }, Msg) 

所以我的消息必须键入Cmd消息。我怎样才能把”我的消息成一个cmd消息

注:我承认有一个简单的方式,这种改变的方式,但我想了解更多榆树根本

回答

13

实在是没有需要把MsgCmd Msg记住update仅仅是一个函数,所以你可以递归调用它

NewTopic办案人员可以简化为这样:。

NewTopic newTopic -> 
    update MorePlease { model | topic = newTopic} 

如果你真的真的想榆树建筑火灾关闭一个cmd对于这种情况,你可以做的Cmd.none简单map到你想要的Msg

NewTopic newTopic -> 
    ({ model | topic = newTopic}, Cmd.map (always MorePlease) Cmd.none) 

(实际上并不推荐)

+0

谢谢。这是解决问题的一种更简单的方法。我仍然想知道,我是否需要将“Msg”“投射”到“Cmd Msg”?如果我做了我会怎么样? – steel

+0

我用一个例子更新了我的答案 –

+0

@ChadGilbert:你能详细阐述一下为什么你不会推荐新的'Msg'来推荐第二种方法吗? – DanEEStar

相关问题