Skip to content

Instantly share code, notes, and snippets.

@Tarmil
Last active October 6, 2016 22:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Tarmil/bda2cc9e63fa184dd48a to your computer and use it in GitHub Desktop.
Save Tarmil/bda2cc9e63fa184dd48a to your computer and use it in GitHub Desktop.
Port of the first example from https://github.com/evancz/elm-architecture-tutorial to WebSharper
namespace Example1
open WebSharper
open WebSharper.UI.Next
open WebSharper.UI.Next.Html
open WebSharper.UI.Next.Client
[<JavaScript>]
module Counter =
type Model = int
type Action = Increment | Decrement
let Update (action: Action) (model: Model) : Model =
match action with
| Increment -> model + 1
| Decrement -> model - 1
let private countStyle =
Attr.Concat [
Attr.Style "font-size" "20px"
Attr.Style "font-family" "monospace"
Attr.Style "display" "inline-block"
Attr.Style "width" "50px"
Attr.Style "text-align" "center"
]
let Render (send: Action -> unit) (model: View<Model>) : Doc =
div [
buttonAttr [on.click (fun _ _ -> send Decrement)] [text "-"]
divAttr [countStyle] [textView (model.Map string)]
buttonAttr [on.click (fun _ _ -> send Increment)] [text "+"]
]
:> Doc
namespace Example1
open WebSharper
open WebSharper.JavaScript
open WebSharper.JQuery
open WebSharper.UI.Next
open WebSharper.UI.Next.Client
[<JavaScript>]
module Main =
let Main =
StartApp.Start {
Model = 0
Update = Counter.Update
Render = Counter.Render
}
// Straightforward equivalent of Elm's StartApp.Simple
// using `Action -> unit` to model Elm's `Signal.Address Action`
// and renaming `view` to `Render` to avoid ambiguity with UI.Next's View<'T>
module StartApp
open WebSharper
open WebSharper.JavaScript
open WebSharper.UI.Next
open WebSharper.UI.Next.Client
type App<'Model, 'Action> =
{
Model : 'Model
Update : 'Action -> 'Model -> 'Model
Render : ('Action -> unit) -> View<'Model> -> Doc
}
[<JavaScript>]
let Start (app: App<'Model, 'Action>) : unit =
let model = Var.Create app.Model
let send = app.Update >> Var.Update model
app.Render send model.View
|> Doc.RunAppend JS.Document?body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment