SlideShare a Scribd company logo
1 of 55
Download to read offline
Architecting non-trivial
      browser applications



      Marc Bächinger
      Zühlke Engineering AG
      1178




Wednesday, June 27, 12
a new paradigm of
      web application engineering




                                    2




Wednesday, June 27, 12
Modern web application paradigm


                                   HTTP GET
                                   text/html
                                                                Application
           Webbrowser
                                                                  server               DB
                           GET/POST/PUT/DELETE
                                   text/json




        - request pages                                 - serve page assets        - CRUD
        - display markup
        - send form data                                - authentication
                                                        - authorization
        - access remote services                        - access data storage
        - access local data                             - enterprise integration

                                                        - provide services
        - maintain user state
        - process business logic
        - process UI logic                     Frontend logic
        - render markup tmpls

                                                                                            5




Wednesday, June 27, 12
Basic lifecycle of a modern HTML5 application

         DOMContentLoaded



                         onload                           onbeforeunload        onunload




                    UI setup
                                  application use cases           state synchronization
                 (augmentation)




    GET /index.html HTTP/1.1




        time
                                                                                      5




Wednesday, June 27, 12
Consequences of shift in architecture




      > Better user experience/usability

      > Unified REST API on the server side

      > Increasing complexity on the client side


                                                   3




Wednesday, June 27, 12
Embrace complexity   2




Wednesday, June 27, 12
Goals and advantages to achieve


      > reusable and extendible software artifacts

      > encapsulation and low coupling for flexibility

      > components can quickly be (re-)assembled and combined

      > applications and components which are easy to maintain

      > separation of concerns to support testing parts in isolation

      > sustainable and efficient development of complex JS applications



                                                                           2




Wednesday, June 27, 12
Craftsmanship

      > automated build for HTML applications
        – JSLint/JSHint to assess code quality
        – a unit test framework (e.g. quint, jasmine)
        – W3C validators
        – dependency resolving of JavaScript files
        – transform and minimize JavaScript code
        – CSS preprocessor (e.g. less, sass)

      > use a version control system
        – source code (html, js, json, css, assets)
        – configuration management

      > automated testing, continuous integration




                                                        5




Wednesday, June 27, 12
Architecture and design in browser applications




                         JavaScript applications need
                           architecture and design




                                                        5




Wednesday, June 27, 12
Observable pattern

          – very simple but powerful pattern to tie objects together
          – generic communication infrastructure
          – low coupling between interacting entities



       // bind a callback function to ‘add’ event
       observable.bind("add", function(addedItem) {
          // do something when called back
       });

       // emit an event to anonymous observers
       AnObservable.prototype.addItem = function(item) {
          this.items.push(item);
          this.emit("add", item);
       };
                                                                       2




Wednesday, June 27, 12
Model-View-Controller

      > a widely used pattern in UI development
      > many derivates and “MVC-look-a-likes”

      > Model
        – defines data an application/component is about
        – offers functions to manipulate model data
      > View
        – displays model data
                                                            Controller
        – provides UI to edit the data
      > Controller
        – connect model and view
        – listens for view events
                                                    Model                View
        – triggers model changes
        – synchronizes model and view
                                                                                2




Wednesday, June 27, 12
MVC in
                         JavaScript
                                  2




Wednesday, June 27, 12
Technology stacks - All in one




                             application code        business logic and plumping code




                           All-in-one framework             extJS, SproutCore




                         Mobile or desktop browser    FF, IE, Chrome, Safari, Opera

                                                                                        2




Wednesday, June 27, 12
Technology stacks - best of breed

                             application code                  business logic and plumping code


                             CSS Framework                     Twitter bootstrap, Zurb foundation


                                                                        jQuery, zepto.js
                                                  Micros
                                                 libraries     Backbone.js, Spine.js, Knockout.js
              Browser              MVC
                                                    and            ember.js, JavaScriptMVC
              facade            framework
                                                component
                                                     s
                                                             GMap, OSM, raphael, jQuery UI, Twitter
                                                                 bootstrap.js, mustache, jade


                         Mobile or desktop browser               FF, IE, Chrome, Safari, Opera




Wednesday, June 27, 12
Wednesday, June 27, 12
                         MVC
                           2
A Model in JavaScript (pseudo code)
        derive base functionality by an inheritance technique
                                                                          1
      var Person = function(spec) {
         Model.call(this, spec);
      };
      Person.prototype = new Model();


        create an instance and register callback to be called on change
                                                                          2
      var person = new Person({name: "Rui"});
      person.bind("change", function(changedData, model) {
          // do something
      });


        data changes trigger registered callbacks
                                                                          3
      person.set({ name: "Marc" });

                                                                              2




Wednesday, June 27, 12
A Model with backbone.js
                                                         1
      // derive constructor Person
      var Person = Backbone.Model.extend({
        setName: function(name) {
           this.set({name: name});
        }
      });

                                                         2
      // create an instance of Person
      var person = new Person();

      // listen for a change of the name field
      person.on("change:name", function(model, name) {
        $("#name").text(name);
      });

                                                         3
      var name = prompt("enter name");
      person.setName(name);
                                                             2




Wednesday, June 27, 12
Collections of Models (Backbone.js)

                                                                 1
      var PersonList = Backbone.Collection.extend({
        model: Person
      });



                                                                 2
      var musicians = new PersonList();

      musicians.on("add", function(person) {
        console.log(person.get("name"), "added to musicians");
      });


                                                                 3
      musicians.add([{
           name: "Gnarls Barkley"
      }]);




Wednesday, June 27, 12
Model wrap-up



      > models represent the data of an application or component

      > a model is observable

      > ‘public API’ of a model is expressed by firing events to callbacks

      > the model doesn’t know the DOM (can be tested outside the browser)




                                                                             2




Wednesday, June 27, 12
Wednesday, June 27, 12
                         MVC
                           2
Views in a browser application

                                 > view technology of a browser
                                   application is usually the
                                   Document Object Model (DOM)

                                 > convenient DOM access by using a
                                   DOM facade (like jQuery)

                                 > leveraging client side templates to
                                   render views

                                 > re-render templates of a component
                                   on Model events

                                 > using templates decouples DOM
                                   structures from render logic
                                                                    2




Wednesday, June 27, 12
Rendering views with a template library
                                                           Mustache template
      <script id="incidents-tmpl" type="text/template">
        <h3>Incidents</h3>
        <ul>
          {{#incidents}}
            <li data-id="{{id}}" class="incident">
              <span class="label>{{title}}</span></li>
            </li>
          {{/incidents}}
        </ul>
      </script>

                                                           Mustache engine
      // get the template text from a script element
      var template = $("#incidents-tmpl").text();

      // render the template with data
      var htmlMarkup = Mustache.render(template, model.get());

      // insert output into DOM
      $("#target").html(htmlMarkup);                                           2




Wednesday, June 27, 12
Wednesday, June 27, 12
                         MVC
                           2
Controllers - keeping things separated but together




                                                            2




Wednesday, June 27, 12
Controllers - keeping things separated but together
                                 var list = app.get("incidents");




                                                                    2




Wednesday, June 27, 12
Controllers - keeping things separated but together
                                 var list = app.get("incidents");


                                 <div id="incident-list"></div>


                                 <script id="incident-list-tmpl">
                                   <label>Incidents</label>
                                   <ul>
                                     {{#incidents}}
                                      <li><label>{{title}}</label></li>
                                      {{/incidents}}
                                   </ul>
                                 </script>




                                                                     2




Wednesday, June 27, 12
Controllers - keeping things separated but together
                                 var list = app.get("incidents");


                                 <div id="incident-list"></div>


                                 <script id="incident-list-tmpl">
                                   <label>Incidents</label>
                                   <ul>
                                     {{#incidents}}
                                      <li><label>{{title}}</label></li>
                                      {{/incidents}}
                                   </ul>
                                 </script>



                                 var listCtrl = new Controller({
                                          id: "incident-list",
                                          model: list
                                    });                              2




Wednesday, June 27, 12
Controller tasks and lifecycle

                   setup   > UI setup (augmentation)
                                  • render template
                                  • register model/UI callbacks



                 runtime   > listen for UI events (user interaction)
                                   • emit events/update model

                           > listen for model events
                                   • connect model events to view rendering



                clean up   > unregister and destroy

                                                                              2




Wednesday, June 27, 12
BIG BANG
   THEORY

                         2




Wednesday, June 27, 12
Application bootstrap and wiring

                 application
                                                           1   application model

                               create
                                        applicationModel


                                                           2   application services
                                                                 - persistence
                               create                            - routing (deep links)
                                           controller
                                          controller
                                          service                - public-subscribe
                                                                 - authentication

                               create
                                           controller
                                          controller
                                                           3   MV controllers
                                         controller
                                                                - application logic
                                                                - layout managers
                                                                                          2




Wednesday, June 27, 12
Birds view of an application

                                          applicationModel




                                      observe                update



                         controller             controller             controller




                                      refresh                observe




                           view                   view                   view       view




                                                                                           2




Wednesday, June 27, 12
Wire up an application

     var applicationController = new Controller({

           containerId: "body",

       init: function() {
         this.model = new ApplicationModel("/rest/api");
         this.crudService = new PersistenceService(”/crud/”);
         this.controllers = [
           new SidebarController(model),
           new EmailEditorController(model, this.crudService),
           new ListController(model.get(“inbox”))
         ];
       },
       render: function() {
         $.each(this.controllers, function() {
           this.render(); // delegate rendering
         });
       }
       [...]
     });                                                         2




Wednesday, June 27, 12
Communication services   2




Wednesday, June 27, 12
CRUD services using a REST API


      > CRUD support (create, read, update, delete)


     var PersistenceService = function(baseUrl) {
       this.url = baseUrl;
       return this;
     };

     PersistenceService.prototype.create = function(type, data, cb) {
     };
     PersistenceService.prototype.get = function(type, callback) {
     };
     PersistenceService.prototype.update = function(type, data, cb) {
     };
     PersistenceService.prototype.remove = function(type, id, cb) {
     };


                                                                        2




Wednesday, June 27, 12
Connect to a REST API with jQuery



     PersistenceService.prototype.update(type, data, callback) {
       $.ajax({
         type: "PUT",
         url: this.url + "/" + type + "/" + data.id,
         data: JSON.stringify(data),
         contentType: "application/json;charset=utf8",
         dataType: "json",
         success: function(respData) {
           if (callback) {
             callback(respData);
            }
          }
        });
     };



                                                                   2




Wednesday, June 27, 12
JAX-RS on the server side

     @Path("/address")
     public class AddressService {

                 @PUT
                 @Produces("application/json")
                 @Consumes("application/json")
                 public Address update(Address address) {
                    // update address using JPA
                      return address;
                 }

                 @POST
                 @Produces("application/json")
                 @Consumes("application/json")
                 public Address create(Address address) {
                     // create address using JPA
                     return address;
                 }
                 // [...]
                                                            2




Wednesday, June 27, 12
Model events trigger service calls

     ApplicationController.prototype.initPersistence = function() {

                 var service = new PersistenceService("/jaxrs");


                 this.addresses.bind("add", function(entry) {
                     service.create("address", entry, function() {
                         // async: handle response (error handling)
                     });
                 });


                 this.addresses.bind("remove", function(entry) {
                     service.remove("address", entry.id, function() {
                         // async: handle response (error handling)
                     });
                 });
     };

                                                                        2




Wednesday, June 27, 12
Using REST with Backbone.js

      > built-in support for local persistence
      > built-in support for remote persistence

     // create a book
     var book = new Backbone.Model({
       title: "Structure and change in economic history",
       author: "Douglass C. North"
     });

     book.save(); // triggers Backbone.sync("create", book);



      > adapt to own REST style by overriding Backbone.sync
     Backbone.sync = function(method, model) {
        // adapt to your REST API
     };

                                                               2




Wednesday, June 27, 12
Backbone.js/Spine.js REST protocol

      > read             ! GET    /collection
      > create           ! POST   /collection
      > update           ! PUT    /collection/id
      > destroy ! DELETE /collection/id



      raw HTTP request of an address creation

     POST /address HTTP/1.1
     Host: localhost:3080
     Origin: http://localhost:3080
     Content-Length: 59
     Content-Type: application/json

     {"id":"E537616F-F5C3-4C2B-8537-7661C7AC101E","name":"Marc"}

                                                                   2




Wednesday, June 27, 12
Untangled complexity




                           2




Wednesday, June 27, 12
Components of a MVC browser application

                              create
              application              applicationModel




                              create                observe/update
      create/
       use




                               use                            observe
                                            controller                     view
                 controller               controller                     view
                controller
               services                 controller                      view




                                                     use                render



                                       templateEngine




                                                                                  2




Wednesday, June 27, 12
Directory listing
           /index.html

           /main.js
           /css/layout.css                   referenced in index.html
           /css/application.css

           /src/application.js
           /src/application-model.js
                                                                    dependency mgmt
           /src/sidebar-controller.js
           /src/email-editor-controller.js


      reusable assets
           /modules/model/model-collection.js
           /modules/controller/controller.js
           /modules/controller/list-controller.js                   dependency mgmt
           /modules/service/persistence.js                          or
           /modules/service/persistence-jaxrs.js                    3-rd party library
           /modules/service/routing.js
           /modules/util.js
                                                                                         2




Wednesday, June 27, 12
Just build it!
      http://addyosmani.github.com/todomvc/




Wednesday, June 27, 12
@marcbaechinger         http://www.zuehlke.com
      Zühlke Engineering AG   bae@zuehlke.com




Wednesday, June 27, 12
Backup slides




      Marc Bächinger
      Zühlke Engineering AG
      1178




Wednesday, June 27, 12
Traditional web application paradigm




                                       GET/POST         HTML




                         Presentation layer (eg. JSF)



                         Business layer (eg. Session bean, Spring beans)


                         Integration layer (eg. JPA, JAX-WS)


                                                                           5




Wednesday, June 27, 12
Traditional web application paradigm



                           HTTP GET/POST       Application             SQL
        Webbrowser
                                                 server                              DB
                               text/html




        - request pages                     - serve page assets              - CRUD
        - display markup                                                     - (stored procedures)
        - send form data                    - authentication
                                            - authorization
                                            - access data storage
                                            - enterprise integration


                                            - maintain user state
                                            - process business logic
                           Frontend logic
                                            - process UI logic
                                            - render markup tplts

                                                                                              5




Wednesday, June 27, 12
5




Wednesday, June 27, 12
REST service API paradigm




                           GET/POST/PUT/DELETE         JSON




                         Remoting layer (eg. JAX-RS)



                         Service layer (eg. Session bean, Spring beans)


                         Integration layer (eg. JPA, JAX-WS)


                                                                          5




Wednesday, June 27, 12
Consequences of shift in architecture


      > Increased complexity on the client side
        – complex life-cycle of an application
        – multiple use cases without reloading the entire document
        – maintain user and UI state
        – call REST APIs
        – render templates
        – read from/write to local storage
        – integration of 3rd-party components (dialogs, data tables, maps)
        – support navigation (back button support)

      > Unified REST API on the server side
        – leveraging standard based HTTP verbs
        – unifies backend infrastructure of browser and mobile OS


                                                                             3




Wednesday, June 27, 12
Architecture and design in browser applications


      > meet non functional requirements (-ilities)
        – Extensibility
        – Reusability
        – Testability
        – Maintainability
        – Manageability
        – ...

      > provides a mental modal about how an application is designed to work
        – intentional decomposition of a system into subsystems
        – definition and description of relationships between entities
        – may be documented
        – always exists as an individual mental model of developers and architects


                                                                                     5




Wednesday, June 27, 12
A sample application model (pseudo code)
      var applicationModel = new Model(),
         inbox = new Collection(),
         sentMails = new Collection();

      // populate model properties
      applicationModel.set(“inbox”, inbox);
      applicationModel.set(“sentMails”, sentMails);
      applicationModel.set(“selectedEmail”, inbox.get(0));

      // register listeners
      applicationModel.on(“change:selectedEmail”, function(email) {
         renderMailView(email);
      });
      inbox.on(“add”, function() {
         renderInboxList();
      });
                                                                      2




Wednesday, June 27, 12
Capturing user interaction


      > efficient event handling by delegation
      > capture bubbling events at the top element only


      var controller = new Controller({
                 id: "incident-list",
                 "ui-events": {
                    "click ul li.incident": function (ev) {
                             // user selected a list entry
                         },
                         "click button.delete": function (ev) {
                             // user clicked delete button
                         }
                 }
      });

                                                                  2




Wednesday, June 27, 12
Spine.js controller



     var ListController = Spine.Controller.sub({

           events: {"click .incident": "click"}

       click: function(event){
         // use spines observable implementation
         this.trigger("selected");
       }
     });




                                                   2




Wednesday, June 27, 12
JAZOON COLOR SCHEME


      > Primary colors




      > Complementary colors




                               6




Wednesday, June 27, 12

More Related Content

What's hot

Struts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web ApplicationsStruts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web Applicationselliando dias
 
Mike Taulty MIX10 Silverlight 4 Patterns Frameworks
Mike Taulty MIX10 Silverlight 4 Patterns FrameworksMike Taulty MIX10 Silverlight 4 Patterns Frameworks
Mike Taulty MIX10 Silverlight 4 Patterns Frameworksukdpe
 
Java Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCJava Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCIMC Institute
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverSpike Brehm
 
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the CloudTDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the CloudArun Gupta
 
2012 04-06-v2-tdp-1163-java e-evsspringshootout-final
2012 04-06-v2-tdp-1163-java e-evsspringshootout-final2012 04-06-v2-tdp-1163-java e-evsspringshootout-final
2012 04-06-v2-tdp-1163-java e-evsspringshootout-finalRohit Kelapure
 
The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5Arun Gupta
 
Miha Lesjak Mobilizing The Web with Web Runtime
Miha Lesjak Mobilizing The Web with Web RuntimeMiha Lesjak Mobilizing The Web with Web Runtime
Miha Lesjak Mobilizing The Web with Web RuntimeNokiaAppForum
 
Java EE 7 (Hamed Hatami)
Java EE 7 (Hamed Hatami)Java EE 7 (Hamed Hatami)
Java EE 7 (Hamed Hatami)Hamed Hatami
 
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...Arun Gupta
 
Social Enabler for XPages
Social Enabler for XPagesSocial Enabler for XPages
Social Enabler for XPagesNiklas Heidloff
 
Java EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for futureJava EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for futureArun Gupta
 
Dojo CRUD Components
Dojo CRUD ComponentsDojo CRUD Components
Dojo CRUD ComponentsTom Mahieu
 
GIDS 2012: PaaSing a Java EE Application
GIDS 2012: PaaSing a Java EE ApplicationGIDS 2012: PaaSing a Java EE Application
GIDS 2012: PaaSing a Java EE ApplicationArun Gupta
 
Front-end Modular & Autmomated Development
Front-end Modular & Autmomated Development Front-end Modular & Autmomated Development
Front-end Modular & Autmomated Development Joseph Chiang
 
Partying with PHP (…and the Microsoft Platform)
Partying with PHP (…and the Microsoft Platform)Partying with PHP (…and the Microsoft Platform)
Partying with PHP (…and the Microsoft Platform)goodfriday
 
GIDS 2012: Java Message Service 2.0
GIDS 2012: Java Message Service 2.0GIDS 2012: Java Message Service 2.0
GIDS 2012: Java Message Service 2.0Arun Gupta
 
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-finalRohit Kelapure
 

What's hot (20)

Struts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web ApplicationsStruts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web Applications
 
Unit 07: Design Patterns and Frameworks (2/3)
Unit 07: Design Patterns and Frameworks (2/3)Unit 07: Design Patterns and Frameworks (2/3)
Unit 07: Design Patterns and Frameworks (2/3)
 
Mike Taulty MIX10 Silverlight 4 Patterns Frameworks
Mike Taulty MIX10 Silverlight 4 Patterns FrameworksMike Taulty MIX10 Silverlight 4 Patterns Frameworks
Mike Taulty MIX10 Silverlight 4 Patterns Frameworks
 
Java Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCJava Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVC
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
 
Unit 07: Design Patterns and Frameworks (1/3)
Unit 07: Design Patterns and Frameworks (1/3)Unit 07: Design Patterns and Frameworks (1/3)
Unit 07: Design Patterns and Frameworks (1/3)
 
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the CloudTDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
 
2012 04-06-v2-tdp-1163-java e-evsspringshootout-final
2012 04-06-v2-tdp-1163-java e-evsspringshootout-final2012 04-06-v2-tdp-1163-java e-evsspringshootout-final
2012 04-06-v2-tdp-1163-java e-evsspringshootout-final
 
The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5
 
Miha Lesjak Mobilizing The Web with Web Runtime
Miha Lesjak Mobilizing The Web with Web RuntimeMiha Lesjak Mobilizing The Web with Web Runtime
Miha Lesjak Mobilizing The Web with Web Runtime
 
Java EE 7 (Hamed Hatami)
Java EE 7 (Hamed Hatami)Java EE 7 (Hamed Hatami)
Java EE 7 (Hamed Hatami)
 
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
 
Social Enabler for XPages
Social Enabler for XPagesSocial Enabler for XPages
Social Enabler for XPages
 
Java EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for futureJava EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for future
 
Dojo CRUD Components
Dojo CRUD ComponentsDojo CRUD Components
Dojo CRUD Components
 
GIDS 2012: PaaSing a Java EE Application
GIDS 2012: PaaSing a Java EE ApplicationGIDS 2012: PaaSing a Java EE Application
GIDS 2012: PaaSing a Java EE Application
 
Front-end Modular & Autmomated Development
Front-end Modular & Autmomated Development Front-end Modular & Autmomated Development
Front-end Modular & Autmomated Development
 
Partying with PHP (…and the Microsoft Platform)
Partying with PHP (…and the Microsoft Platform)Partying with PHP (…and the Microsoft Platform)
Partying with PHP (…and the Microsoft Platform)
 
GIDS 2012: Java Message Service 2.0
GIDS 2012: Java Message Service 2.0GIDS 2012: Java Message Service 2.0
GIDS 2012: Java Message Service 2.0
 
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
 

Similar to Architecting Modern Web Apps

Wei ding(resume)
Wei ding(resume)Wei ding(resume)
Wei ding(resume)WEI DING
 
Building assets on the fly with Node.js
Building assets on the fly with Node.jsBuilding assets on the fly with Node.js
Building assets on the fly with Node.jsAcquisio
 
Naresh Kumar
Naresh KumarNaresh Kumar
Naresh KumarNaresh K
 
Nitesh_Sr._Java_developer_Lead
Nitesh_Sr._Java_developer_Lead Nitesh_Sr._Java_developer_Lead
Nitesh_Sr._Java_developer_Lead Nitesh Dasari
 
MVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on RailsMVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on Railscodeinmotion
 
.NetCampus Windows Azure Mobile
.NetCampus Windows Azure Mobile.NetCampus Windows Azure Mobile
.NetCampus Windows Azure Mobileantimo musone
 
Model Driven Architecture (MDA): Motivations, Status & Future
Model Driven Architecture (MDA): Motivations, Status & FutureModel Driven Architecture (MDA): Motivations, Status & Future
Model Driven Architecture (MDA): Motivations, Status & Futureelliando dias
 
Makersbay Overview
Makersbay OverviewMakersbay Overview
Makersbay Overviewslodha
 
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJSMeteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJSJulio Antonio Mendonça de Marins
 
Rajiv ranjan resume-us
Rajiv ranjan  resume-usRajiv ranjan  resume-us
Rajiv ranjan resume-usRajiv Ranjan
 
Android Data Binding Support Library
Android Data Binding Support LibraryAndroid Data Binding Support Library
Android Data Binding Support Libraryersin ertan
 
What's Next Replay - SpringSource
What's Next Replay - SpringSourceWhat's Next Replay - SpringSource
What's Next Replay - SpringSourceZenikaOuest
 
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
 

Similar to Architecting Modern Web Apps (20)

Wei ding(resume)
Wei ding(resume)Wei ding(resume)
Wei ding(resume)
 
Building assets on the fly with Node.js
Building assets on the fly with Node.jsBuilding assets on the fly with Node.js
Building assets on the fly with Node.js
 
Delivering with ember.js
Delivering with ember.jsDelivering with ember.js
Delivering with ember.js
 
Naresh Kumar
Naresh KumarNaresh Kumar
Naresh Kumar
 
Nitesh_Sr._Java_developer_Lead
Nitesh_Sr._Java_developer_Lead Nitesh_Sr._Java_developer_Lead
Nitesh_Sr._Java_developer_Lead
 
MVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on RailsMVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on Rails
 
.NetCampus Windows Azure Mobile
.NetCampus Windows Azure Mobile.NetCampus Windows Azure Mobile
.NetCampus Windows Azure Mobile
 
Model Driven Architecture (MDA): Motivations, Status & Future
Model Driven Architecture (MDA): Motivations, Status & FutureModel Driven Architecture (MDA): Motivations, Status & Future
Model Driven Architecture (MDA): Motivations, Status & Future
 
Makersbay Overview
Makersbay OverviewMakersbay Overview
Makersbay Overview
 
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJSMeteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
 
JulianSerna2016
JulianSerna2016JulianSerna2016
JulianSerna2016
 
Resume
ResumeResume
Resume
 
Rajiv ranjan resume-us
Rajiv ranjan  resume-usRajiv ranjan  resume-us
Rajiv ranjan resume-us
 
Android Data Binding Support Library
Android Data Binding Support LibraryAndroid Data Binding Support Library
Android Data Binding Support Library
 
Lecture 05 web_applicationframeworks
Lecture 05 web_applicationframeworksLecture 05 web_applicationframeworks
Lecture 05 web_applicationframeworks
 
What's Next Replay - SpringSource
What's Next Replay - SpringSourceWhat's Next Replay - SpringSource
What's Next Replay - SpringSource
 
Sarada Ojha CV
Sarada Ojha CVSarada Ojha CV
Sarada Ojha CV
 
Struts ppt 1
Struts ppt 1Struts ppt 1
Struts ppt 1
 
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)
 
Charan Grandhi_Resume
Charan Grandhi_ResumeCharan Grandhi_Resume
Charan Grandhi_Resume
 

More from Marc Bächinger

More from Marc Bächinger (9)

Introduction to web components
Introduction to web componentsIntroduction to web components
Introduction to web components
 
High-Quality JavaScript
High-Quality JavaScriptHigh-Quality JavaScript
High-Quality JavaScript
 
HTML5 unplugged
HTML5 unpluggedHTML5 unplugged
HTML5 unplugged
 
Modern web application network architecture
Modern web application network architectureModern web application network architecture
Modern web application network architecture
 
JavaScript toolchain
JavaScript toolchainJavaScript toolchain
JavaScript toolchain
 
JQuery primer
JQuery primerJQuery primer
JQuery primer
 
With your bare hands
With your bare handsWith your bare hands
With your bare hands
 
Jax-rs-js Tutorial
Jax-rs-js TutorialJax-rs-js Tutorial
Jax-rs-js Tutorial
 
Html5 communication
Html5 communicationHtml5 communication
Html5 communication
 

Recently uploaded

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Recently uploaded (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Architecting Modern Web Apps

  • 1. Architecting non-trivial browser applications Marc Bächinger Zühlke Engineering AG 1178 Wednesday, June 27, 12
  • 2. a new paradigm of web application engineering 2 Wednesday, June 27, 12
  • 3. Modern web application paradigm HTTP GET text/html Application Webbrowser server DB GET/POST/PUT/DELETE text/json - request pages - serve page assets - CRUD - display markup - send form data - authentication - authorization - access remote services - access data storage - access local data - enterprise integration - provide services - maintain user state - process business logic - process UI logic Frontend logic - render markup tmpls 5 Wednesday, June 27, 12
  • 4. Basic lifecycle of a modern HTML5 application DOMContentLoaded onload onbeforeunload onunload UI setup application use cases state synchronization (augmentation) GET /index.html HTTP/1.1 time 5 Wednesday, June 27, 12
  • 5. Consequences of shift in architecture > Better user experience/usability > Unified REST API on the server side > Increasing complexity on the client side 3 Wednesday, June 27, 12
  • 6. Embrace complexity 2 Wednesday, June 27, 12
  • 7. Goals and advantages to achieve > reusable and extendible software artifacts > encapsulation and low coupling for flexibility > components can quickly be (re-)assembled and combined > applications and components which are easy to maintain > separation of concerns to support testing parts in isolation > sustainable and efficient development of complex JS applications 2 Wednesday, June 27, 12
  • 8. Craftsmanship > automated build for HTML applications – JSLint/JSHint to assess code quality – a unit test framework (e.g. quint, jasmine) – W3C validators – dependency resolving of JavaScript files – transform and minimize JavaScript code – CSS preprocessor (e.g. less, sass) > use a version control system – source code (html, js, json, css, assets) – configuration management > automated testing, continuous integration 5 Wednesday, June 27, 12
  • 9. Architecture and design in browser applications JavaScript applications need architecture and design 5 Wednesday, June 27, 12
  • 10. Observable pattern – very simple but powerful pattern to tie objects together – generic communication infrastructure – low coupling between interacting entities // bind a callback function to ‘add’ event observable.bind("add", function(addedItem) { // do something when called back }); // emit an event to anonymous observers AnObservable.prototype.addItem = function(item) { this.items.push(item); this.emit("add", item); }; 2 Wednesday, June 27, 12
  • 11. Model-View-Controller > a widely used pattern in UI development > many derivates and “MVC-look-a-likes” > Model – defines data an application/component is about – offers functions to manipulate model data > View – displays model data Controller – provides UI to edit the data > Controller – connect model and view – listens for view events Model View – triggers model changes – synchronizes model and view 2 Wednesday, June 27, 12
  • 12. MVC in JavaScript 2 Wednesday, June 27, 12
  • 13. Technology stacks - All in one application code business logic and plumping code All-in-one framework extJS, SproutCore Mobile or desktop browser FF, IE, Chrome, Safari, Opera 2 Wednesday, June 27, 12
  • 14. Technology stacks - best of breed application code business logic and plumping code CSS Framework Twitter bootstrap, Zurb foundation jQuery, zepto.js Micros libraries Backbone.js, Spine.js, Knockout.js Browser MVC and ember.js, JavaScriptMVC facade framework component s GMap, OSM, raphael, jQuery UI, Twitter bootstrap.js, mustache, jade Mobile or desktop browser FF, IE, Chrome, Safari, Opera Wednesday, June 27, 12
  • 16. A Model in JavaScript (pseudo code) derive base functionality by an inheritance technique 1 var Person = function(spec) { Model.call(this, spec); }; Person.prototype = new Model(); create an instance and register callback to be called on change 2 var person = new Person({name: "Rui"}); person.bind("change", function(changedData, model) { // do something }); data changes trigger registered callbacks 3 person.set({ name: "Marc" }); 2 Wednesday, June 27, 12
  • 17. A Model with backbone.js 1 // derive constructor Person var Person = Backbone.Model.extend({ setName: function(name) { this.set({name: name}); } }); 2 // create an instance of Person var person = new Person(); // listen for a change of the name field person.on("change:name", function(model, name) { $("#name").text(name); }); 3 var name = prompt("enter name"); person.setName(name); 2 Wednesday, June 27, 12
  • 18. Collections of Models (Backbone.js) 1 var PersonList = Backbone.Collection.extend({ model: Person }); 2 var musicians = new PersonList(); musicians.on("add", function(person) { console.log(person.get("name"), "added to musicians"); }); 3 musicians.add([{ name: "Gnarls Barkley" }]); Wednesday, June 27, 12
  • 19. Model wrap-up > models represent the data of an application or component > a model is observable > ‘public API’ of a model is expressed by firing events to callbacks > the model doesn’t know the DOM (can be tested outside the browser) 2 Wednesday, June 27, 12
  • 21. Views in a browser application > view technology of a browser application is usually the Document Object Model (DOM) > convenient DOM access by using a DOM facade (like jQuery) > leveraging client side templates to render views > re-render templates of a component on Model events > using templates decouples DOM structures from render logic 2 Wednesday, June 27, 12
  • 22. Rendering views with a template library Mustache template <script id="incidents-tmpl" type="text/template"> <h3>Incidents</h3> <ul> {{#incidents}} <li data-id="{{id}}" class="incident"> <span class="label>{{title}}</span></li> </li> {{/incidents}} </ul> </script> Mustache engine // get the template text from a script element var template = $("#incidents-tmpl").text(); // render the template with data var htmlMarkup = Mustache.render(template, model.get()); // insert output into DOM $("#target").html(htmlMarkup); 2 Wednesday, June 27, 12
  • 24. Controllers - keeping things separated but together 2 Wednesday, June 27, 12
  • 25. Controllers - keeping things separated but together var list = app.get("incidents"); 2 Wednesday, June 27, 12
  • 26. Controllers - keeping things separated but together var list = app.get("incidents"); <div id="incident-list"></div> <script id="incident-list-tmpl"> <label>Incidents</label> <ul> {{#incidents}} <li><label>{{title}}</label></li> {{/incidents}} </ul> </script> 2 Wednesday, June 27, 12
  • 27. Controllers - keeping things separated but together var list = app.get("incidents"); <div id="incident-list"></div> <script id="incident-list-tmpl"> <label>Incidents</label> <ul> {{#incidents}} <li><label>{{title}}</label></li> {{/incidents}} </ul> </script> var listCtrl = new Controller({ id: "incident-list", model: list }); 2 Wednesday, June 27, 12
  • 28. Controller tasks and lifecycle setup > UI setup (augmentation) • render template • register model/UI callbacks runtime > listen for UI events (user interaction) • emit events/update model > listen for model events • connect model events to view rendering clean up > unregister and destroy 2 Wednesday, June 27, 12
  • 29. BIG BANG THEORY 2 Wednesday, June 27, 12
  • 30. Application bootstrap and wiring application 1 application model create applicationModel 2 application services - persistence create - routing (deep links) controller controller service - public-subscribe - authentication create controller controller 3 MV controllers controller - application logic - layout managers 2 Wednesday, June 27, 12
  • 31. Birds view of an application applicationModel observe update controller controller controller refresh observe view view view view 2 Wednesday, June 27, 12
  • 32. Wire up an application var applicationController = new Controller({ containerId: "body", init: function() { this.model = new ApplicationModel("/rest/api"); this.crudService = new PersistenceService(”/crud/”); this.controllers = [ new SidebarController(model), new EmailEditorController(model, this.crudService), new ListController(model.get(“inbox”)) ]; }, render: function() { $.each(this.controllers, function() { this.render(); // delegate rendering }); } [...] }); 2 Wednesday, June 27, 12
  • 33. Communication services 2 Wednesday, June 27, 12
  • 34. CRUD services using a REST API > CRUD support (create, read, update, delete) var PersistenceService = function(baseUrl) { this.url = baseUrl; return this; }; PersistenceService.prototype.create = function(type, data, cb) { }; PersistenceService.prototype.get = function(type, callback) { }; PersistenceService.prototype.update = function(type, data, cb) { }; PersistenceService.prototype.remove = function(type, id, cb) { }; 2 Wednesday, June 27, 12
  • 35. Connect to a REST API with jQuery PersistenceService.prototype.update(type, data, callback) { $.ajax({ type: "PUT", url: this.url + "/" + type + "/" + data.id, data: JSON.stringify(data), contentType: "application/json;charset=utf8", dataType: "json", success: function(respData) { if (callback) { callback(respData); } } }); }; 2 Wednesday, June 27, 12
  • 36. JAX-RS on the server side @Path("/address") public class AddressService { @PUT @Produces("application/json") @Consumes("application/json") public Address update(Address address) { // update address using JPA return address; } @POST @Produces("application/json") @Consumes("application/json") public Address create(Address address) { // create address using JPA return address; } // [...] 2 Wednesday, June 27, 12
  • 37. Model events trigger service calls ApplicationController.prototype.initPersistence = function() { var service = new PersistenceService("/jaxrs"); this.addresses.bind("add", function(entry) { service.create("address", entry, function() { // async: handle response (error handling) }); }); this.addresses.bind("remove", function(entry) { service.remove("address", entry.id, function() { // async: handle response (error handling) }); }); }; 2 Wednesday, June 27, 12
  • 38. Using REST with Backbone.js > built-in support for local persistence > built-in support for remote persistence // create a book var book = new Backbone.Model({ title: "Structure and change in economic history", author: "Douglass C. North" }); book.save(); // triggers Backbone.sync("create", book); > adapt to own REST style by overriding Backbone.sync Backbone.sync = function(method, model) { // adapt to your REST API }; 2 Wednesday, June 27, 12
  • 39. Backbone.js/Spine.js REST protocol > read ! GET /collection > create ! POST /collection > update ! PUT /collection/id > destroy ! DELETE /collection/id raw HTTP request of an address creation POST /address HTTP/1.1 Host: localhost:3080 Origin: http://localhost:3080 Content-Length: 59 Content-Type: application/json {"id":"E537616F-F5C3-4C2B-8537-7661C7AC101E","name":"Marc"} 2 Wednesday, June 27, 12
  • 40. Untangled complexity 2 Wednesday, June 27, 12
  • 41. Components of a MVC browser application create application applicationModel create observe/update create/ use use observe controller view controller controller view controller services controller view use render templateEngine 2 Wednesday, June 27, 12
  • 42. Directory listing /index.html /main.js /css/layout.css referenced in index.html /css/application.css /src/application.js /src/application-model.js dependency mgmt /src/sidebar-controller.js /src/email-editor-controller.js reusable assets /modules/model/model-collection.js /modules/controller/controller.js /modules/controller/list-controller.js dependency mgmt /modules/service/persistence.js or /modules/service/persistence-jaxrs.js 3-rd party library /modules/service/routing.js /modules/util.js 2 Wednesday, June 27, 12
  • 43. Just build it! http://addyosmani.github.com/todomvc/ Wednesday, June 27, 12
  • 44. @marcbaechinger http://www.zuehlke.com Zühlke Engineering AG bae@zuehlke.com Wednesday, June 27, 12
  • 45. Backup slides Marc Bächinger Zühlke Engineering AG 1178 Wednesday, June 27, 12
  • 46. Traditional web application paradigm GET/POST HTML Presentation layer (eg. JSF) Business layer (eg. Session bean, Spring beans) Integration layer (eg. JPA, JAX-WS) 5 Wednesday, June 27, 12
  • 47. Traditional web application paradigm HTTP GET/POST Application SQL Webbrowser server DB text/html - request pages - serve page assets - CRUD - display markup - (stored procedures) - send form data - authentication - authorization - access data storage - enterprise integration - maintain user state - process business logic Frontend logic - process UI logic - render markup tplts 5 Wednesday, June 27, 12
  • 49. REST service API paradigm GET/POST/PUT/DELETE JSON Remoting layer (eg. JAX-RS) Service layer (eg. Session bean, Spring beans) Integration layer (eg. JPA, JAX-WS) 5 Wednesday, June 27, 12
  • 50. Consequences of shift in architecture > Increased complexity on the client side – complex life-cycle of an application – multiple use cases without reloading the entire document – maintain user and UI state – call REST APIs – render templates – read from/write to local storage – integration of 3rd-party components (dialogs, data tables, maps) – support navigation (back button support) > Unified REST API on the server side – leveraging standard based HTTP verbs – unifies backend infrastructure of browser and mobile OS 3 Wednesday, June 27, 12
  • 51. Architecture and design in browser applications > meet non functional requirements (-ilities) – Extensibility – Reusability – Testability – Maintainability – Manageability – ... > provides a mental modal about how an application is designed to work – intentional decomposition of a system into subsystems – definition and description of relationships between entities – may be documented – always exists as an individual mental model of developers and architects 5 Wednesday, June 27, 12
  • 52. A sample application model (pseudo code) var applicationModel = new Model(), inbox = new Collection(), sentMails = new Collection(); // populate model properties applicationModel.set(“inbox”, inbox); applicationModel.set(“sentMails”, sentMails); applicationModel.set(“selectedEmail”, inbox.get(0)); // register listeners applicationModel.on(“change:selectedEmail”, function(email) { renderMailView(email); }); inbox.on(“add”, function() { renderInboxList(); }); 2 Wednesday, June 27, 12
  • 53. Capturing user interaction > efficient event handling by delegation > capture bubbling events at the top element only var controller = new Controller({ id: "incident-list", "ui-events": { "click ul li.incident": function (ev) { // user selected a list entry }, "click button.delete": function (ev) { // user clicked delete button } } }); 2 Wednesday, June 27, 12
  • 54. Spine.js controller var ListController = Spine.Controller.sub({ events: {"click .incident": "click"} click: function(event){ // use spines observable implementation this.trigger("selected"); } }); 2 Wednesday, June 27, 12
  • 55. JAZOON COLOR SCHEME > Primary colors > Complementary colors 6 Wednesday, June 27, 12