Skip to content

Instantly share code, notes, and snippets.

@Alexandre-Herve
Last active May 15, 2017 09:48
Show Gist options
  • Save Alexandre-Herve/dda1572341101d32e7f4ce2a48711fce to your computer and use it in GitHub Desktop.
Save Alexandre-Herve/dda1572341101d32e7f4ce2a48711fce to your computer and use it in GitHub Desktop.
A way to handle cross-pages shared actions in Elm
module Main exposing (main)
import Model exposing (Model, initialModel)
import Html exposing (Html, div, text, button)
import Html.Events exposing (onClick)
import Shared
import Page
import Debug
-- Update
type Msg
= SharedMsg Shared.Msg
| PageMsg Page.Msg
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
-- To modularize, delegate this to Shared's own update function
SharedMsg msg ->
let
log =
Debug.log "Shared msg" msg
in
( model, Cmd.none )
-- To modularize, delegate this to Page's own update function
PageMsg msg ->
let
log =
Debug.log "Page msg" msg
in
case msg of
Page.SharedMsg sharedMsg ->
update ( SharedMsg sharedMsg ) model
-- shared messages are sent back to be handled by Shared's update function
Page.PageSpecificAction ->
( model, Cmd.none )
-- View
view : Model -> Html Msg
view model =
div []
[ button [ onClick ( SharedMsg Shared.SharedAction ) ] [ text "Shared action from main view" ]
, Html.map PageMsg ( Page.view model )
]
-- Subscriptions
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- Main
main : Program Never Model Msg
main =
Html.program
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
init : ( Model, Cmd Msg )
init =
( initialModel, Cmd.none )
module Model exposing (..)
type alias Model =
{}
initialModel : Model
initialModel =
{}
module Page exposing (..)
import Html exposing (Html, div, text, button)
import Html.Events exposing (onClick)
import Model exposing (Model)
import Shared
-- Update
type Msg
= PageSpecificAction
| SharedMsg Shared.Msg
-- View
view : Model -> Html Msg
view model =
div []
[ button [ onClick ( SharedMsg Shared.SharedAction ) ] [ text "Shared action from page view" ]
, button [ onClick ( PageSpecificAction ) ] [ text "Page action from page view" ]
]
module Shared exposing (..)
-- Update
type Msg
= SharedAction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment