In this tutorial, you will learn about using WebSharper UI to implement a simple Model-View-Update (MVU) application pattern, similar to the Elm architecture. In subsequent tutorials, you will learn about enhancing this pattern to a full-scale application development architecture (The WebSharper Architecture) that has superior performance and sufficient flexibility to implement any type of web application. Be sure to read the First Steps: Using HTML templates, accessing form values, and wiring events tutorial to get a solid grip on some of the WebSharper fundamentals, these will come handy while reading this tutorial.
What You Will Learn and a Quick Recap
Using a Model-View-Update (MVU)-like approach with WebSharper UI. As you will see, WebSharper UI can implement a number of different styles of reactive UI programming easily.
You Already Learned in the Previous Tutorial How to:
Create WebSharper SPA projects. In the parent folder of your choice, type:dotnet new websharper-spa -lang f# -n YourApp
Edit the key files in your SPA project. For simple SPAs, these files will be:
wwwroot\index.html – Your main SPA – this is the file you open to run your app.
Client.fs – The logic for your SPA – this is where your F# code will be.
Use HTML Templates. WebSharper UI provides an advanced templating engine with dynamic code generation both for C# and F#. Always consider using external HTML templates instead of inlined HTML combinators to speed up your developer workflow. Templates allow you to make changes to your presentation layer without having to compile your project.open WebSharper.UI.Templating
type MySPA = Template<"wwwroot/index.html", ClientLoad.FromDocument>
.Bind()You can use templates everywhere you need Doc values by calling .Doc(), or you can use .Bind() to apply your template instantiations to your master document (typically your main SPA page).
In wwwroot/index.html, mark input controls with ws-on[xxx] for each event xxx you want to bind:<button ws-onclick="OnSubmit">Click me</button>
Read and write the values of HTML input controls
In wwwroot/index.html, mark input controls with ws-var="xxx":<input ws-var="Name" ws-onkeydown="OnEdit" type="text" />
To read form values in Client.fs, access them as follows: `fsharp open WebSharper.UI open WebSharper.UI.Client … MySPA() .OnSubmit(fun e -> … e.Vars.Name …)`
To write/update form values, in Client.fs, access them as follows:open WebSharper.UI.Notation
.OnSubmit(fun e ->
e.Vars.Name := ""
Use Reactive Variables
Create a reactive variable: `fsharp let v = Var.Create 0`
Read the value of a reactive variable: `fsharp v.Value`
Set the value of a reactive variable: `fsharp open WebSharper.UI.Notation … v := !v + 1`
To get the most out of this tutorial, make sure you have installed the following: