SlideShare ist ein Scribd-Unternehmen logo
1 von 30
MILAN - 08TH OF MAY - 2015
PARTNERS
Hands on ScalaJS
Alberto Paro
Engineer from Politecnico of Milan
Working at Big Data Technologies + Consulting
Author of two ElasticSearch books.
Mainly working in Scala (Akka, Spray.io, Playframework, Apache Spark)
Developed big application with Scala.JS
Alberto Paro
Table Of Contents
Background information
Why Scala.JS
SBT
Libraries
Tricks and Tips
Questions
1. Why Scala.Js?
Why I don’t like Javascript
• A lot of language “defects”
• It’s a script language, not designed to scale large applications (SPA or many modules)
• IDEs are good, but no refactory available
• Hard to be used for large projects
• Verbose if you want safe code.
• Coffescript and similar (Any => Js) try to simplify it.
• A lot of language compiles to javascript (Coffeescript, Microsoft typescript, …)
https://github.com/jashkenas/coffeescript/wiki/List-of-languages-that-compile-to-JS
What’s Scala.JS
"Scala.js is a compiler that converts Scala code into the equivalent, executable Javascript”
Write Scala, not Javascript
The compiler handles the rest
It brings the advantages of Scala into client web development.
Support of “all” Scala (also macros)
Easy interoperability with Javascript
SBT integration
IDE support as “standard” Scala language
Compiled code is reasonable small (GCC => Google Closure Compiler)
SourceMaps for easy debug in Web browser
Interoperability with Javascript (JS => ScalaJS , ScalaJS => JS)
Scala.js code calls Javascript
Scala.js can export classes and methods to Javascript
Scala.js Compiler Pipeline
Main.class
Main$.class
Main.Scala
Main.sjsir
Main$.sjsir
script- fastopt.js
500k - 3000Kb
script- opt.js
100k - 1000kb
Scalac
Scala.js
Plugin
Optimizer
Renderer
Google C
C
On developing Web Apps
No code reuse between client and server
A least you must learn two languages (Scala + JS)
Algorithms and models must be rewritten
RCP/Ajax calls with “no type”
No compiler checks
Javascript issues:
Forgot a “var”
Js => [“10”, “10”, “10”, “10”].map(parseInt)
[10, NaN, 2, 3]
['10','10','10','10','10'].map(function(x){return
parseInt(x);})
On developing Web Apps with Scala.js
Application in only one language
and the language is Scala
Strong typing in the application and RCP layer
Autowire library
Scala typesafe
document.getElementByld(“foo”)
“Standard” behavior
scala.js> List("10", "10", "10", "10").map(parseInt)
List(10, 10, 10, 10)
…
Some Semantic differences from JS
• Division by 0 doesn’t throw exception
• Checking the type of number is based on its numeric value, not class instance.
• Scala.Unit is represented as undefined in Javascript
• JavaScript regular expressions are slightly different from Java regular expressions.
• Different behavior of some exceptions
Javascript VM != Java VM
2. SBT
name := "Foo root project”
lazy val root = project.in(file(".")).
aggregate(fooJS, fooJVM).
settings(publish := {},
publishLocal := {})
lazy val foo = crossProject.in(file(".")).
settings(
name := "foo",
version := "0.1-SNAPSHOT",
scalaVersion := "2.11.6”,
libraryDependencies += "com.lihaoyi" %%% "scalatags" % "0.4.3"
).
jvmSettings(
// Add JVM-specific settings here
).
jsSettings(
// Add JS-specific settings here )
lazy val fooJVM = foo.jvm
lazy val fooJS = foo.js
Simple multi target JS/JVM
SBT configuration for ScalaJS
<project root>
+- jvm
| +- src/main/scala
+- js
| +- src/main/scala
+- shared
+- src/main/scala
3. Libraries
Type safe RPC between client and server
API trait in shared code
Server code implement the backend code
Client calls in a type safe way
// shared interface
trait Api{
def add(x: Int, y: Int, z: Int): Int
}
Safe Server Client Communication
AutoWire
// server-side router and implementation
object Server extends autowire.Server...
object ApiImpl extends Api
def add(x: Int, y: Int, z: Int) = x + y + z
}
// client-side callsite
import autowire._ // needed for correct macro application
object Client extends autowire.Client...
Client[Api].add(1, 2, 3).call(): Future[Int]
// | | |
// | | The T is pickled and wrapped in a Future[T]
// | The arguments to that method are pickled automatically
// Call a method on the `Api` trait
https://github.com/lihaoyi/scalatags
libraryDependencies += "com.lihaoyi" %%% "scalatags" % "0.5.1”
ScalaTags is a small XML/HTML construction library for Scala.
Since ScalaTags is pure Scala, any editor that understands Scala will understand scalatags.
Not only do you get syntax highlighting, you also get code completion:
• Autocomplete
• Error Highlighting
• In-editor documentation:
And all the other good things (jump to definition, extract method, etc.) you're used to in a statically typed
language.
No more digging around in templates which mess up the highlighting of your HTML editor, or waiting
months for the correct plugin to materialize.
Strong Typed HTML Syntax for JVM/JS
Scala Tags
Strong Typed HTML Syntax for JVM/JS
Scala Tags - Example
html(
head(
script(src:="..."),
script(
"alert('Hello World')"
)
),
body(
div(
h1(id:="title", "This is a title"),
p("This is a big paragraph of text")
)
)
)
<html>
<head>
<script src="..."></script>
<script>alert('Hello World')</script>
</head>
<body>
<div>
<h1 id="title">This is a title</h1>
<p>This is a big paragraph of text</p>
</div>
</body>
</html>
https://github.com/greencatsoft/scalajs-angular
libraryDependencies += "com.greencatsoft" %%% "scalajs-angular" % "0.4”
“scalajs-angular aims to help developers build AngularJS based applications in type safe manner with
Scala language.”
Schermata 2015-04-26 alle 10.56.47.png
AngulaJS - scalajs-angular 1/2
It provides annotation helper for AngularJS Services, Controllers, Directives, and Filters.
It wraps ngRoute for routing in your SPA.
Schermata 2015-04-26 alle 10.56.47.png
AngulaJS - scalajs-angular 2/2
https://github.com/jokade/scalajs-angulate
libraryDependencies += "biz.enef" %%% "scalajs-angulate" % "0.1”
“scalajs-angulate is a small library to simplify developing AngularJS applications in Scala (via Scala.js).
To this end it provides:
• façade traits for the Angular core API
• macros for defining controllers, services and directives in a more natural Scala style”
val module = angular.createModule("counter")
module.controllerOf[CounterCtrl]
class CounterCtrl extends Controller {
var count = 0
def inc() = count += 1
def dec() = count -= 1
// private properties and functions are not exported to the controller scope
private def foo() : Unit = ...
}
AngulaJS - scalajs-angulate 1/2
It can be called in a similar HTML fragment:
<html ng-app="counter">
<body>
<div ng-controller="App.CounterCtrl as ctrl">
Count: {{ctrl.count}} <button ng-click="ctrl.inc()">+</button> <button ng-click="ctrl.dec()">&ndash;</button>
</div>
<!-- ... -->
</body>
</html>
Schermata 2015-04-26 alle 10.56.47.png
AngulaJS - scalajs-angulate 2/2
I love ReactJS because:
• Your code is clear. It is arranged into components, each with its own defined responsibility. (Web
component, better dividi-et-impera approach)
• Your app is predictable. It’s very clear where data flows, and what happens when a user does
something.
• Your app is fast. React is really, really fast, creating a better experience for users, even if you have a
ton of data. (Virtual DOM, …)
• Your app is standards-based. React adds layers only when it needs to. You feel like you are actually
writing JavaScript and HTML, not some magic template language.
• Surprise, you’re an app developer. React breaks down barriers across platforms, by applying its
same model across the board. This means that once you learn the React way of structuring an web
application, you have a huge head start on developing a native iOS or Android app, thanks to react-
native. Surely this will happen to other platforms.Schermata 2015-04-26 alle 10.56.47.png
Scala Js - React
http://aspiringwebdev.com/why-react-js-matters-for-developers/
I love ScalaJS ReactJS because:
• It composed by simple concepts:
• Properties (Props) are immutable
• State is mutable
• a render method
• Everything is strong typed: VDOM,
Components
• Easy to extend components• Schermata 2015-04-26 alle 10.56.47.png
Scala Js - React
Javascript
var HelloMessage = React.createClass({displayName:
'HelloMessage',
render: function() {
return React.createElement("div", null, "Hello ",
this.props.name);
}
});
React.render(React.createElement(HelloMessage, {name:
”Alberto"}), mountNode);• Schermata 2015-04-26 alle 10.56.47.png
Scala
val HelloMessage =
ReactComponentB[String]("HelloMessage")
.render(name => <.div("Hello ", name))
.build
React.render(HelloMessage(”Alberto"), mountNode)Schermata 2015-04-26 alle 10.56.47.png
https://github.com/japgolly/scalajs-react
http://japgolly.github.io/scalajs-react/
Scala
Scala Js - React
https://github.com/japgolly/scalajs-react
http://japgolly.github.io/scalajs-react/
ScalaJS React provide also many extra:
• Scalaz support ("com.github.japgolly.scalajs-react" %%% "ext-scalaz71" % "0.8.4")
• Monocle support (Lens for case class) ("com.github.japgolly.scalajs-react" %%% "ext-monocle" %
"0.8.4")
• Testing support ("com.github.japgolly.scalajs-react" %%% "test" % "0.8.4" % "test")
val s = Simulation.focus >> ChangeEventData("hi").simulation >> Simulation.blur
• Module extra ("com.github.japgolly.scalajs-react" %%% "extra" % "0.8.4") with
 Router
 Component Mixins:
 Broadcaster and Listenable
 ExternalVar
 LogLifecycle
 OnUmount
 SetInterval
Scala
Scala CSS - CSS Type Safe!
https://github.com/japgolly/scalacss
http://japgolly.github.io/scalacss/book/
ScalaCSS aims to bring type-safety and clarity to:
• creating CSS
• using CSS
• maintaining CSS
• correctness of CSS
You can create standalone CSS like SCSS/LESS, or you can create inline styles to be applied to
directly without the need to manually manage class names.
Being 100% Scala, you benefit from all the normal type-aware advantages like jump-to-definition of a
style, type-safe keys and values, worry-free refactoring, etc.
Example: http://japgolly.github.io/scalacss/book/quickstart/standalone.html
Scala
Other Libraries Links
A lot of libraries are linked in Scala.js Homepage (http://www.scala-js.org/)
For a complete projects, the best resources are:
- SPA Tutorial (https://github.com/ochrons/scalajs-spa-tutorial) with doc
(http://ochrons.github.io/scalajs-spa-tutorial/css-in-scala.html):
- Spray
- Autowire
- Scala.JS React
- Scala CSS
- Deploy
- Querki (https://github.com/jducoeur/Querki)
- Scala.Js jquery
- Facades
- Play Scala.Js Example (https://github.com/hussachai/play-scalajs-showcase)
- Gitter Channels
4. Tips & Tricks
To manage the javascript library, Scala needs the code signature of the Javascript methods.
First search on scala.js site or github scalajs
trait JQuery extends js.Object {
/**
* Adds the specified class(es) to each of the set of matched elements.
*/
def addClass(classNames:String):JQuery = js.native
def addClass(func:js.ThisFunction2[Element, Int, String, String]):JQuery = js.native
@JSName("after")
def afterInternal(content:js.Any):JQuery = js.native
@JSName("append")
def appendInternal(content:js.Any*):JQuery = js.native
@JSName("appendTo")
def appendToInternal(target:js.Any):JQuery = js.native
@JSName("attr")
def attrInternal(attributeName:String):UndefOr[String] = js.native
Facading Javascript Libraries
$(“div#myId”).addClass("m
yclass")
“Automatically” bootstrap your façade from a typescript definition
(https://github.com/borisyankov/DefinitelyTyped): ~900 library already “typed”.
The process is not 100 % accurate, so manual editing is often needed afterwards. This can be improved,
but not to perfection, because the features offered by the type systems of TypeScript and Scala.js differ in
some subtle ways.
Usage
$ sbt 'run somelib.d.ts SomeLib.scala'
Facading Javascript Libraries
https://github.com/sjrd/scala-js-ts-importer
5. Questions
MILAN - 08TH OF MAY - 2015
PARTNERS
THANK YOU!
Alberto Paro
alberto.paro@gmail.com
@aparo77
PARTNERS

Weitere ähnliche Inhalte

Was ist angesagt?

Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developersYakov Fain
 
Ruby On Rails Tutorial
Ruby On Rails TutorialRuby On Rails Tutorial
Ruby On Rails Tutorialsunniboy
 
Android Auto instrumentation
Android Auto instrumentationAndroid Auto instrumentation
Android Auto instrumentationPrzemek Jakubczyk
 
Practices and Tools for Building Better APIs
Practices and Tools for Building Better APIsPractices and Tools for Building Better APIs
Practices and Tools for Building Better APIsPeter Hendriks
 
JavaFX Versus HTML5 - JavaOne 2014
JavaFX Versus HTML5 - JavaOne 2014JavaFX Versus HTML5 - JavaOne 2014
JavaFX Versus HTML5 - JavaOne 2014Ryan Cuprak
 
[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JSIvano Malavolta
 
Sling models by Justin Edelson
Sling models by Justin Edelson Sling models by Justin Edelson
Sling models by Justin Edelson AEM HUB
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework Yakov Fain
 
Introduction to React Native
Introduction to React NativeIntroduction to React Native
Introduction to React NativeRami Sayar
 
Eclipse e4 on Java Forum Stuttgart 2010
Eclipse e4 on Java Forum Stuttgart 2010Eclipse e4 on Java Forum Stuttgart 2010
Eclipse e4 on Java Forum Stuttgart 2010Lars Vogel
 
JavaFX Enterprise (JavaOne 2014)
JavaFX Enterprise (JavaOne 2014)JavaFX Enterprise (JavaOne 2014)
JavaFX Enterprise (JavaOne 2014)Hendrik Ebbers
 
3 rad extensibility-srilakshmi_s_rajesh_k
3 rad extensibility-srilakshmi_s_rajesh_k3 rad extensibility-srilakshmi_s_rajesh_k
3 rad extensibility-srilakshmi_s_rajesh_kIBM
 
JavaFX in Action (devoxx'16)
JavaFX in Action (devoxx'16)JavaFX in Action (devoxx'16)
JavaFX in Action (devoxx'16)Alexander Casall
 
An Introduction to Play 2 Framework
An Introduction to Play 2 FrameworkAn Introduction to Play 2 Framework
An Introduction to Play 2 FrameworkPT.JUG
 
Sling Models Using Sightly and JSP by Deepak Khetawat
Sling Models Using Sightly and JSP by Deepak KhetawatSling Models Using Sightly and JSP by Deepak Khetawat
Sling Models Using Sightly and JSP by Deepak KhetawatAEM HUB
 
Presentation - Course about JavaFX
Presentation - Course about JavaFXPresentation - Course about JavaFX
Presentation - Course about JavaFXTom Mix Petreca
 
AEM and Sling
AEM and SlingAEM and Sling
AEM and SlingLo Ki
 
Advanced iOS Debbuging (Reloaded)
Advanced iOS Debbuging (Reloaded)Advanced iOS Debbuging (Reloaded)
Advanced iOS Debbuging (Reloaded)Massimo Oliviero
 

Was ist angesagt? (20)

Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developers
 
Ruby On Rails Tutorial
Ruby On Rails TutorialRuby On Rails Tutorial
Ruby On Rails Tutorial
 
Android Auto instrumentation
Android Auto instrumentationAndroid Auto instrumentation
Android Auto instrumentation
 
OmniFaces validators
OmniFaces validatorsOmniFaces validators
OmniFaces validators
 
Practices and Tools for Building Better APIs
Practices and Tools for Building Better APIsPractices and Tools for Building Better APIs
Practices and Tools for Building Better APIs
 
JavaFX Versus HTML5 - JavaOne 2014
JavaFX Versus HTML5 - JavaOne 2014JavaFX Versus HTML5 - JavaOne 2014
JavaFX Versus HTML5 - JavaOne 2014
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS
 
Sling models by Justin Edelson
Sling models by Justin Edelson Sling models by Justin Edelson
Sling models by Justin Edelson
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework
 
Introduction to React Native
Introduction to React NativeIntroduction to React Native
Introduction to React Native
 
Eclipse e4 on Java Forum Stuttgart 2010
Eclipse e4 on Java Forum Stuttgart 2010Eclipse e4 on Java Forum Stuttgart 2010
Eclipse e4 on Java Forum Stuttgart 2010
 
JavaFX Enterprise (JavaOne 2014)
JavaFX Enterprise (JavaOne 2014)JavaFX Enterprise (JavaOne 2014)
JavaFX Enterprise (JavaOne 2014)
 
3 rad extensibility-srilakshmi_s_rajesh_k
3 rad extensibility-srilakshmi_s_rajesh_k3 rad extensibility-srilakshmi_s_rajesh_k
3 rad extensibility-srilakshmi_s_rajesh_k
 
JavaFX in Action (devoxx'16)
JavaFX in Action (devoxx'16)JavaFX in Action (devoxx'16)
JavaFX in Action (devoxx'16)
 
An Introduction to Play 2 Framework
An Introduction to Play 2 FrameworkAn Introduction to Play 2 Framework
An Introduction to Play 2 Framework
 
Sling Models Using Sightly and JSP by Deepak Khetawat
Sling Models Using Sightly and JSP by Deepak KhetawatSling Models Using Sightly and JSP by Deepak Khetawat
Sling Models Using Sightly and JSP by Deepak Khetawat
 
Presentation - Course about JavaFX
Presentation - Course about JavaFXPresentation - Course about JavaFX
Presentation - Course about JavaFX
 
AEM and Sling
AEM and SlingAEM and Sling
AEM and Sling
 
Advanced iOS Debbuging (Reloaded)
Advanced iOS Debbuging (Reloaded)Advanced iOS Debbuging (Reloaded)
Advanced iOS Debbuging (Reloaded)
 

Andere mochten auch

Complexity is Outside the Code - Craft Conference
Complexity is Outside the Code - Craft ConferenceComplexity is Outside the Code - Craft Conference
Complexity is Outside the Code - Craft Conferencejessitron
 
Origami, a monadic fold library for Scala
Origami, a monadic fold library for ScalaOrigami, a monadic fold library for Scala
Origami, a monadic fold library for ScalaEric Torreborre
 
The Need for Async @ ScalaWorld
The Need for Async @ ScalaWorldThe Need for Async @ ScalaWorld
The Need for Async @ ScalaWorldKonrad Malawski
 
Simplify Cloud Applications using Spring Cloud
Simplify Cloud Applications using Spring CloudSimplify Cloud Applications using Spring Cloud
Simplify Cloud Applications using Spring CloudRamnivas Laddad
 
OrientDB Distributed Architecture v2.0
OrientDB Distributed Architecture v2.0OrientDB Distributed Architecture v2.0
OrientDB Distributed Architecture v2.0Orient Technologies
 
Akka Streams and HTTP
Akka Streams and HTTPAkka Streams and HTTP
Akka Streams and HTTPRoland Kuhn
 

Andere mochten auch (6)

Complexity is Outside the Code - Craft Conference
Complexity is Outside the Code - Craft ConferenceComplexity is Outside the Code - Craft Conference
Complexity is Outside the Code - Craft Conference
 
Origami, a monadic fold library for Scala
Origami, a monadic fold library for ScalaOrigami, a monadic fold library for Scala
Origami, a monadic fold library for Scala
 
The Need for Async @ ScalaWorld
The Need for Async @ ScalaWorldThe Need for Async @ ScalaWorld
The Need for Async @ ScalaWorld
 
Simplify Cloud Applications using Spring Cloud
Simplify Cloud Applications using Spring CloudSimplify Cloud Applications using Spring Cloud
Simplify Cloud Applications using Spring Cloud
 
OrientDB Distributed Architecture v2.0
OrientDB Distributed Architecture v2.0OrientDB Distributed Architecture v2.0
OrientDB Distributed Architecture v2.0
 
Akka Streams and HTTP
Akka Streams and HTTPAkka Streams and HTTP
Akka Streams and HTTP
 

Ähnlich wie Scala Italy 2015 - Hands On ScalaJS

Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Codemotion
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayLuka Zakrajšek
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaKazuhiro Sera
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scalascalaconfjp
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java DevelopersYakov Fain
 
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..Mark Rackley
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsSebastian Springer
 
Scala Frustrations
Scala FrustrationsScala Frustrations
Scala Frustrationstakezoe
 
React & Redux JS
React & Redux JS React & Redux JS
React & Redux JS Hamed Farag
 
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)Daniel Bryant
 
Lessons Learned: Scala and its Ecosystem
Lessons Learned: Scala and its EcosystemLessons Learned: Scala and its Ecosystem
Lessons Learned: Scala and its EcosystemPetr Hošek
 
Challenges of angular in production (Tasos Bekos) - GreeceJS #17
Challenges of angular in production (Tasos Bekos) - GreeceJS #17Challenges of angular in production (Tasos Bekos) - GreeceJS #17
Challenges of angular in production (Tasos Bekos) - GreeceJS #17GreeceJS
 
Rad Extensibility - Srilakshmi S Rajesh K
Rad Extensibility - Srilakshmi S Rajesh KRad Extensibility - Srilakshmi S Rajesh K
Rad Extensibility - Srilakshmi S Rajesh KRoopa Nadkarni
 

Ähnlich wie Scala Italy 2015 - Hands On ScalaJS (20)

Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in Scala
 
Scala at Netflix
Scala at NetflixScala at Netflix
Scala at Netflix
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scala
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java Developers
 
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
 
Full Stack Scala
Full Stack ScalaFull Stack Scala
Full Stack Scala
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.js
 
Scala Frustrations
Scala FrustrationsScala Frustrations
Scala Frustrations
 
React & Redux JS
React & Redux JS React & Redux JS
React & Redux JS
 
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
Lessons Learned: Scala and its Ecosystem
Lessons Learned: Scala and its EcosystemLessons Learned: Scala and its Ecosystem
Lessons Learned: Scala and its Ecosystem
 
Challenges of angular in production (Tasos Bekos) - GreeceJS #17
Challenges of angular in production (Tasos Bekos) - GreeceJS #17Challenges of angular in production (Tasos Bekos) - GreeceJS #17
Challenges of angular in production (Tasos Bekos) - GreeceJS #17
 
Rad Extensibility - Srilakshmi S Rajesh K
Rad Extensibility - Srilakshmi S Rajesh KRad Extensibility - Srilakshmi S Rajesh K
Rad Extensibility - Srilakshmi S Rajesh K
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 

Mehr von Alberto Paro

LUISS - Deep Learning and data analyses - 09/01/19
LUISS - Deep Learning and data analyses - 09/01/19LUISS - Deep Learning and data analyses - 09/01/19
LUISS - Deep Learning and data analyses - 09/01/19Alberto Paro
 
2018 07-11 - kafka integration patterns
2018 07-11 - kafka integration patterns2018 07-11 - kafka integration patterns
2018 07-11 - kafka integration patternsAlberto Paro
 
Elasticsearch in architetture Big Data - EsInADay-2017
Elasticsearch in architetture Big Data - EsInADay-2017Elasticsearch in architetture Big Data - EsInADay-2017
Elasticsearch in architetture Big Data - EsInADay-2017Alberto Paro
 
2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locatorAlberto Paro
 
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
ElasticSearch 5.x -  New Tricks - 2017-02-08 - Elasticsearch Meetup ElasticSearch 5.x -  New Tricks - 2017-02-08 - Elasticsearch Meetup
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup Alberto Paro
 
2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locatorAlberto Paro
 
2016 02-24 - Piattaforme per i Big Data
2016 02-24 - Piattaforme per i Big Data2016 02-24 - Piattaforme per i Big Data
2016 02-24 - Piattaforme per i Big DataAlberto Paro
 
What's Big Data? - Big Data Tech - 2015 - Firenze
What's Big Data? - Big Data Tech - 2015 - FirenzeWhat's Big Data? - Big Data Tech - 2015 - Firenze
What's Big Data? - Big Data Tech - 2015 - FirenzeAlberto Paro
 
ElasticSearch Meetup 30 - 10 - 2014
ElasticSearch Meetup 30 - 10 - 2014ElasticSearch Meetup 30 - 10 - 2014
ElasticSearch Meetup 30 - 10 - 2014Alberto Paro
 

Mehr von Alberto Paro (10)

Data streaming
Data streamingData streaming
Data streaming
 
LUISS - Deep Learning and data analyses - 09/01/19
LUISS - Deep Learning and data analyses - 09/01/19LUISS - Deep Learning and data analyses - 09/01/19
LUISS - Deep Learning and data analyses - 09/01/19
 
2018 07-11 - kafka integration patterns
2018 07-11 - kafka integration patterns2018 07-11 - kafka integration patterns
2018 07-11 - kafka integration patterns
 
Elasticsearch in architetture Big Data - EsInADay-2017
Elasticsearch in architetture Big Data - EsInADay-2017Elasticsearch in architetture Big Data - EsInADay-2017
Elasticsearch in architetture Big Data - EsInADay-2017
 
2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator
 
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
ElasticSearch 5.x -  New Tricks - 2017-02-08 - Elasticsearch Meetup ElasticSearch 5.x -  New Tricks - 2017-02-08 - Elasticsearch Meetup
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
 
2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator
 
2016 02-24 - Piattaforme per i Big Data
2016 02-24 - Piattaforme per i Big Data2016 02-24 - Piattaforme per i Big Data
2016 02-24 - Piattaforme per i Big Data
 
What's Big Data? - Big Data Tech - 2015 - Firenze
What's Big Data? - Big Data Tech - 2015 - FirenzeWhat's Big Data? - Big Data Tech - 2015 - Firenze
What's Big Data? - Big Data Tech - 2015 - Firenze
 
ElasticSearch Meetup 30 - 10 - 2014
ElasticSearch Meetup 30 - 10 - 2014ElasticSearch Meetup 30 - 10 - 2014
ElasticSearch Meetup 30 - 10 - 2014
 

Kürzlich hochgeladen

Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Delhi Call girls
 
Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...shambhavirathore45
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxolyaivanovalion
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxfirstjob4
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAroojKhan71
 
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxBPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxMohammedJunaid861692
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% SecurePooja Nehwal
 
Zuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptxZuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptxolyaivanovalion
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxolyaivanovalion
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxolyaivanovalion
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxolyaivanovalion
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...amitlee9823
 
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdfAccredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdfadriantubila
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...amitlee9823
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysismanisha194592
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023ymrp368
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 

Kürzlich hochgeladen (20)

Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
 
Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptx
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
 
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxBPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts ServiceCall Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
 
Zuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptxZuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptx
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptx
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptx
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptx
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdfAccredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
 
Sampling (random) method and Non random.ppt
Sampling (random) method and Non random.pptSampling (random) method and Non random.ppt
Sampling (random) method and Non random.ppt
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 

Scala Italy 2015 - Hands On ScalaJS

  • 1. MILAN - 08TH OF MAY - 2015 PARTNERS Hands on ScalaJS Alberto Paro
  • 2. Engineer from Politecnico of Milan Working at Big Data Technologies + Consulting Author of two ElasticSearch books. Mainly working in Scala (Akka, Spray.io, Playframework, Apache Spark) Developed big application with Scala.JS Alberto Paro
  • 3. Table Of Contents Background information Why Scala.JS SBT Libraries Tricks and Tips Questions
  • 5. Why I don’t like Javascript • A lot of language “defects” • It’s a script language, not designed to scale large applications (SPA or many modules) • IDEs are good, but no refactory available • Hard to be used for large projects • Verbose if you want safe code. • Coffescript and similar (Any => Js) try to simplify it. • A lot of language compiles to javascript (Coffeescript, Microsoft typescript, …) https://github.com/jashkenas/coffeescript/wiki/List-of-languages-that-compile-to-JS
  • 6. What’s Scala.JS "Scala.js is a compiler that converts Scala code into the equivalent, executable Javascript” Write Scala, not Javascript The compiler handles the rest It brings the advantages of Scala into client web development. Support of “all” Scala (also macros) Easy interoperability with Javascript SBT integration IDE support as “standard” Scala language Compiled code is reasonable small (GCC => Google Closure Compiler) SourceMaps for easy debug in Web browser Interoperability with Javascript (JS => ScalaJS , ScalaJS => JS) Scala.js code calls Javascript Scala.js can export classes and methods to Javascript
  • 7. Scala.js Compiler Pipeline Main.class Main$.class Main.Scala Main.sjsir Main$.sjsir script- fastopt.js 500k - 3000Kb script- opt.js 100k - 1000kb Scalac Scala.js Plugin Optimizer Renderer Google C C
  • 8. On developing Web Apps No code reuse between client and server A least you must learn two languages (Scala + JS) Algorithms and models must be rewritten RCP/Ajax calls with “no type” No compiler checks Javascript issues: Forgot a “var” Js => [“10”, “10”, “10”, “10”].map(parseInt) [10, NaN, 2, 3] ['10','10','10','10','10'].map(function(x){return parseInt(x);})
  • 9. On developing Web Apps with Scala.js Application in only one language and the language is Scala Strong typing in the application and RCP layer Autowire library Scala typesafe document.getElementByld(“foo”) “Standard” behavior scala.js> List("10", "10", "10", "10").map(parseInt) List(10, 10, 10, 10) …
  • 10. Some Semantic differences from JS • Division by 0 doesn’t throw exception • Checking the type of number is based on its numeric value, not class instance. • Scala.Unit is represented as undefined in Javascript • JavaScript regular expressions are slightly different from Java regular expressions. • Different behavior of some exceptions Javascript VM != Java VM
  • 12. name := "Foo root project” lazy val root = project.in(file(".")). aggregate(fooJS, fooJVM). settings(publish := {}, publishLocal := {}) lazy val foo = crossProject.in(file(".")). settings( name := "foo", version := "0.1-SNAPSHOT", scalaVersion := "2.11.6”, libraryDependencies += "com.lihaoyi" %%% "scalatags" % "0.4.3" ). jvmSettings( // Add JVM-specific settings here ). jsSettings( // Add JS-specific settings here ) lazy val fooJVM = foo.jvm lazy val fooJS = foo.js Simple multi target JS/JVM SBT configuration for ScalaJS <project root> +- jvm | +- src/main/scala +- js | +- src/main/scala +- shared +- src/main/scala
  • 14. Type safe RPC between client and server API trait in shared code Server code implement the backend code Client calls in a type safe way // shared interface trait Api{ def add(x: Int, y: Int, z: Int): Int } Safe Server Client Communication AutoWire // server-side router and implementation object Server extends autowire.Server... object ApiImpl extends Api def add(x: Int, y: Int, z: Int) = x + y + z } // client-side callsite import autowire._ // needed for correct macro application object Client extends autowire.Client... Client[Api].add(1, 2, 3).call(): Future[Int] // | | | // | | The T is pickled and wrapped in a Future[T] // | The arguments to that method are pickled automatically // Call a method on the `Api` trait
  • 15. https://github.com/lihaoyi/scalatags libraryDependencies += "com.lihaoyi" %%% "scalatags" % "0.5.1” ScalaTags is a small XML/HTML construction library for Scala. Since ScalaTags is pure Scala, any editor that understands Scala will understand scalatags. Not only do you get syntax highlighting, you also get code completion: • Autocomplete • Error Highlighting • In-editor documentation: And all the other good things (jump to definition, extract method, etc.) you're used to in a statically typed language. No more digging around in templates which mess up the highlighting of your HTML editor, or waiting months for the correct plugin to materialize. Strong Typed HTML Syntax for JVM/JS Scala Tags
  • 16. Strong Typed HTML Syntax for JVM/JS Scala Tags - Example html( head( script(src:="..."), script( "alert('Hello World')" ) ), body( div( h1(id:="title", "This is a title"), p("This is a big paragraph of text") ) ) ) <html> <head> <script src="..."></script> <script>alert('Hello World')</script> </head> <body> <div> <h1 id="title">This is a title</h1> <p>This is a big paragraph of text</p> </div> </body> </html>
  • 17. https://github.com/greencatsoft/scalajs-angular libraryDependencies += "com.greencatsoft" %%% "scalajs-angular" % "0.4” “scalajs-angular aims to help developers build AngularJS based applications in type safe manner with Scala language.” Schermata 2015-04-26 alle 10.56.47.png AngulaJS - scalajs-angular 1/2
  • 18. It provides annotation helper for AngularJS Services, Controllers, Directives, and Filters. It wraps ngRoute for routing in your SPA. Schermata 2015-04-26 alle 10.56.47.png AngulaJS - scalajs-angular 2/2
  • 19. https://github.com/jokade/scalajs-angulate libraryDependencies += "biz.enef" %%% "scalajs-angulate" % "0.1” “scalajs-angulate is a small library to simplify developing AngularJS applications in Scala (via Scala.js). To this end it provides: • façade traits for the Angular core API • macros for defining controllers, services and directives in a more natural Scala style” val module = angular.createModule("counter") module.controllerOf[CounterCtrl] class CounterCtrl extends Controller { var count = 0 def inc() = count += 1 def dec() = count -= 1 // private properties and functions are not exported to the controller scope private def foo() : Unit = ... } AngulaJS - scalajs-angulate 1/2
  • 20. It can be called in a similar HTML fragment: <html ng-app="counter"> <body> <div ng-controller="App.CounterCtrl as ctrl"> Count: {{ctrl.count}} <button ng-click="ctrl.inc()">+</button> <button ng-click="ctrl.dec()">&ndash;</button> </div> <!-- ... --> </body> </html> Schermata 2015-04-26 alle 10.56.47.png AngulaJS - scalajs-angulate 2/2
  • 21. I love ReactJS because: • Your code is clear. It is arranged into components, each with its own defined responsibility. (Web component, better dividi-et-impera approach) • Your app is predictable. It’s very clear where data flows, and what happens when a user does something. • Your app is fast. React is really, really fast, creating a better experience for users, even if you have a ton of data. (Virtual DOM, …) • Your app is standards-based. React adds layers only when it needs to. You feel like you are actually writing JavaScript and HTML, not some magic template language. • Surprise, you’re an app developer. React breaks down barriers across platforms, by applying its same model across the board. This means that once you learn the React way of structuring an web application, you have a huge head start on developing a native iOS or Android app, thanks to react- native. Surely this will happen to other platforms.Schermata 2015-04-26 alle 10.56.47.png Scala Js - React http://aspiringwebdev.com/why-react-js-matters-for-developers/
  • 22. I love ScalaJS ReactJS because: • It composed by simple concepts: • Properties (Props) are immutable • State is mutable • a render method • Everything is strong typed: VDOM, Components • Easy to extend components• Schermata 2015-04-26 alle 10.56.47.png Scala Js - React Javascript var HelloMessage = React.createClass({displayName: 'HelloMessage', render: function() { return React.createElement("div", null, "Hello ", this.props.name); } }); React.render(React.createElement(HelloMessage, {name: ”Alberto"}), mountNode);• Schermata 2015-04-26 alle 10.56.47.png Scala val HelloMessage = ReactComponentB[String]("HelloMessage") .render(name => <.div("Hello ", name)) .build React.render(HelloMessage(”Alberto"), mountNode)Schermata 2015-04-26 alle 10.56.47.png https://github.com/japgolly/scalajs-react http://japgolly.github.io/scalajs-react/
  • 23. Scala Scala Js - React https://github.com/japgolly/scalajs-react http://japgolly.github.io/scalajs-react/ ScalaJS React provide also many extra: • Scalaz support ("com.github.japgolly.scalajs-react" %%% "ext-scalaz71" % "0.8.4") • Monocle support (Lens for case class) ("com.github.japgolly.scalajs-react" %%% "ext-monocle" % "0.8.4") • Testing support ("com.github.japgolly.scalajs-react" %%% "test" % "0.8.4" % "test") val s = Simulation.focus >> ChangeEventData("hi").simulation >> Simulation.blur • Module extra ("com.github.japgolly.scalajs-react" %%% "extra" % "0.8.4") with  Router  Component Mixins:  Broadcaster and Listenable  ExternalVar  LogLifecycle  OnUmount  SetInterval
  • 24. Scala Scala CSS - CSS Type Safe! https://github.com/japgolly/scalacss http://japgolly.github.io/scalacss/book/ ScalaCSS aims to bring type-safety and clarity to: • creating CSS • using CSS • maintaining CSS • correctness of CSS You can create standalone CSS like SCSS/LESS, or you can create inline styles to be applied to directly without the need to manually manage class names. Being 100% Scala, you benefit from all the normal type-aware advantages like jump-to-definition of a style, type-safe keys and values, worry-free refactoring, etc. Example: http://japgolly.github.io/scalacss/book/quickstart/standalone.html
  • 25. Scala Other Libraries Links A lot of libraries are linked in Scala.js Homepage (http://www.scala-js.org/) For a complete projects, the best resources are: - SPA Tutorial (https://github.com/ochrons/scalajs-spa-tutorial) with doc (http://ochrons.github.io/scalajs-spa-tutorial/css-in-scala.html): - Spray - Autowire - Scala.JS React - Scala CSS - Deploy - Querki (https://github.com/jducoeur/Querki) - Scala.Js jquery - Facades - Play Scala.Js Example (https://github.com/hussachai/play-scalajs-showcase) - Gitter Channels
  • 26. 4. Tips & Tricks
  • 27. To manage the javascript library, Scala needs the code signature of the Javascript methods. First search on scala.js site or github scalajs trait JQuery extends js.Object { /** * Adds the specified class(es) to each of the set of matched elements. */ def addClass(classNames:String):JQuery = js.native def addClass(func:js.ThisFunction2[Element, Int, String, String]):JQuery = js.native @JSName("after") def afterInternal(content:js.Any):JQuery = js.native @JSName("append") def appendInternal(content:js.Any*):JQuery = js.native @JSName("appendTo") def appendToInternal(target:js.Any):JQuery = js.native @JSName("attr") def attrInternal(attributeName:String):UndefOr[String] = js.native Facading Javascript Libraries $(“div#myId”).addClass("m yclass")
  • 28. “Automatically” bootstrap your façade from a typescript definition (https://github.com/borisyankov/DefinitelyTyped): ~900 library already “typed”. The process is not 100 % accurate, so manual editing is often needed afterwards. This can be improved, but not to perfection, because the features offered by the type systems of TypeScript and Scala.js differ in some subtle ways. Usage $ sbt 'run somelib.d.ts SomeLib.scala' Facading Javascript Libraries https://github.com/sjrd/scala-js-ts-importer
  • 30. MILAN - 08TH OF MAY - 2015 PARTNERS THANK YOU! Alberto Paro alberto.paro@gmail.com @aparo77 PARTNERS

Hinweis der Redaktion

  1. It works very well with small projects, but big projects are difficult to manage
  2. It allows you to write your web application entirely in Scala!. Scala.js compiles full-fledged Scala code down to JavaScript, which can be integrated in your Web application. It provides very good interoperability with JavaScript code, both from Scala.js to JavaScript and vice versa. E.g., use jQuery and HTML5 from your Scala.js code.Since scala as a language and also its library rely on java standard library, so it is impossible to support all of scala without supporting some of java. hence scala.js includes partial part of java standard library , written in scala itself If you are developing rich internet application in scala and you are using all goodness of scala but you are sacrificing javascript interoperability, then you can use scala.js , a scala to javascript compiler. So that you can build entire web application in scala. A javascript backend for scala It allows you to write your web application entirely in Scala!. Scala.js compiles full-fledged Scala code down to JavaScript, which can be integrated in your Web application. It provides very good interoperability with JavaScript code, both from Scala.js to JavaScript and vice versa. E.g., use jQuery and HTML5 from your Scala.js code.Since scala as a language and also its library rely on java standard library, so it is impossible to support all of scala without supporting some of java. hence scala.js includes partial part of java standard library , written in scala itself If you are developing rich internet application in scala and you are using all goodness of scala but you are sacrificing javascript interoperability, then you can use scala.js , a scala to javascript compiler. So that you can build entire web application in scala. A javascript backend for scala
  3. scala.js compiles your scala code to javascript code. its just a usual scala compiler that takes scala code and produces javascript code instead of JVM byte code. on the other hand, js-scala is a scala library providing composable javascript code generator. You can use them in your usual scala program to write javascript program generator. your scala program will be compile into JVM byte code using scala compiler and executing of this program generates javascript program. The main difference is that js-scala is a library while scala.js is a compiler. Suppose that you want to write a JavaScript program solving a given problem. In js-scala you write aScala program generating a JavaScript program solving the given problem. In scala.js you write a Scala program solving the given problem
  4. parseInt receives two arguments: string and radix: var intValue = parseInt(string[, radix]); while map handler's second argument is index: ... callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. ['10','10','10','10','10'].map(function(x){return parseInt(x);})
  5. Number and characters have same semantices on JVM except 4 exceptionSince JavaScript doesn't have a native float type, we sometimes represent Floats using doubles/numbers, rather than with lower-precision 32-bit floatsUnlike the JVM where dividing an integer type by 0 throws an exception, in Scala.js integer division by 0 is undefined. Instance tests (and consequently pattern matching) on any of Byte, Short, Int, Float, Double are based on the value and not the type they were created with. Calling toString on a Float or a Double that holds an integral value, will not append ".0" to that value. This is due to how numeric values are represented at runtime in Scala.js scala.Unit is represented using JavaScript's undefined. Therefore, calling toString() on Unit will returnundefined rather than (). JavaScript regular expressions are slightly different from Java regular expressions. The support for regular expressions in Scala.js is implemented on top of JavaScript regexes. StackOverFlowError is unsupported NullPointerException is reported as Type error ArrayIndexOutOfBoundsException is never throw
  6. Since ScalaTags is pure Scala, any editor that understands Scala will understand scalatags.Text. Not only do you get syntax highlighting, you also get code completion: Autocomplete and Error Highlighting: Error Highlighting and in-editor documentation: Inline Documentation And all the other good things (jump to definition, extract method, etc.) you're used to in a statically typed language. No more digging around in templates which mess up the highlighting of your HTML editor, or waiting months for the correct plugin to materialize.
  7. Since ScalaTags is pure Scala, any editor that understands Scala will understand scalatags.Text. Not only do you get syntax highlighting, you also get code completion: Autocomplete and Error Highlighting: Error Highlighting and in-editor documentation: Inline Documentation And all the other good things (jump to definition, extract method, etc.) you're used to in a statically typed language. No more digging around in templates which mess up the highlighting of your HTML editor, or waiting months for the correct plugin to materialize.
  8. Since ScalaTags is pure Scala, any editor that understands Scala will understand scalatags.Text. Not only do you get syntax highlighting, you also get code completion: Autocomplete and Error Highlighting: Error Highlighting and in-editor documentation: Inline Documentation And all the other good things (jump to definition, extract method, etc.) you're used to in a statically typed language. No more digging around in templates which mess up the highlighting of your HTML editor, or waiting months for the correct plugin to materialize.
  9. Since ScalaTags is pure Scala, any editor that understands Scala will understand scalatags.Text. Not only do you get syntax highlighting, you also get code completion: Autocomplete and Error Highlighting: Error Highlighting and in-editor documentation: Inline Documentation And all the other good things (jump to definition, extract method, etc.) you're used to in a statically typed language. No more digging around in templates which mess up the highlighting of your HTML editor, or waiting months for the correct plugin to materialize.
  10. Since ScalaTags is pure Scala, any editor that understands Scala will understand scalatags.Text. Not only do you get syntax highlighting, you also get code completion: Autocomplete and Error Highlighting: Error Highlighting and in-editor documentation: Inline Documentation And all the other good things (jump to definition, extract method, etc.) you're used to in a statically typed language. No more digging around in templates which mess up the highlighting of your HTML editor, or waiting months for the correct plugin to materialize.
  11. It can be tempting to think of React JS as just another JavaScript framework, along the lines of Angular JS and Ember JS. This entirely misses why it was created and the problems it solves. React is not designed to solve problems specific to web applications. Rather, it is designed to solve problems for all applications. This sounds like buzz until you look at where React is going. Its first uses were in web applications, specifically Facebook and Instagram. Now, though, it’s rapidly moving past that: Facebook used it to build a native iOS mobile app, and is open sourcing react-native to allow anyone to do the same for iOS and Android. Learn more from Facebook’s recent React conference: overview, deep dive. Flipboard used it to power canvas graphics on its web site, which unlike the traditional browser DOM can operate with video-like smoothness. They open sourced this add-on to React. Netflix uses it to create TV interfaces. Hear about it in their own words. It’s used on both the server-side and the client-side. React doesn’t need a web browser to work. Why is React gaining traction on so many platforms, unlike other JavaScript frameworks? It’s simple: React presents a better model for development, generally. React’s impact is best explained by its side effects: Your code is clear. It is arranged into components, each with its own defined responsibility. Learn more about structure. Your app is predictable. It’s very clear where data flows, and what happens when a user does something. Learn more about data flow. Your app is fast. React is really, really fast, creating a better experience for users, even if you have a ton of data. See this example. Your app is standards-based. React adds layers only when it needs to. You feel like you are actually writing JavaScript and HTML, not some magic template language. Surprise, you’re an app developer. React breaks down barriers across platforms, by applying its same model across the board. This means that once you learn the React way of structuring an web application, you have a huge head start on developing a native iOS or Android app, thanks to react-native. Surely this will happen to other platforms. So, get to know React, even if you don’t see a need for it in your current projects. Far more than a shiny new JavaScript framework, it could represent a new standard for structuring applications. See also, the benefits of adding React to a real-world Rails app, and a deep dive into React in Rails.