Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- port module PortTest exposing (..)
- import Browser
- import Html exposing (..)
- import Html.Attributes exposing (..)
- import Html.Events exposing (..)
- import Json.Decode exposing (Decoder,decodeString, map4, field, int, string)
- import Json.Encode
- -- MAIN
- main : Program () Model Msg
- main =
- Browser.element
- { init = init
- , view = view
- , update = update
- , subscriptions = subscriptions
- }
- -- PORTS
- port sendMessage : Json.Encode.Value -> Cmd msg
- port messageReceiver : (Json.Encode.Value -> msg) -> Sub msg
- -- MODEL
- type alias Model =
- { draft : String
- , messages : List Quote
- }
- type alias Quote =
- { quote : String
- , source : String
- , author : String
- , year : Int
- }
- init : () -> ( Model, Cmd Msg )
- init flags =
- ( { draft = "", messages = [] }
- , Cmd.none
- )
- -- UPDATE
- type Msg = Recv Quote
- -- Use the `sendMessage` port when someone presses ENTER or clicks
- -- the "Send" button. Check out index.html to see the corresponding
- -- JS where this is piped into a WebSocket.
- --
- update : Msg -> Model -> ( Model, Cmd Msg )
- update msg model =
- case msg of
- Recv message ->
- ( { model | messages = model.messages ++ [ message] }
- , Cmd.none
- )
- -- SUBSCRIPTIONS
- -- Subscribe to the `messageReceiver` port to hear about messages coming in
- -- from JS. Check out the index.html file to see how this is hooked up to a
- -- WebSocket.
- --
- subscriptions : Model -> Sub Msg
- subscriptions model = messageReceiver quoteDecoder
- -- VIEW
- view : Model -> Html Msg
- view model =
- -- Debug.log "my model" model
- div []
- [ h1 [] [ text "Websocket json test" ]
- , ul []
- (List.map (\msg -> li [] [ text msg.quote ]) model.messages)
- ]
- quoteDecoder : Json.Decode.Decoder msg
- quoteDecoder =
- map4 Quote
- (field "quote" string)
- (field "source" string)
- (field "author" string)
- (field "year" int)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement