Rethink Frontend Development With Elm

Brian Hogan
Brian HoganProgrammer and writer.
Rethinking Front
End Development
With Elm
Brian Hogan
About me
• I build web things.
• I teach people.
• I make music.
• I write books.
Elm is a functional programming language like Haskell, but more
friendly, and aimed at front-end web development.
We use Elm to make our user interface and give it behavior.
Example
import Graphics.Element exposing (show)
main =
show "Hello World"
Elm compiles to JavaScript
Yes. We just wrote a bunch of code that gets injected into an HTML
page.
Feel gross yet?
That's what React does too.
var HelloMessage = React.createClass({
render: function () {
return <h1>Hello {this.props.message}!</h1>;
}
});
React.render(<HelloMessage message="World" />, document.body);
Okay, Why Elm?
• Same concepts as React
• Pure functions
• Immutable State
• Static Typing
What you need
• Node.js http://nodejs.org
• The elm package for Node
$ npm install -g elm
• Your favorite text editor
OR
http://elm-lang.org/try
Compiling Elm
• Create a hello.elm file
• Run
$ elm make hello.elm
Success! Compiled 1 modules.
Successfully generated index.html
• Open resulting index.html in your browser.
HTML
Comparison
• Elm: ~5400 lines
• React: ~19300 lines
• JQuery: ~9800 lines
Elm Reactor
Elm Reactor compiles Elm to HTML on
each request.
$ elm-reactor
elm reactor 0.16.0
Listening on http://0.0.0.0:8000/
How Elm Works
Every Elm app calls a main function when we run it.
main =
-- something goes here
Functions
We define functions with a name followed by an = sign.
hello =
"Hello there"
We indent the definitions of functions.
We invoke this function like this:
hello
Arguments
Functions can have arguments
square number =
number * number
Call it as
square 2
They have explicit returns.
Multiple Arguments
Multiple arguments use spaces:
add number1 number2 =
number1 + number2
Call it as
add 1 2
Woah.... no commas!
Type annotations
We can enforce data types for our functions so Elm can help us out.
functionName: TypeOfArg1-> TypeOfArg2 -> TypeOfArg3 -> ReturnType
Annotation Examples:
No parameters. Just return value
hello: String
hello =
"Hello there"
Two parameters and a return value
add: Float -> Float -> Float
add number1 number2 =
number1 + number2
Modules
Define modules to group your code.
module Hello where
main =
-- something goes here
Html functions
The elm-html module exposes many functions for building up virtual
DOM nodes.
The main function can render HTML if the HTML module is included.
import Html exposing(p, text)
main =
p [] [text "Hello World"]
p and text
p [] [text "Hello World"]
p and text are two functions from elm-html
p takes two lists
• a list of attributes (can be empty)
• a list of child elements
text takes a string of text to display.
HTML functions are uniform.
Each takes attributes and elements. So we can nest them like HTML.
div [class "foo", id "bar" ] [
h1 [] [text "Hello"],
p [] [text "World"]
]
There's a function for every element. Just be sure to expose what you
use.
Seriously uniform
label [for "name"] [text "Name"]
input [id "name", type' "number", step "any"] []
Even functions for tags that don't allow inner content still take two
lists as arguments.
Html Modules
• Html contains all the tags
• Html.Attributes contains the attributes (like class, id, href,
etc)
• Html.Events contains events like onClick
Html Attributes
import Html exposing(Html, div, text, p)
import Html.Attributes exposing(class)
main =
div [class "wrapper"] [
p [class "notice"] [text "This is important!"]
]
Composability
main =
view
view: Html
view =
div [] [
p [] [
text "Hello ",
em [] [text "world"]
]
]
Resuability
main =
div [] [
view "Hello",
view "Goodbye"
]
view: String -> Html
view word =
div [] [
p [] [ text (word ++ " "), em [] [text "world"] ]
]
Web Interfaces
import Html exposing(Html, Attribute, p, text)
import Html.Attributes exposing(style)
elementStyle: Attribute
elementStyle =
style [ ("color", "red") , ("font-size", "2em") ]
main: Html
main =
view
view =
p [elementStyle] [text "Hello World"]
Helpers!
fieldWithLabel: String -> String -> String -> Html
fieldWithLabel fieldID fieldName fieldType =
div [] [
label [for fieldID] [text fieldName],
input [ id fieldID, type' fieldType] []
]
Build Out The Helpers
numberField: String -> String -> Html
numberField fieldID fieldName =
fieldWithLabel fieldID fieldName "number"
textField: String -> String -> Html
textField fieldID fieldName =
fieldWithLabel fieldID fieldName "text"
emailField: String -> String -> Html
emailField fieldID fieldName =
fieldWithLabel fieldID fieldName "email"
Shiny Happy Frontend Code
main: Html
main =
div [] [
textField "name" "Name",
numberField "age" "Age",
emailField "email" "Email"
]
Elm Architecture
View: Function that fires when model changes. Transofms a model
into the UI that people see.
Model: Something that holds the current state of the app. No behavior.
Just the state. No behavior. This is not MVC with objects!
Update: Function that fires when state changes. Always returns a new
model.
Signals and Mailboxes
Signals
Signals route messages around the application. Pressing a button is a
signal. We can send data along signals.
Mailboxes
Mailboxes receive signals and send signals. A mailbox has an address
and a signal to respond to.
Basic Flow
• Model is initialized
• View is displayed with model
• Events send Signals to Mailboxes
• Mailboxes trigger updates
• New model is created
• New view is rendered
Yikes!
Elm StartApp.Simple
Like Flux, without all the code.
• Define Actions
• Define a model to represent data
• Define a view function
• Define an update function that returns a new model.
Change Text On Click
import Html exposing (Html, text, h1, p, div, button)
import StartApp.Simple as StartApp
import Html.Events exposing (onClick)
main =
StartApp.start {model = "Hello ", view = view, update = update}
view address initialText =
div [] [
h1 [] [text "Events"],
p [] [ text initialText ],
button [onClick address "change"] [text "Push me"]
]
update action model =
"it changed"
Actions
Actions get sent to the Update.
type Action = Increment | Decrement
model = 0
update: Signal.Action -> Int -> Int
update action model =
case action of
Increment -> model + 1
Decrement -> model - 1
Multiple events
main =
StartApp.start { model = model, view = view, update = update }
view: Signal.Address Action -> Int -> Html
view address model =
div []
[ button [ onClick address Increment ] [ text "Up" ]
, span [] [ text (toString model) ]
, button [ onClick address Decrement ] [ text "Down" ]
]
Once again...
• StartApp renders the view using an initial model state.
• Events defined in the view send Actions to Signal Addresses
which route to update.
• update returns a new version of the model
• StartApp causes the view to be rendered whenever model
changes.
Calculator
Compound Interest Calculator
Write a program to compute the value of an investment compounded
over time. The program should ask for the starting amount, the
number of years to invest, the interest rate, and the number of periods
per year to compound.
Project setup
Create folder and file to work in
$ mkdir calculator && cd calculator
$ touch calculator.elm
Init the project
$ elm package install
Install HTML and StartApp dependencies.
$ elm package install evancz/elm-html
$ elm package install evancz/start-app
Livereloading
Make browser reload when we save
$ npm install -g elm-live
$ elm-live calculator.elm
Steps
• Create the basic app
• Build the form
• Bind form to model and define events
• Perform calculations
• Display Output
The Basic App
import Html exposing (Html, text, h1, p, div, button, label, input)
import Html.Attributes exposing ( style, for, id, step, type', value)
import StartApp.Simple as StartApp
import Html.Events exposing (onClick)
main =
StartApp.start {model = model, view = view, update = update}
Define a model and update
model: Float
model = 0
update: String -> Float -> Float
update action model =
model
Building the form
• Use label, input functions
• Use number fields
• Each field change updates model state
• Clicking button calculates new amount
numberField helper
numberField: String -> String -> Html
numberField fieldID fieldName =
div [] [
label [for fieldID] [text fieldName],
input [ id fieldID, type' "number", step "any"] []
]
Style the form
labelStyle: Attribute
labelStyle =
style
[ ("width", "200px")
, ("padding", "10px")
, ("text-align", "right")
, ("display", "inline-block")
]
Apply style to field
div [] [
label [labelStyle, for fieldID] [text fieldName],
input [ id fieldID, type' "number", step "any"] []
]
Build the View
view: Signal.Address String -> Float -> Html
view address model =
div [] [
h1 [] [text "Calculator"],
div [] [
numberField "principal" "Principal",
numberField "rate" "Rate",
numberField "years" "Periods",
numberField "years" "Years"
]
button [onClick address "calculate"] [text "Calculate"]
]
Define Our Actions
type Action
= NoOp
| SetPrinciple String
| SetPeriods String
| SetRate String
| SetYears String
| Calculate
Define A Model
type alias Model =
{ principle: String
, rate: String
, years: String
, periods: String
, newAmount: Float}
model: Model
model =
{ principle = "1500.00"
, rate = "4.3"
, years = "6"
, periods = "4"
, newAmount = 0 }
Pass address, action, and model data to fields
view: Signal.Address Action -> Model -> Html
view address model =
div [] [
h1 [] [text "Calculator"],
div [] [
numberField address SetPrinciple "principle" "Principle" model.principle,
numberField address SetRate "rate" "Rate" model.rate,
numberField address SetPeriods "periods" "Periods" model.periods,
numberField address SetYears "years" "Years" model.years
],
button [onClick address Calculate] [text "Click me"],
Add Events To Form using Actions and model data
numberField: Signal.Address Action -> (String -> Action) ->
String -> String -> String -> Html
numberField address action fieldID name fieldValue =
div [] [
label [labelStyle, for fieldID] [text name],
input [id fieldID, type' "number", step "any",
on "input" targetValue (Signal.message address << action ),
value fieldValue] []
]
Update model from form
update: Action -> Model -> Model
update action model =
case action of
NoOp -> model
SetPrinciple p -> {model | principle = p}
SetRate r -> {model | rate = r}
SetYears y -> {model | years = y}
SetPeriods p -> {model | periods = p}
Calculate -> calculateNewAmount model
The program Logic
compoundInterest: Float -> Float -> Float -> Float -> Float
compoundInterest principle rate periods years =
(principle * (1 + (rate / periods ) ) ^ (years * periods) )
Converting Strings To Floats
convertToFloat: String -> Float
convertToFloat string =
case String.toFloat string of
Ok n -> n
Err _ -> 0.0
Implement CalculateNewAmount
calculateNewAmount: Model -> Model
calculateNewAmount model =
let
rate = convertToFloat model.rate / 100
years = convertToFloat model.years
principle = convertToFloat model.principle
periods = convertToFloat model.periods
in
{model | newAmount = (compoundInterest principle rate periods years) }
Display the Output
output: Model -> Html
output model =
div [] [
span [] [text "Amount: "],
span [] [text (toString model.newAmount) ]
]
And add it to the view.
Discuss
What are your thoughts?
Is this cool? Good? Bad? A terrible idea or
the greatest thing ever?
Issues
1. Tons of code to do simple things
2. Integration with external services is
complex
3. Must re-learn a lot of things about web
development
4. Small community
Benefits
1. Small community
2. Benefits of React with a clear
opinionated approach
3. Fantastic error messages
4. Types ensure data integrity and flow
Write code
• Elm website: http://elm-lang.org/
• Try Elm http://elm-lang.org/try
• Package system: http://package.elm-
lang.org/
• Documentation http://elm-lang.org/docs
Where to go next?
Book: http://pragprog.com/titles/bhwb
Twitter: @bphogan
Material: http://bphogan.com/
presentations/elm2016/
Thank you!
© Brian Hogan, 2016.
Photos from http://pexels.com
1 of 64

Recommended

Elm intro by
Elm introElm intro
Elm introGonzalo Gabriel Jiménez Fuentes
805 views29 slides
Rethink Frontend Development With Elm by
Rethink Frontend Development With ElmRethink Frontend Development With Elm
Rethink Frontend Development With ElmBrian Hogan
288 views31 slides
Html JavaScript and CSS by
Html JavaScript and CSSHtml JavaScript and CSS
Html JavaScript and CSSRadhe Krishna Rajan
12.9K views60 slides
Print function in PHP by
Print function in PHPPrint function in PHP
Print function in PHPVineet Kumar Saini
2.2K views7 slides
Dynamic HTML Event Model by
Dynamic HTML Event ModelDynamic HTML Event Model
Dynamic HTML Event ModelReem Alattas
4.2K views27 slides
Client side scripting by
Client side scriptingClient side scripting
Client side scriptingEleonora Ciceri
5.4K views106 slides

More Related Content

What's hot

Javascript by
JavascriptJavascript
JavascriptSun Technlogies
2.9K views68 slides
A quick guide to Css and java script by
A quick guide to Css and  java scriptA quick guide to Css and  java script
A quick guide to Css and java scriptAVINASH KUMAR
712 views83 slides
WPF L02-Graphics, Binding and Animation by
WPF L02-Graphics, Binding and AnimationWPF L02-Graphics, Binding and Animation
WPF L02-Graphics, Binding and AnimationMohammad Shaker
7.9K views78 slides
HTML 5 Simple Tutorial Part 4 by
HTML 5 Simple Tutorial Part 4HTML 5 Simple Tutorial Part 4
HTML 5 Simple Tutorial Part 4Sanjeev Kumar
128 views19 slides
1. introduction to html5 by
1. introduction to html51. introduction to html5
1. introduction to html5JayjZens
616 views12 slides
Java script by
Java scriptJava script
Java scriptSanjay Gunjal
54 views36 slides

What's hot(17)

A quick guide to Css and java script by AVINASH KUMAR
A quick guide to Css and  java scriptA quick guide to Css and  java script
A quick guide to Css and java script
AVINASH KUMAR712 views
WPF L02-Graphics, Binding and Animation by Mohammad Shaker
WPF L02-Graphics, Binding and AnimationWPF L02-Graphics, Binding and Animation
WPF L02-Graphics, Binding and Animation
Mohammad Shaker7.9K views
HTML 5 Simple Tutorial Part 4 by Sanjeev Kumar
HTML 5 Simple Tutorial Part 4HTML 5 Simple Tutorial Part 4
HTML 5 Simple Tutorial Part 4
Sanjeev Kumar128 views
1. introduction to html5 by JayjZens
1. introduction to html51. introduction to html5
1. introduction to html5
JayjZens616 views
Javascript by Nagarajan
JavascriptJavascript
Javascript
Nagarajan5.4K views
WPF L01-Layouts, Controls, Styles and Templates by Mohammad Shaker
WPF L01-Layouts, Controls, Styles and TemplatesWPF L01-Layouts, Controls, Styles and Templates
WPF L01-Layouts, Controls, Styles and Templates
Mohammad Shaker3K views
Java Script ppt by Priya Goyal
Java Script pptJava Script ppt
Java Script ppt
Priya Goyal4.5K views
Students Stars by Othaimeen
Students StarsStudents Stars
Students Stars
Othaimeen817 views
Fundamental JavaScript [In Control 2009] by Aaron Gustafson
Fundamental JavaScript [In Control 2009]Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]
Aaron Gustafson3K views
JavaScript Workshop by Pamela Fox
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
Pamela Fox3.4K views
Learn javascript easy steps by prince Loffar
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy steps
prince Loffar5.8K views
Html basics 10 form by H K
Html basics 10 formHtml basics 10 form
Html basics 10 form
H K2.6K views

Viewers also liked

Introduction to Elm by
Introduction to ElmIntroduction to Elm
Introduction to ElmRogerio Chaves
2K views46 slides
My adventure with Elm by
My adventure with ElmMy adventure with Elm
My adventure with ElmYan Cui
10.9K views178 slides
Elm a possible future for web frontend by
Elm   a possible future for web frontendElm   a possible future for web frontend
Elm a possible future for web frontendGaetano Contaldi
557 views56 slides
Claudia Doppioslash - Time Travel for game development with Elm by
Claudia Doppioslash - Time Travel for game development with ElmClaudia Doppioslash - Time Travel for game development with Elm
Claudia Doppioslash - Time Travel for game development with ElmCodemotion
800 views159 slides
Elm: frontend code without runtime exceptions by
Elm: frontend code without runtime exceptionsElm: frontend code without runtime exceptions
Elm: frontend code without runtime exceptionsPietro Grandi
666 views41 slides
Very basic functional design patterns by
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patternsTomasz Kowal
820 views77 slides

Viewers also liked(20)

My adventure with Elm by Yan Cui
My adventure with ElmMy adventure with Elm
My adventure with Elm
Yan Cui10.9K views
Elm a possible future for web frontend by Gaetano Contaldi
Elm   a possible future for web frontendElm   a possible future for web frontend
Elm a possible future for web frontend
Gaetano Contaldi557 views
Claudia Doppioslash - Time Travel for game development with Elm by Codemotion
Claudia Doppioslash - Time Travel for game development with ElmClaudia Doppioslash - Time Travel for game development with Elm
Claudia Doppioslash - Time Travel for game development with Elm
Codemotion800 views
Elm: frontend code without runtime exceptions by Pietro Grandi
Elm: frontend code without runtime exceptionsElm: frontend code without runtime exceptions
Elm: frontend code without runtime exceptions
Pietro Grandi666 views
Very basic functional design patterns by Tomasz Kowal
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patterns
Tomasz Kowal820 views
Elixir and elm - the perfect couple by Tomasz Kowal
Elixir and elm - the perfect coupleElixir and elm - the perfect couple
Elixir and elm - the perfect couple
Tomasz Kowal856 views
Unic - frontend development-in-complex-projects by Unic
Unic - frontend development-in-complex-projectsUnic - frontend development-in-complex-projects
Unic - frontend development-in-complex-projects
Unic2.6K views
Technology independent UI development with JVx by SIB Visions GmbH
Technology independent UI development with JVxTechnology independent UI development with JVx
Technology independent UI development with JVx
SIB Visions GmbH1.2K views
Elm: delightful web development by Amir Barylko
Elm: delightful web developmentElm: delightful web development
Elm: delightful web development
Amir Barylko1K views
Web Frontend development: tools and good practices to (re)organize the chaos by Matteo Papadopoulos
Web Frontend development: tools and good practices to (re)organize the chaosWeb Frontend development: tools and good practices to (re)organize the chaos
Web Frontend development: tools and good practices to (re)organize the chaos
Matteo Papadopoulos1.8K views
Agile IT: Modern Architecture for Rapid Mobile App Development by AnyPresence
Agile IT: Modern Architecture for Rapid Mobile App DevelopmentAgile IT: Modern Architecture for Rapid Mobile App Development
Agile IT: Modern Architecture for Rapid Mobile App Development
AnyPresence1.6K views
Collaborative music with elm and phoenix by Josh Adams
Collaborative music with elm and phoenixCollaborative music with elm and phoenix
Collaborative music with elm and phoenix
Josh Adams581 views
Comparison of Java Web Application Frameworks by Angelin R
Comparison of Java Web Application FrameworksComparison of Java Web Application Frameworks
Comparison of Java Web Application Frameworks
Angelin R5.5K views
Modern Rapid Application Development - Too good to be true by WaveMaker, Inc.
Modern Rapid Application Development - Too good to be trueModern Rapid Application Development - Too good to be true
Modern Rapid Application Development - Too good to be true
WaveMaker, Inc.2K views
Need for Async: Hot pursuit for scalable applications by Konrad Malawski
Need for Async: Hot pursuit for scalable applicationsNeed for Async: Hot pursuit for scalable applications
Need for Async: Hot pursuit for scalable applications
Konrad Malawski6.2K views

Similar to Rethink Frontend Development With Elm

Elm 0.17 at Dublin Elm Meetup May 2016 by
Elm 0.17 at Dublin Elm Meetup May 2016Elm 0.17 at Dublin Elm Meetup May 2016
Elm 0.17 at Dublin Elm Meetup May 2016Michael Twomey
697 views33 slides
Html css by
Html cssHtml css
Html cssJohn Felix
24 views15 slides
JavaScript - Chapter 12 - Document Object Model by
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
5.3K views41 slides
Scripting languages by
Scripting languagesScripting languages
Scripting languagesteach4uin
9.7K views36 slides
Javascript by
JavascriptJavascript
JavascriptD V BHASKAR REDDY
370 views28 slides
Android L01 - Warm Up by
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm UpMohammad Shaker
872 views106 slides

Similar to Rethink Frontend Development With Elm(20)

Elm 0.17 at Dublin Elm Meetup May 2016 by Michael Twomey
Elm 0.17 at Dublin Elm Meetup May 2016Elm 0.17 at Dublin Elm Meetup May 2016
Elm 0.17 at Dublin Elm Meetup May 2016
Michael Twomey697 views
JavaScript - Chapter 12 - Document Object Model by WebStackAcademy
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy5.3K views
Scripting languages by teach4uin
Scripting languagesScripting languages
Scripting languages
teach4uin9.7K views
dotnetConf2019 meetup in AICHI / Elmish by Midoliy
dotnetConf2019 meetup in AICHI / ElmishdotnetConf2019 meetup in AICHI / Elmish
dotnetConf2019 meetup in AICHI / Elmish
Midoliy 593 views
Html5ppt by recroup
Html5pptHtml5ppt
Html5ppt
recroup1.1K views
Python Code Camp for Professionals 4/4 by DEVCON
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
DEVCON 322 views
Build a game with javascript (april 2017) by Thinkful
Build a game with javascript (april 2017)Build a game with javascript (april 2017)
Build a game with javascript (april 2017)
Thinkful352 views
Code camp 2011 Getting Started with IOS, Una Daly by Una Daly
Code camp 2011 Getting Started with IOS, Una DalyCode camp 2011 Getting Started with IOS, Una Daly
Code camp 2011 Getting Started with IOS, Una Daly
Una Daly495 views
Introduzione JQuery by orestJump
Introduzione JQueryIntroduzione JQuery
Introduzione JQuery
orestJump405 views
Build a game with javascript (may 21 atlanta) by Thinkful
Build a game with javascript (may 21 atlanta)Build a game with javascript (may 21 atlanta)
Build a game with javascript (may 21 atlanta)
Thinkful209 views
Web development (html) by AliNaqvi131
Web development (html)Web development (html)
Web development (html)
AliNaqvi131479 views

More from Brian Hogan

Creating and Deploying Static Sites with Hugo by
Creating and Deploying Static Sites with HugoCreating and Deploying Static Sites with Hugo
Creating and Deploying Static Sites with HugoBrian Hogan
1.2K views65 slides
Automating the Cloud with Terraform, and Ansible by
Automating the Cloud with Terraform, and AnsibleAutomating the Cloud with Terraform, and Ansible
Automating the Cloud with Terraform, and AnsibleBrian Hogan
1.8K views80 slides
Create Development and Production Environments with Vagrant by
Create Development and Production Environments with VagrantCreate Development and Production Environments with Vagrant
Create Development and Production Environments with VagrantBrian Hogan
3.5K views43 slides
Docker by
DockerDocker
DockerBrian Hogan
1.2K views86 slides
Getting Started Contributing To Open Source by
Getting Started Contributing To Open SourceGetting Started Contributing To Open Source
Getting Started Contributing To Open SourceBrian Hogan
867 views34 slides
Testing Client-side Code with Jasmine and CoffeeScript by
Testing Client-side Code with Jasmine and CoffeeScriptTesting Client-side Code with Jasmine and CoffeeScript
Testing Client-side Code with Jasmine and CoffeeScriptBrian Hogan
4.9K views59 slides

More from Brian Hogan(20)

Creating and Deploying Static Sites with Hugo by Brian Hogan
Creating and Deploying Static Sites with HugoCreating and Deploying Static Sites with Hugo
Creating and Deploying Static Sites with Hugo
Brian Hogan1.2K views
Automating the Cloud with Terraform, and Ansible by Brian Hogan
Automating the Cloud with Terraform, and AnsibleAutomating the Cloud with Terraform, and Ansible
Automating the Cloud with Terraform, and Ansible
Brian Hogan1.8K views
Create Development and Production Environments with Vagrant by Brian Hogan
Create Development and Production Environments with VagrantCreate Development and Production Environments with Vagrant
Create Development and Production Environments with Vagrant
Brian Hogan3.5K views
Getting Started Contributing To Open Source by Brian Hogan
Getting Started Contributing To Open SourceGetting Started Contributing To Open Source
Getting Started Contributing To Open Source
Brian Hogan867 views
Testing Client-side Code with Jasmine and CoffeeScript by Brian Hogan
Testing Client-side Code with Jasmine and CoffeeScriptTesting Client-side Code with Jasmine and CoffeeScript
Testing Client-side Code with Jasmine and CoffeeScript
Brian Hogan4.9K views
FUD-Free Accessibility for Web Developers - Also, Cake. by Brian Hogan
FUD-Free Accessibility for Web Developers - Also, Cake.FUD-Free Accessibility for Web Developers - Also, Cake.
FUD-Free Accessibility for Web Developers - Also, Cake.
Brian Hogan3.2K views
Responsive Web Design by Brian Hogan
Responsive Web DesignResponsive Web Design
Responsive Web Design
Brian Hogan1.3K views
Web Development with CoffeeScript and Sass by Brian Hogan
Web Development with CoffeeScript and SassWeb Development with CoffeeScript and Sass
Web Development with CoffeeScript and Sass
Brian Hogan9.3K views
Building A Gem From Scratch by Brian Hogan
Building A Gem From ScratchBuilding A Gem From Scratch
Building A Gem From Scratch
Brian Hogan1.4K views
Intro To Advanced Ruby by Brian Hogan
Intro To Advanced RubyIntro To Advanced Ruby
Intro To Advanced Ruby
Brian Hogan2.5K views
Turning Passion Into Words by Brian Hogan
Turning Passion Into WordsTurning Passion Into Words
Turning Passion Into Words
Brian Hogan1.1K views
HTML5 and CSS3 Today by Brian Hogan
HTML5 and CSS3 TodayHTML5 and CSS3 Today
HTML5 and CSS3 Today
Brian Hogan2.2K views
Web Development With Ruby - From Simple To Complex by Brian Hogan
Web Development With Ruby - From Simple To ComplexWeb Development With Ruby - From Simple To Complex
Web Development With Ruby - From Simple To Complex
Brian Hogan4.8K views
Stop Reinventing The Wheel - The Ruby Standard Library by Brian Hogan
Stop Reinventing The Wheel - The Ruby Standard LibraryStop Reinventing The Wheel - The Ruby Standard Library
Stop Reinventing The Wheel - The Ruby Standard Library
Brian Hogan9.8K views
Intro to Ruby by Brian Hogan
Intro to RubyIntro to Ruby
Intro to Ruby
Brian Hogan1.7K views
Intro to Ruby - Twin Cities Code Camp 7 by Brian Hogan
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7
Brian Hogan2.2K views
Make GUI Apps with Shoes by Brian Hogan
Make GUI Apps with ShoesMake GUI Apps with Shoes
Make GUI Apps with Shoes
Brian Hogan10.4K views
Story-driven Testing by Brian Hogan
Story-driven TestingStory-driven Testing
Story-driven Testing
Brian Hogan1.2K views

Recently uploaded

Airline Booking Software by
Airline Booking SoftwareAirline Booking Software
Airline Booking SoftwareSharmiMehta
5 views26 slides
DevsRank by
DevsRankDevsRank
DevsRankdevsrank786
11 views1 slide
Keep by
KeepKeep
KeepGeniusee
75 views10 slides
Headless JS UG Presentation.pptx by
Headless JS UG Presentation.pptxHeadless JS UG Presentation.pptx
Headless JS UG Presentation.pptxJack Spektor
7 views24 slides
Programming Field by
Programming FieldProgramming Field
Programming Fieldthehardtechnology
5 views9 slides
A first look at MariaDB 11.x features and ideas on how to use them by
A first look at MariaDB 11.x features and ideas on how to use themA first look at MariaDB 11.x features and ideas on how to use them
A first look at MariaDB 11.x features and ideas on how to use themFederico Razzoli
45 views36 slides

Recently uploaded(20)

Airline Booking Software by SharmiMehta
Airline Booking SoftwareAirline Booking Software
Airline Booking Software
SharmiMehta5 views
Headless JS UG Presentation.pptx by Jack Spektor
Headless JS UG Presentation.pptxHeadless JS UG Presentation.pptx
Headless JS UG Presentation.pptx
Jack Spektor7 views
A first look at MariaDB 11.x features and ideas on how to use them by Federico Razzoli
A first look at MariaDB 11.x features and ideas on how to use themA first look at MariaDB 11.x features and ideas on how to use them
A first look at MariaDB 11.x features and ideas on how to use them
Federico Razzoli45 views
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut... by Deltares
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...
Deltares7 views
Software evolution understanding: Automatic extraction of software identifier... by Ra'Fat Al-Msie'deen
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...
DSD-INT 2023 Leveraging the results of a 3D hydrodynamic model to improve the... by Deltares
DSD-INT 2023 Leveraging the results of a 3D hydrodynamic model to improve the...DSD-INT 2023 Leveraging the results of a 3D hydrodynamic model to improve the...
DSD-INT 2023 Leveraging the results of a 3D hydrodynamic model to improve the...
Deltares6 views
Advanced API Mocking Techniques by Dimpy Adhikary
Advanced API Mocking TechniquesAdvanced API Mocking Techniques
Advanced API Mocking Techniques
Dimpy Adhikary19 views
Generic or specific? Making sensible software design decisions by Bert Jan Schrijver
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema by Deltares
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - GeertsemaDSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
Deltares17 views
DSD-INT 2023 Delft3D FM Suite 2024.01 2D3D - New features + Improvements - Ge... by Deltares
DSD-INT 2023 Delft3D FM Suite 2024.01 2D3D - New features + Improvements - Ge...DSD-INT 2023 Delft3D FM Suite 2024.01 2D3D - New features + Improvements - Ge...
DSD-INT 2023 Delft3D FM Suite 2024.01 2D3D - New features + Improvements - Ge...
Deltares17 views
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm14 views
Fleet Management Software in India by Fleetable
Fleet Management Software in India Fleet Management Software in India
Fleet Management Software in India
Fleetable11 views
Software testing company in India.pptx by SakshiPatel82
Software testing company in India.pptxSoftware testing company in India.pptx
Software testing company in India.pptx
SakshiPatel827 views
MariaDB stored procedures and why they should be improved by Federico Razzoli
MariaDB stored procedures and why they should be improvedMariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improved

Rethink Frontend Development With Elm

  • 2. About me • I build web things. • I teach people. • I make music. • I write books.
  • 3. Elm is a functional programming language like Haskell, but more friendly, and aimed at front-end web development. We use Elm to make our user interface and give it behavior.
  • 4. Example import Graphics.Element exposing (show) main = show "Hello World"
  • 5. Elm compiles to JavaScript Yes. We just wrote a bunch of code that gets injected into an HTML page. Feel gross yet?
  • 6. That's what React does too. var HelloMessage = React.createClass({ render: function () { return <h1>Hello {this.props.message}!</h1>; } }); React.render(<HelloMessage message="World" />, document.body);
  • 7. Okay, Why Elm? • Same concepts as React • Pure functions • Immutable State • Static Typing
  • 8. What you need • Node.js http://nodejs.org • The elm package for Node $ npm install -g elm • Your favorite text editor OR http://elm-lang.org/try
  • 9. Compiling Elm • Create a hello.elm file • Run $ elm make hello.elm Success! Compiled 1 modules. Successfully generated index.html • Open resulting index.html in your browser.
  • 10. HTML
  • 11. Comparison • Elm: ~5400 lines • React: ~19300 lines • JQuery: ~9800 lines
  • 12. Elm Reactor Elm Reactor compiles Elm to HTML on each request. $ elm-reactor elm reactor 0.16.0 Listening on http://0.0.0.0:8000/
  • 13. How Elm Works Every Elm app calls a main function when we run it. main = -- something goes here
  • 14. Functions We define functions with a name followed by an = sign. hello = "Hello there" We indent the definitions of functions. We invoke this function like this: hello
  • 15. Arguments Functions can have arguments square number = number * number Call it as square 2 They have explicit returns.
  • 16. Multiple Arguments Multiple arguments use spaces: add number1 number2 = number1 + number2 Call it as add 1 2 Woah.... no commas!
  • 17. Type annotations We can enforce data types for our functions so Elm can help us out. functionName: TypeOfArg1-> TypeOfArg2 -> TypeOfArg3 -> ReturnType
  • 18. Annotation Examples: No parameters. Just return value hello: String hello = "Hello there" Two parameters and a return value add: Float -> Float -> Float add number1 number2 = number1 + number2
  • 19. Modules Define modules to group your code. module Hello where main = -- something goes here
  • 20. Html functions The elm-html module exposes many functions for building up virtual DOM nodes. The main function can render HTML if the HTML module is included. import Html exposing(p, text) main = p [] [text "Hello World"]
  • 21. p and text p [] [text "Hello World"] p and text are two functions from elm-html p takes two lists • a list of attributes (can be empty) • a list of child elements text takes a string of text to display.
  • 22. HTML functions are uniform. Each takes attributes and elements. So we can nest them like HTML. div [class "foo", id "bar" ] [ h1 [] [text "Hello"], p [] [text "World"] ] There's a function for every element. Just be sure to expose what you use.
  • 23. Seriously uniform label [for "name"] [text "Name"] input [id "name", type' "number", step "any"] [] Even functions for tags that don't allow inner content still take two lists as arguments.
  • 24. Html Modules • Html contains all the tags • Html.Attributes contains the attributes (like class, id, href, etc) • Html.Events contains events like onClick
  • 25. Html Attributes import Html exposing(Html, div, text, p) import Html.Attributes exposing(class) main = div [class "wrapper"] [ p [class "notice"] [text "This is important!"] ]
  • 26. Composability main = view view: Html view = div [] [ p [] [ text "Hello ", em [] [text "world"] ] ]
  • 27. Resuability main = div [] [ view "Hello", view "Goodbye" ] view: String -> Html view word = div [] [ p [] [ text (word ++ " "), em [] [text "world"] ] ]
  • 28. Web Interfaces import Html exposing(Html, Attribute, p, text) import Html.Attributes exposing(style) elementStyle: Attribute elementStyle = style [ ("color", "red") , ("font-size", "2em") ] main: Html main = view view = p [elementStyle] [text "Hello World"]
  • 29. Helpers! fieldWithLabel: String -> String -> String -> Html fieldWithLabel fieldID fieldName fieldType = div [] [ label [for fieldID] [text fieldName], input [ id fieldID, type' fieldType] [] ]
  • 30. Build Out The Helpers numberField: String -> String -> Html numberField fieldID fieldName = fieldWithLabel fieldID fieldName "number" textField: String -> String -> Html textField fieldID fieldName = fieldWithLabel fieldID fieldName "text" emailField: String -> String -> Html emailField fieldID fieldName = fieldWithLabel fieldID fieldName "email"
  • 31. Shiny Happy Frontend Code main: Html main = div [] [ textField "name" "Name", numberField "age" "Age", emailField "email" "Email" ]
  • 32. Elm Architecture View: Function that fires when model changes. Transofms a model into the UI that people see. Model: Something that holds the current state of the app. No behavior. Just the state. No behavior. This is not MVC with objects! Update: Function that fires when state changes. Always returns a new model.
  • 33. Signals and Mailboxes Signals Signals route messages around the application. Pressing a button is a signal. We can send data along signals. Mailboxes Mailboxes receive signals and send signals. A mailbox has an address and a signal to respond to.
  • 34. Basic Flow • Model is initialized • View is displayed with model • Events send Signals to Mailboxes • Mailboxes trigger updates • New model is created • New view is rendered Yikes!
  • 35. Elm StartApp.Simple Like Flux, without all the code. • Define Actions • Define a model to represent data • Define a view function • Define an update function that returns a new model.
  • 36. Change Text On Click import Html exposing (Html, text, h1, p, div, button) import StartApp.Simple as StartApp import Html.Events exposing (onClick) main = StartApp.start {model = "Hello ", view = view, update = update} view address initialText = div [] [ h1 [] [text "Events"], p [] [ text initialText ], button [onClick address "change"] [text "Push me"] ] update action model = "it changed"
  • 37. Actions Actions get sent to the Update. type Action = Increment | Decrement model = 0 update: Signal.Action -> Int -> Int update action model = case action of Increment -> model + 1 Decrement -> model - 1
  • 38. Multiple events main = StartApp.start { model = model, view = view, update = update } view: Signal.Address Action -> Int -> Html view address model = div [] [ button [ onClick address Increment ] [ text "Up" ] , span [] [ text (toString model) ] , button [ onClick address Decrement ] [ text "Down" ] ]
  • 39. Once again... • StartApp renders the view using an initial model state. • Events defined in the view send Actions to Signal Addresses which route to update. • update returns a new version of the model • StartApp causes the view to be rendered whenever model changes.
  • 40. Calculator Compound Interest Calculator Write a program to compute the value of an investment compounded over time. The program should ask for the starting amount, the number of years to invest, the interest rate, and the number of periods per year to compound.
  • 41. Project setup Create folder and file to work in $ mkdir calculator && cd calculator $ touch calculator.elm Init the project $ elm package install Install HTML and StartApp dependencies. $ elm package install evancz/elm-html $ elm package install evancz/start-app
  • 42. Livereloading Make browser reload when we save $ npm install -g elm-live $ elm-live calculator.elm
  • 43. Steps • Create the basic app • Build the form • Bind form to model and define events • Perform calculations • Display Output
  • 44. The Basic App import Html exposing (Html, text, h1, p, div, button, label, input) import Html.Attributes exposing ( style, for, id, step, type', value) import StartApp.Simple as StartApp import Html.Events exposing (onClick) main = StartApp.start {model = model, view = view, update = update}
  • 45. Define a model and update model: Float model = 0 update: String -> Float -> Float update action model = model
  • 46. Building the form • Use label, input functions • Use number fields • Each field change updates model state • Clicking button calculates new amount
  • 47. numberField helper numberField: String -> String -> Html numberField fieldID fieldName = div [] [ label [for fieldID] [text fieldName], input [ id fieldID, type' "number", step "any"] [] ]
  • 48. Style the form labelStyle: Attribute labelStyle = style [ ("width", "200px") , ("padding", "10px") , ("text-align", "right") , ("display", "inline-block") ]
  • 49. Apply style to field div [] [ label [labelStyle, for fieldID] [text fieldName], input [ id fieldID, type' "number", step "any"] [] ]
  • 50. Build the View view: Signal.Address String -> Float -> Html view address model = div [] [ h1 [] [text "Calculator"], div [] [ numberField "principal" "Principal", numberField "rate" "Rate", numberField "years" "Periods", numberField "years" "Years" ] button [onClick address "calculate"] [text "Calculate"] ]
  • 51. Define Our Actions type Action = NoOp | SetPrinciple String | SetPeriods String | SetRate String | SetYears String | Calculate
  • 52. Define A Model type alias Model = { principle: String , rate: String , years: String , periods: String , newAmount: Float} model: Model model = { principle = "1500.00" , rate = "4.3" , years = "6" , periods = "4" , newAmount = 0 }
  • 53. Pass address, action, and model data to fields view: Signal.Address Action -> Model -> Html view address model = div [] [ h1 [] [text "Calculator"], div [] [ numberField address SetPrinciple "principle" "Principle" model.principle, numberField address SetRate "rate" "Rate" model.rate, numberField address SetPeriods "periods" "Periods" model.periods, numberField address SetYears "years" "Years" model.years ], button [onClick address Calculate] [text "Click me"],
  • 54. Add Events To Form using Actions and model data numberField: Signal.Address Action -> (String -> Action) -> String -> String -> String -> Html numberField address action fieldID name fieldValue = div [] [ label [labelStyle, for fieldID] [text name], input [id fieldID, type' "number", step "any", on "input" targetValue (Signal.message address << action ), value fieldValue] [] ]
  • 55. Update model from form update: Action -> Model -> Model update action model = case action of NoOp -> model SetPrinciple p -> {model | principle = p} SetRate r -> {model | rate = r} SetYears y -> {model | years = y} SetPeriods p -> {model | periods = p} Calculate -> calculateNewAmount model
  • 56. The program Logic compoundInterest: Float -> Float -> Float -> Float -> Float compoundInterest principle rate periods years = (principle * (1 + (rate / periods ) ) ^ (years * periods) )
  • 57. Converting Strings To Floats convertToFloat: String -> Float convertToFloat string = case String.toFloat string of Ok n -> n Err _ -> 0.0
  • 58. Implement CalculateNewAmount calculateNewAmount: Model -> Model calculateNewAmount model = let rate = convertToFloat model.rate / 100 years = convertToFloat model.years principle = convertToFloat model.principle periods = convertToFloat model.periods in {model | newAmount = (compoundInterest principle rate periods years) }
  • 59. Display the Output output: Model -> Html output model = div [] [ span [] [text "Amount: "], span [] [text (toString model.newAmount) ] ] And add it to the view.
  • 60. Discuss What are your thoughts? Is this cool? Good? Bad? A terrible idea or the greatest thing ever?
  • 61. Issues 1. Tons of code to do simple things 2. Integration with external services is complex 3. Must re-learn a lot of things about web development 4. Small community
  • 62. Benefits 1. Small community 2. Benefits of React with a clear opinionated approach 3. Fantastic error messages 4. Types ensure data integrity and flow
  • 63. Write code • Elm website: http://elm-lang.org/ • Try Elm http://elm-lang.org/try • Package system: http://package.elm- lang.org/ • Documentation http://elm-lang.org/docs
  • 64. Where to go next? Book: http://pragprog.com/titles/bhwb Twitter: @bphogan Material: http://bphogan.com/ presentations/elm2016/ Thank you! © Brian Hogan, 2016. Photos from http://pexels.com