Elm Language
Mit ccapndave / elm-update-extra komplexe Update-Funktionen erstellen
Suche…
Einführung
ccapndave / elm-update-extra ist ein fantastisches Paket, das Ihnen beim Umgang mit komplexeren Aktualisierungsfunktionen hilft und sehr nützlich sein kann.
Nachricht, die eine Liste von Nachrichten aufruft
Mit der sequence können Sie einfach eine Nachricht beschreiben, die eine Liste anderer Nachrichten aufruft. Dies ist nützlich, wenn es um die Semantik Ihrer Nachrichten geht.
Beispiel 1: Sie erstellen eine Spiel-Engine und müssen den Bildschirm in jedem Frame aktualisieren.
module Video exposing (..)
type Message = module Video exposing (..)
import Update.Extra exposing (sequence)
-- Model definition [...]
type Message
= ClearBuffer
| DrawToBuffer
| UpdateLogic
| Update
update : Message -> Model -> (Model, Cmd)
update msg model =
case msg of
ClearBuffer ->
-- do something
DrawToBuffer ->
-- do something
UpdateLogic ->
-- do something
Update ->
model ! []
|> sequence update [ ClearBuffer
, DrawToBuffer
, UpdateLogic]
Verkettung von Nachrichten mit andThen
Die andThen Funktion ermöglicht die Aktualisierung der andThen . Kann mit dem Pipeline-Operator ( |> ) verwendet werden, um Updates zu verketten.
Beispiel: Sie erstellen einen Dokumenteditor und möchten, dass jede Änderungsnachricht, die Sie an Ihr Dokument senden, auch gespeichert wird:
import Update.Extra exposing (andThen)
import Update.Extra.Infix exposing (..)
-- type alias Model = [...]
type Message
= ModifyDocumentWithSomeSettings
| ModifyDocumentWithOtherSettings
| SaveDocument
update : Model -> Message -> (Model, Cmd)
update model msg =
case msg of
ModifyDocumentWithSomeSettings ->
-- make the modifications
(modifiedModel, Cmd.none)
|> andThen SaveDocument
ModifyDocumentWithOtherSettings ->
-- make other modifications
(modifiedModel, Cmd.none)
|> andThen SaveDocument
SaveDocument ->
-- save document code
Wenn Sie auch Update.Extra.Infix exposing (..) importieren, können Sie möglicherweise den Infix-Operator verwenden:
update : Model -> Message -> (Model, Cmd)
update model msg =
case msg of
ModifyDocumentWithSomeSettings ->
-- make the modifications
(modifiedModel, Cmd.none)
:> andThen SaveDocument
ModifyDocumentWithOtherSettings ->
-- make other modifications
(modifiedModel, Cmd.none)
:> SaveDocument
SaveDocument ->
-- save document code