Skip to main content
Polyglot Programming in the
          Browser
   or ‘Building Hybrid Web Apps’
buzdin@gmail.com
         @buzdin
         www.buzdin.lv

Dmitry Buzdin
The Story
 Begins...
This story begins
 long time ago...
When Browsers
 Were Brutal
Back in School I learned JavaScript
JavaScript seemed simplistic,
fragile and
useless...
I skipped that and
went for Windows-based
   client-server apps
Some time
passed...
I joined my first serious
Java-based Web project
It had quite standard
architecture:
JSP, Struts, Servlets, XML
> Ajax
> Drag and drop
> Custom components
> Auto-completion
> XSLT transformations
> Lots of CSS
Running in IE6
Written in plain JavaScript,
     without jQuery!
JavaScript seemed simplistic,
fragile and
kinda useful ...
People liked the system !

And they asked for more
like that ...
After a lot of
thinking we picked
Google Web Toolkit
GWT Primer

Write in Java - compile to JavaScript
Recompilation on browser refresh
Transparent RPC protocol via Ajax
> Everything is dynamic
> Everything is Ajax
> OOP and Modularity
> Refactoring Support
Some More Features
> Multi-browser support
> Obfuscation and compression
> Browser-specific optimization
> No vendor lock-in
Shipped 10+ applications
 own custom widget set
and few reusable libraries
Some more time
passed...
JavaScript became cool !
Two more things
appeared
Customers started demanding
> Excel-like grids
> Data Visualization
> Mobile Support
We started
considering
JavaScript seriously
console.log("2" / "2");
// 1

console.log("2" * "2");
// 4

console.log("1" + "2");
// 12
console.log([1, 2, 3] + 1);
// 1,2,31

console.log(1 + true + false);
// 2

console.log(true + "a");
// truea
> Weak typing
> No scopes, no modules
> Awkward class syntax
> No refactoring
> DIY builds
JavaScript...
JavaScript is still simplistic,
fragile,
but extremely useful !
So what to do?
We decided to stick with
  Google Web Toolkit
GWT had few problems:
> No high-end widgets
> No HTML5 support
> No eval()
How to integrate with
 JavaScript libraries?
GWT JavaScript Native Interface
private static void java(String param) {
}

private native void javaScript() /*-{

  $wnd.alert(‘Hello, JavaScript!’);

  $wnd.callback =
@com.a.b.Type.java(Ljava.lang.String;);

}-*/;
Java <> JSON
class JSOAttributes extends JavaScriptObject {

    public native void set(String k, String v) /*-{
      this[k]=v;
    }-*/;

    public native String get(String k) /*-{
      return this[k];
    }-*/;

}
Hybrid Web App

More than 1 language in your app

 JavaScript as host platform
Views

UI Components           View Libs

          JSON Model

 Controllers           Support Libs

  Ajax          REST         Storage
Frequency of changes
                       Views

                 UI Components

                 Application Logic

                   Infrastructure

                                     Code complexity
UI plumbing could be done
    in dynamic language

 Infrastructure code is more
manageable in static language
JavaScript   GWT
   Part      Part
JSNI Method for Every Call ?
private native void drawThings(...) /*-{
  $jsLib.drawThings(...);
}-*/;

private native void drawStuff(...) /*-{
  $jsLib.drawStuff(...);
}-*/;

private native void paintBlue() /*-{
  $jsLib.paint(‘blue’);
}-*/;
Code like
 that?...
 Really?
Too complex and
              unmanageable




JavaScript                     Dart/GWT
   Part                           Part
JavaScript         ?          Dart/GWT
   Part                          Part

             What if we do
              it like this?
Event Bus in the
   browser?!
Event Bus Pattern
         EventBridge                Callback

subscribe(Topic, Callback)
unsubscribe(Callback)        onEvent(Data, Callback)
publish(Topic, Data)
This resulted in
event ping-pong
Introducing ‘Event Bridge’
        EventBridge                     Callback

subscribe(Topic, Callback)
unsubscribe(Callback)            onEvent(Data, Callback)
publish(Topic, Data, Callback)
Java
bridge.subscribe("broadcast", this);



public void onEvent(ModelAttributes attributes,
  		 	 	 	 	 	       ModelEventCallback callback) {
   ModelAttributes result = Responses.attributes();
   result.set("result", "Response for JS");
   callback.resolve(result);
}


ModelAttributes data = Responses.attributes();
data.set("value", "Hello from GWT");
bridge.publish("broadcast", data);
$bridge.subscribe('broadcast',         JavaScript
        function (attrs, fn) {
            // JavaScript code
            fn();
        });




$bridge.publish('broadcast',
            { value: ‘Hello from JavaScript‘ },
            onResult
);
Profit!
Not using JavaScript interoperability API
Transparent JSON based exchange
Single point of communication
Sync/async possible
Some
Real-World Stuff
Introducing Livesheets

   Visual Graph-based
spreadsheets in the cloud

               www.livesheets.com
Main Challenges
Complex Domain Model
Expression language
Offline calculations
Sharing and embedding
JavaScript     Client TechStack          Java

     Twitter Bootstrap         GWT SDK


       Underscore.js             Guava


             Require.js   B      Guice


              jQuery            ANTLR


              jsPlumb         Domain Model
Event Flow

Draw

                    Domain Model
       Click




       jQuery   B    Controller



   jsPlumb
                        REST
Views

         UI Components              View Libs
JavaScript
                      JSON Model
  Java
             Controllers           Support Libs

             Ajax           REST         Storage
Clean View and Logic separation
Reusing cool JavaScript libraries
ANTLR in the browser!
Evaluation on client and server
But what if ?...
Event Bridge is coded in
      JavaScript.
   Can we use other
      languages?
Dart Primer

• New language by Google
• Compiles to JavaScript and runs in VM
• Both server and client modes
Dart Highlights

•   Created by people with GWT, V8, JVM
    and Java background
•   Sweet spot between Java and JavaScript
• Optional type safety
Dart <> JavaScript
#import('package:js/js.dart', prefix: 'js');

void main() {

    dart() {
    }

    js.scoped() {
      js.context.alert(‘Hello, JavaScript!’);
      js.context.x = new js.Callback.once(dart);
    }
}
onEvent(data, callback) {
  // Dart code                             Dart
}

eventBridge.subscribe(‘broadcast’, onEvent);



onResult(data) {
  // Dart code
}

eventBridge.publish('broadcast',
           {'value': 'Hello from Dart'},
           onResult);
Event Bridge was much
simpler to implement in
          Dart
Dart
                      Coffee
   Clojure
                      Script



                           Type
GWT            JS          Script



   Fantom             Kotlin
             Ceylon


One B!d" to rule #em all
JavaScript is a platform, not only a language
JavaScript libraries should be pluggable
JavaScript is challenging to scale
For ambitious projects pick GWT, Dart or other
Next Web Lang Checklist
JavaScript bi-directional integration
No recompilation while developing
Source maps for in-browser debugging
Consider using Event Bridge
Pick the right tools!
buzdin@gmail.com
         @buzdin
         www.buzdin.lv

Dmitry Buzdin
Additional Info
https://developers.google.com/web-toolkit/
http://www.dartlang.org
https://github.com/buzdin/hybrid-web-apps

        FlickrAttributions
           robert.molinarius
           theirhistory
           al unisono
           esther**
           Maccio Capatonda