Skip to content

Instantly share code, notes, and snippets.

@monty5811
Created May 1, 2017 09:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monty5811/63727fd75b76ad9857d60a2685620fc2 to your computer and use it in GitHub Desktop.
Save monty5811/63727fd75b76ad9857d60a2685620fc2 to your computer and use it in GitHub Desktop.
Super Simple Communication Between Tabs for Elm
const Elm = require('./Main.elm');
const lsKey = 'elm-inter-tab-eg-v1'; // change the key if the model changes
function handleDOMContentLoaded() {
// setup elm
const node = document.getElementById('elmContainer');
const app = Elm.Main.embed(
node,
{model: localStorage.getItem(lsKey)}, // load model on page load
);
app.ports.saveToStorage.subscribe(function(m) {
// save our model to local storage
localStorage.setItem(lsKey, JSON.stringify(m));
});
window.addEventListener('storage', function (event) {
if (event.key === lsKey) {
// if the model changes, pass it into elm
app.ports.fromStorage.send(event.newValue);
}
});
}
window.addEventListener('DOMContentLoaded', handleDOMContentLoaded, false);
port module Main exposing (..)
import Json.Decode
import Html exposing (..)
import Html.Events exposing (onClick)
type alias Flags =
{ model : Maybe String }
type Msg
= Increment
| Decrement
| FromStorage (Maybe String)
type alias Model =
Int
initialModel flags =
decodeLocalStorage flags.model
decodeLocalStorage : Maybe String -> Int
decodeLocalStorage ms =
case ms of
Nothing ->
0
Just s ->
Json.Decode.decodeString Json.Decode.int s
|> Result.withDefault 0
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
let
newModel =
updateHelper msg model
in
( newModel, saveToStorage newModel )
updateHelper : Msg -> Model -> Model
updateHelper msg model =
case msg of
Increment ->
model + 1
Decrement ->
model - 1
FromStorage ms ->
decodeLocalStorage ms
view : Model -> Html Msg
view model =
div []
[ button [ onClick Decrement ] [ text "-" ]
, div [] [ text (toString model) ]
, button [ onClick Increment ] [ text "+" ]
]
port saveToStorage : Int -> Cmd msg
port fromStorage : (Maybe String -> msg) -> Sub msg
subscriptions model =
fromStorage FromStorage
main : Program Flags Model Msg
main =
programWithFlags
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
init : Flags -> ( Model, Cmd Msg )
init flags =
( initialModel flags, Cmd.none )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment