SlideShare uma empresa Scribd logo
1 de 31
MV* presentation frameworks in
Javascript: en garde, pret, allez!
      Knockout JS vs Backbone JS
      Roberto Messora / robymes
Thanks to the sponsors
Poll
• How many expert Javascript developers?
• How many new to Javascript?
• How many, at least once, did use a Javascript
  Presentation Framework (not plain jQuery)?
• How many did come from server side
  development and switched to client side
  because of HTML5 new wave?
Foreword
• Session goals:
  – Why choose a client Presentation Framework
    when building a web application
  – Clarify how Presentation Patterns are
    implemented in Javascript
  – Show the differences between an MVC(*) and a
    MVVM Javascript Framework
• Many thanks to the great TodoMVC project
  and its contributors (http://todomvc.com/)
Summary
• Presentation frameworks: why and when
• Inside presentation patterns
• BackboneJS: is it really MVC? Aka: where is my
  controller?
• KnockoutJS: the emerging MVVM pattern that
  "shifted its strategy" (reinterpreting Muglia…)
• BackboneJS vs KnockoutJS: the bad and the
  good parts
Without a Presentation Fx
TodoMVC: the plain jQuery implementation
  – Classical jQuery DOM management using direct
    tag reference + HTML templating engine
  – Simple DOM element event binding
    implementation
  – Monolithic single code file solution with "utilities"
    object containers (prone to spaghetti code)
  – Very difficult to test and maintain, nearly
    impossibile when app size scales up
With a Presentation Fx
TodoMVC: an MV* implementation (BackboneJS
or KnockoutJS)
  – Structured DOM/element event management and
    binding + HTML templating engine
  – Structured solution organization in terms of object
    responsabilities and interactions (is more difficult
    to write spaghetti code)
  – It's possibile to adopt a unit testing strategy and
    manage complexity when app size scales up
Presentation Fxs: a brief history
A long time ago in a galaxy far, far away....
• 1979: Trygve Reenskaug designed the original
  pattern called Model-View-Controller-Editor in
  Smalltalk-80, its objective was to decouple
  data (Model) from UI (View) using a
  coordinator (Controller), enforcing separation
  of concerns (and accordingly single
  responsibilities)
Presentation Fxs: a brief history
• Over the years many other presentation
  design patterns came to light delivering the
  same main principle: decouple Model from
  the View
  – Refined versions of Model-View-Controller (MVC)
  – Variations of Model-View-Presenter (MVP)
  – Model-View-ViewModel (MVVM)
• We can talk about an MV* presentation
  design patterns family
Presentation Fxs: a brief history
• MV* presentation design patterns
  – Originally designed for desktop applications and
    then implemented also for enterprise server side
    web applications
  – Only in recent years implemented for client side
    web development
  – Javascript implementations often differ from the
    original "pure" vision, maintaining the basic
    principles (they can be considered more "flexible")
MVC pattern
• A classical MVC pattern interpratation:
  – A Model: a business (or domain) object that
    doesn't have any knowledge about presentation
  – A View: the UI representation of one or more
    models, also contains widgets for user interactions
  – A Controller: the key element that reacts to user
    inputs doing something with model objects
  – A Publish/Subscribe system: an Observer pattern
    implementation that handles model state updates
BackboneJS: Javascript MVC
• Is one of the most used Jascript MVC
  Presentation Frameworks (others are
  EmberJS, JavascriptMVC, Spine, …)
• It's more than an MVC implementation: it
  offers features like RESTful
  services, pagination, support for multiple
  DOM templating libraries, support for key-
  value observing libraries (KVO)
BackboneJS: the Model
• Business data representation: properties +
  operations, it doesn't have any UI knowledge
• It extends Backbone.Model base object:
  – get and set methods to access properties
  – on method to listen to model changes or errors
    defined in the initialize method
  – validate method for properties validation logic
  – toJSON utility method for JSON serialization
BackboneJS: the Model
var MyModel = Backbone.Model.extend({
  defaults: { property_01: ..., ... },
  validate: function(attribs){
    if (attribs.property_01 ...){...}
  },
  initialize: function(){
    this.on("error", function(model, error){ ... };
    this.on("change:property_01", function(){ ... };
    ...
  }
});
var myModel = new MyModel();
var prop = myModel.get("property_01");
myModel.set({"propery_01": ...);
BackboneJS: the View
• It doesn't contain any DOM informations, it's
  an object that manages Model UI
  representation
• It extends Backbone.View base object:
  – el attribute to define DOM related element
  – render method to define DOM rendering using a
    templating library
    (HandlebarsJS, Mustache, …), called on model
    changes
  – events attribute to listen to DOM events (el
    element and childrens)
BackboneJS: the View
var MyView = Backbone.View.extend({
  el: $('#id'),
  render: function(event){
     var tmpl = ...; //templating
     this.$el.html(tmpl(this.model.toJSON()));
     return this; //this enables calls to be chained
  },
  events: { "click #myBtn": "myBtnClick", ... },
  myBtnClick: function(event){ ... };
  initialize: function(){
     this.model.on('change', this.render);
  }
});
var myView = new MyView({ model: myModel });
BackboneJS: Collections
• There is a special support for Collections of
  Models:
  – get and set methods to access specfic elements
  – on method to listen to elements changes
  – fetch method for server REST calls
BackboneJS: the Router
• This is a special concept: it handles
  – Application state
  – Connection between URLs and application events
• It extends Backbone.Router base object and
  define a series of URL route pattern/method
  pairs
• It needs the special Backbone.history object to
  be started to trigger methods when URL
  changes
BackboneJS: the Router
var MyRouter = Backbone.Router.extend({
  routes: {'search/:query': 'search', ... },
  // http://www.foo.com/#search/bar
  search: function(query){ ... }
});
var myRouter = new MyRouter();
Backbone.history.start();
BackboneJS: the Controller
• And the very question is: where is my
  controller? There are any Controller man…
• BackboneJS is not a pure MVC
  implementation:
  – A View can be seen as a Presenter in the MVP
    pattern (it contains rendering UI logic)
  – A View is also flexible to be a classical MVC view (if
    we don't write any UI logic such as DOM events
    callbacks)
  – Controller role is shared between View and Router
MVVM pattern
• It promotes a deeper separation beetween UI
  and business logic development:
  – Views designed by User Experience and
    Interaction experts
  – ViewModels and Models developed by sofwtare
    developer
  – Bridge between View and ViewModels is defined
    by declarative View markup data and events
    (commands) binding
KnockoutJS: Javascript MVVM
• It's the most used Javascript MVVM
  Presentation Framework (but there are a few)
• It's a relatively recent library, it doesn't offer
  yet much support for anything else but the
  presentation functionalities (eg service
  communication, data fetching, …)
• it can be used in a nearly exact Silverlight way
KnockoutJS: The Model
• Business data anemic representation, it
  contains only properties and their validation
  logic, it doesn't have any UI knowledge
• It's a plain Javascript object that uses the
  special observable Knockout method to
  initialize its properties as observable objects
  so they can automatically notify their changes
  and detect their dependencies
KnockoutJS: The Model
var Todo = function(title, completed) {
  this.title = ko.observable(title);
  this.completed = ko.observable(completed);
  this.editing = ko.observable(false);
};
KnockoutJS: the View
• It's the concrete UI: it's a portion of the HTML
  page DOM
• It's active: it contains data and events binding
  so must have Model and ViewModel
  knowledge
• It doesn't maintain any state but only the
  synchronization with the ViewModel
• It can use DOM templating
KnockoutJS: the View
<section id="main" data-bind="visible: todos().length">
  <input id="toggle-all" data-bind="checked: allCompleted" type="checkbox">
  <label for="toggle-all">Mark all as complete</label>
  <ul id="todo-list" data-bind="foreach: filteredTodos">
    <li data-bind="css: { completed: completed, editing: editing }">
      <div class="view">
        <input class="toggle" data-bind="checked: completed" type="checkbox">
        <label data-bind="text: title,
          event:{dblclick: $root.editItem}"></label>
        <button class="destroy" data-bind="click: $root.remove"></button>
      </div>
      <input class="edit" data-bind="value: title,
        valueUpdate:'afterkeydown', enterKey: $root.stopEditing,
        selectAndFocus: editing, event: {blur: $root.stopEditing}">
    </li>
  </ul>
</section>
KnockoutJS: the ViewModel
• Can be considered as the bridge between the
  View and the Model, it can convert Model
  informations to provide the View data in the
  correct format
• It handles the View state and reacts to its events
  wiring services and Model to orchestrate
  application logic
• It's a plain Javascript object that uses the special
  observable, computed and observableArray
  Knockout methods so it can automatically notify
  View about its changes, it also contains methods
  that handles View events
KnockoutJS: the ViewModel
var ViewModel = function(todos) {
  var self = this;
  self.todos = ko.observableArray(ko.utils.arrayMap(
    todos, function(todo) {
    return new Todo(todo.title, todo.completed);
  }));
  ...
  self.allCompleted = ko.computed(...);
  ...
});
var viewModel = new ViewModel(todos || []);
ko.applyBindings(viewModel);
KnockoutJS: data bind
• The library core is the notification and data
  bind engine:
  – The special ko object methods for automatic
    notification
  – The special data-bind DOM attribute for markup
    data-binding with some predefined built-in
    bindings (they can be extended using
    ko.bindingHandlers to define new ones)
BackboneJS vs KnockoutJS
• Really? My answer:
  – "You cannot be serious" (quote, Jhon McEnroe)
• They both accomplish the same tasks and
  offers the same overall benefits in terms of
  – Architecture
  – Maintainability
  – Testing
• Really: it's a matter of taste and experience
  IMHO (I come from Silverlight so I'm more
  comfortable with KnockoutJS)
Please rate this session
Scan the code, go online, rate this session

Mais conteúdo relacionado

Mais procurados

MVC pattern for widgets
MVC pattern for widgetsMVC pattern for widgets
MVC pattern for widgetsBehnam Taraghi
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
Intro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptIntro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptAndrew Lovett-Barron
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Ayes Chinmay
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery BasicsKaloyan Kosev
 
Single page webapps & javascript-testing
Single page webapps & javascript-testingSingle page webapps & javascript-testing
Single page webapps & javascript-testingsmontanari
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todaygerbille
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
Knockout.js presentation
Knockout.js presentationKnockout.js presentation
Knockout.js presentationScott Messinger
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery EssentialsMark Rackley
 
JS Single-Page Web App Essentials
JS Single-Page Web App EssentialsJS Single-Page Web App Essentials
JS Single-Page Web App EssentialsSergey Bolshchikov
 
JavaScript para Graficos y Visualizacion de Datos - BogotaJS
JavaScript para Graficos y Visualizacion de Datos - BogotaJSJavaScript para Graficos y Visualizacion de Datos - BogotaJS
JavaScript para Graficos y Visualizacion de Datos - BogotaJSphilogb
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Jeado Ko
 
e-suap - client technologies- english version
e-suap - client technologies- english versione-suap - client technologies- english version
e-suap - client technologies- english versionSabino Labarile
 

Mais procurados (20)

MVC pattern for widgets
MVC pattern for widgetsMVC pattern for widgets
MVC pattern for widgets
 
netbeans
netbeansnetbeans
netbeans
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Intro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptIntro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate Javascript
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
 
Single page webapps & javascript-testing
Single page webapps & javascript-testingSingle page webapps & javascript-testing
Single page webapps & javascript-testing
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of today
 
Jquery ui
Jquery uiJquery ui
Jquery ui
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Knockout.js presentation
Knockout.js presentationKnockout.js presentation
Knockout.js presentation
 
jQuery Introduction
jQuery IntroductionjQuery Introduction
jQuery Introduction
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 
JS Single-Page Web App Essentials
JS Single-Page Web App EssentialsJS Single-Page Web App Essentials
JS Single-Page Web App Essentials
 
JQuery UI
JQuery UIJQuery UI
JQuery UI
 
JavaScript para Graficos y Visualizacion de Datos - BogotaJS
JavaScript para Graficos y Visualizacion de Datos - BogotaJSJavaScript para Graficos y Visualizacion de Datos - BogotaJS
JavaScript para Graficos y Visualizacion de Datos - BogotaJS
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
 
e-suap - client technologies- english version
e-suap - client technologies- english versione-suap - client technologies- english version
e-suap - client technologies- english version
 

Destaque

High performance web server
High performance web serverHigh performance web server
High performance web serverWataru OKAMOTO
 
IPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHopIPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHopSteve Kamerman
 
Unit Testing in PHP
Unit Testing in PHPUnit Testing in PHP
Unit Testing in PHPRadu Murzea
 
Contributing to Drupal 8
Contributing to Drupal 8Contributing to Drupal 8
Contributing to Drupal 8Ruben Teijeiro
 
Javascript Framework Acessibiliity Review
Javascript Framework Acessibiliity ReviewJavascript Framework Acessibiliity Review
Javascript Framework Acessibiliity ReviewAimee Maree Forsstrom
 

Destaque (7)

High performance web server
High performance web serverHigh performance web server
High performance web server
 
Drupal Heroes
Drupal HeroesDrupal Heroes
Drupal Heroes
 
IPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHopIPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHop
 
Unit Testing in PHP
Unit Testing in PHPUnit Testing in PHP
Unit Testing in PHP
 
Contributing to Drupal 8
Contributing to Drupal 8Contributing to Drupal 8
Contributing to Drupal 8
 
Javascript Framework Acessibiliity Review
Javascript Framework Acessibiliity ReviewJavascript Framework Acessibiliity Review
Javascript Framework Acessibiliity Review
 
Android Concurrency Presentation
Android Concurrency PresentationAndroid Concurrency Presentation
Android Concurrency Presentation
 

Semelhante a MV* presentation frameworks in Javascript: en garde, pret, allez!

Backbone JS for mobile apps
Backbone JS for mobile appsBackbone JS for mobile apps
Backbone JS for mobile appsIvano Malavolta
 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatiasapientindia
 
jquery summit presentation for large scale javascript applications
jquery summit  presentation for large scale javascript applicationsjquery summit  presentation for large scale javascript applications
jquery summit presentation for large scale javascript applicationsDivyanshGupta922023
 
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
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applicationsIvano Malavolta
 
Knockout implementing mvvm in java script with knockout
Knockout implementing mvvm in java script with knockoutKnockout implementing mvvm in java script with knockout
Knockout implementing mvvm in java script with knockoutAndoni Arroyo
 
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
 
Planbox Backbone MVC
Planbox Backbone MVCPlanbox Backbone MVC
Planbox Backbone MVCAcquisio
 
"Umbraco MVC - a journey of discovery" - Lotte Pitcher
"Umbraco MVC - a journey of discovery" - Lotte Pitcher"Umbraco MVC - a journey of discovery" - Lotte Pitcher
"Umbraco MVC - a journey of discovery" - Lotte Pitcherlottepitcher
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVC Introduction to ASP.NET MVC
Introduction to ASP.NET MVC Joe Wilson
 
Angular JS, A dive to concepts
Angular JS, A dive to conceptsAngular JS, A dive to concepts
Angular JS, A dive to conceptsAbhishek Sur
 

Semelhante a MV* presentation frameworks in Javascript: en garde, pret, allez! (20)

MVC & backbone.js
MVC & backbone.jsMVC & backbone.js
MVC & backbone.js
 
Fundaments of Knockout js
Fundaments of Knockout jsFundaments of Knockout js
Fundaments of Knockout js
 
Backbone JS for mobile apps
Backbone JS for mobile appsBackbone JS for mobile apps
Backbone JS for mobile apps
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
[2015/2016] Backbone JS
[2015/2016] Backbone JS[2015/2016] Backbone JS
[2015/2016] Backbone JS
 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatia
 
jquery summit presentation for large scale javascript applications
jquery summit  presentation for large scale javascript applicationsjquery summit  presentation for large scale javascript applications
jquery summit presentation for large scale javascript applications
 
Training: MVVM Pattern
Training: MVVM PatternTraining: MVVM Pattern
Training: MVVM Pattern
 
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)
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applications
 
Knockout implementing mvvm in java script with knockout
Knockout implementing mvvm in java script with knockoutKnockout implementing mvvm in java script with knockout
Knockout implementing mvvm in java script with knockout
 
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
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Planbox Backbone MVC
Planbox Backbone MVCPlanbox Backbone MVC
Planbox Backbone MVC
 
MVC Framework
MVC FrameworkMVC Framework
MVC Framework
 
"Umbraco MVC - a journey of discovery" - Lotte Pitcher
"Umbraco MVC - a journey of discovery" - Lotte Pitcher"Umbraco MVC - a journey of discovery" - Lotte Pitcher
"Umbraco MVC - a journey of discovery" - Lotte Pitcher
 
MVC
MVCMVC
MVC
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVC Introduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
Angular JS, A dive to concepts
Angular JS, A dive to conceptsAngular JS, A dive to concepts
Angular JS, A dive to concepts
 

Mais de Roberto Messora

Azure Synapse: data lake & modern data warehouse dalla A alla Z
Azure Synapse: data lake &  modern data warehouse dalla A alla ZAzure Synapse: data lake &  modern data warehouse dalla A alla Z
Azure Synapse: data lake & modern data warehouse dalla A alla ZRoberto Messora
 
Azure Data Factory: l'evoluzione della specie della data integration
Azure Data Factory: l'evoluzione della specie della data integrationAzure Data Factory: l'evoluzione della specie della data integration
Azure Data Factory: l'evoluzione della specie della data integrationRoberto Messora
 
Real world Visual Studio Code
Real world Visual Studio CodeReal world Visual Studio Code
Real world Visual Studio CodeRoberto Messora
 
Architetture a Microservizi con Docker Container
Architetture a Microservizi con Docker ContainerArchitetture a Microservizi con Docker Container
Architetture a Microservizi con Docker ContainerRoberto Messora
 
Da JavaScript a TypeScript
Da JavaScript a TypeScriptDa JavaScript a TypeScript
Da JavaScript a TypeScriptRoberto Messora
 
Docker as a hosting target
Docker as a hosting targetDocker as a hosting target
Docker as a hosting targetRoberto Messora
 
Da imperativo a reattivo: Bacon.JS
Da imperativo a reattivo: Bacon.JSDa imperativo a reattivo: Bacon.JS
Da imperativo a reattivo: Bacon.JSRoberto Messora
 
Event streaming pipeline with Windows Azure and ArcGIS Geoevent extension
Event streaming pipeline with Windows Azure and ArcGIS Geoevent extensionEvent streaming pipeline with Windows Azure and ArcGIS Geoevent extension
Event streaming pipeline with Windows Azure and ArcGIS Geoevent extensionRoberto Messora
 
Code quality e test automatizzati con JavaScript
Code quality e test automatizzati con JavaScriptCode quality e test automatizzati con JavaScript
Code quality e test automatizzati con JavaScriptRoberto Messora
 
Single Page Applications
Single Page ApplicationsSingle Page Applications
Single Page ApplicationsRoberto Messora
 
Single Page web Application
Single Page web ApplicationSingle Page web Application
Single Page web ApplicationRoberto Messora
 
Javascript avanzato: sfruttare al massimo il web
Javascript avanzato: sfruttare al massimo il webJavascript avanzato: sfruttare al massimo il web
Javascript avanzato: sfruttare al massimo il webRoberto Messora
 
Self-adaptive geospatial web applications
Self-adaptive geospatial web applicationsSelf-adaptive geospatial web applications
Self-adaptive geospatial web applicationsRoberto Messora
 
Web technologies and patterns in HTML5 mapping
Web technologies and patterns in HTML5 mappingWeb technologies and patterns in HTML5 mapping
Web technologies and patterns in HTML5 mappingRoberto Messora
 

Mais de Roberto Messora (18)

Azure Synapse: data lake & modern data warehouse dalla A alla Z
Azure Synapse: data lake &  modern data warehouse dalla A alla ZAzure Synapse: data lake &  modern data warehouse dalla A alla Z
Azure Synapse: data lake & modern data warehouse dalla A alla Z
 
Azure Data Factory: l'evoluzione della specie della data integration
Azure Data Factory: l'evoluzione della specie della data integrationAzure Data Factory: l'evoluzione della specie della data integration
Azure Data Factory: l'evoluzione della specie della data integration
 
Introduzione a Docker
Introduzione a DockerIntroduzione a Docker
Introduzione a Docker
 
Seminario Big Data
Seminario Big DataSeminario Big Data
Seminario Big Data
 
Real world Visual Studio Code
Real world Visual Studio CodeReal world Visual Studio Code
Real world Visual Studio Code
 
Architetture a Microservizi con Docker Container
Architetture a Microservizi con Docker ContainerArchitetture a Microservizi con Docker Container
Architetture a Microservizi con Docker Container
 
Da JavaScript a TypeScript
Da JavaScript a TypeScriptDa JavaScript a TypeScript
Da JavaScript a TypeScript
 
Docker as a hosting target
Docker as a hosting targetDocker as a hosting target
Docker as a hosting target
 
Da imperativo a reattivo: Bacon.JS
Da imperativo a reattivo: Bacon.JSDa imperativo a reattivo: Bacon.JS
Da imperativo a reattivo: Bacon.JS
 
Event streaming pipeline with Windows Azure and ArcGIS Geoevent extension
Event streaming pipeline with Windows Azure and ArcGIS Geoevent extensionEvent streaming pipeline with Windows Azure and ArcGIS Geoevent extension
Event streaming pipeline with Windows Azure and ArcGIS Geoevent extension
 
Code quality e test automatizzati con JavaScript
Code quality e test automatizzati con JavaScriptCode quality e test automatizzati con JavaScript
Code quality e test automatizzati con JavaScript
 
Single Page Applications
Single Page ApplicationsSingle Page Applications
Single Page Applications
 
Javascript Unit Testing
Javascript Unit TestingJavascript Unit Testing
Javascript Unit Testing
 
Single Page web Application
Single Page web ApplicationSingle Page web Application
Single Page web Application
 
Javascript avanzato: sfruttare al massimo il web
Javascript avanzato: sfruttare al massimo il webJavascript avanzato: sfruttare al massimo il web
Javascript avanzato: sfruttare al massimo il web
 
Self-adaptive geospatial web applications
Self-adaptive geospatial web applicationsSelf-adaptive geospatial web applications
Self-adaptive geospatial web applications
 
Web technologies and patterns in HTML5 mapping
Web technologies and patterns in HTML5 mappingWeb technologies and patterns in HTML5 mapping
Web technologies and patterns in HTML5 mapping
 
Usare Knockout JS
Usare Knockout JSUsare Knockout JS
Usare Knockout JS
 

Último

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 

Último (20)

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 

MV* presentation frameworks in Javascript: en garde, pret, allez!

  • 1. MV* presentation frameworks in Javascript: en garde, pret, allez! Knockout JS vs Backbone JS Roberto Messora / robymes
  • 2. Thanks to the sponsors
  • 3. Poll • How many expert Javascript developers? • How many new to Javascript? • How many, at least once, did use a Javascript Presentation Framework (not plain jQuery)? • How many did come from server side development and switched to client side because of HTML5 new wave?
  • 4. Foreword • Session goals: – Why choose a client Presentation Framework when building a web application – Clarify how Presentation Patterns are implemented in Javascript – Show the differences between an MVC(*) and a MVVM Javascript Framework • Many thanks to the great TodoMVC project and its contributors (http://todomvc.com/)
  • 5. Summary • Presentation frameworks: why and when • Inside presentation patterns • BackboneJS: is it really MVC? Aka: where is my controller? • KnockoutJS: the emerging MVVM pattern that "shifted its strategy" (reinterpreting Muglia…) • BackboneJS vs KnockoutJS: the bad and the good parts
  • 6. Without a Presentation Fx TodoMVC: the plain jQuery implementation – Classical jQuery DOM management using direct tag reference + HTML templating engine – Simple DOM element event binding implementation – Monolithic single code file solution with "utilities" object containers (prone to spaghetti code) – Very difficult to test and maintain, nearly impossibile when app size scales up
  • 7. With a Presentation Fx TodoMVC: an MV* implementation (BackboneJS or KnockoutJS) – Structured DOM/element event management and binding + HTML templating engine – Structured solution organization in terms of object responsabilities and interactions (is more difficult to write spaghetti code) – It's possibile to adopt a unit testing strategy and manage complexity when app size scales up
  • 8. Presentation Fxs: a brief history A long time ago in a galaxy far, far away.... • 1979: Trygve Reenskaug designed the original pattern called Model-View-Controller-Editor in Smalltalk-80, its objective was to decouple data (Model) from UI (View) using a coordinator (Controller), enforcing separation of concerns (and accordingly single responsibilities)
  • 9. Presentation Fxs: a brief history • Over the years many other presentation design patterns came to light delivering the same main principle: decouple Model from the View – Refined versions of Model-View-Controller (MVC) – Variations of Model-View-Presenter (MVP) – Model-View-ViewModel (MVVM) • We can talk about an MV* presentation design patterns family
  • 10. Presentation Fxs: a brief history • MV* presentation design patterns – Originally designed for desktop applications and then implemented also for enterprise server side web applications – Only in recent years implemented for client side web development – Javascript implementations often differ from the original "pure" vision, maintaining the basic principles (they can be considered more "flexible")
  • 11. MVC pattern • A classical MVC pattern interpratation: – A Model: a business (or domain) object that doesn't have any knowledge about presentation – A View: the UI representation of one or more models, also contains widgets for user interactions – A Controller: the key element that reacts to user inputs doing something with model objects – A Publish/Subscribe system: an Observer pattern implementation that handles model state updates
  • 12. BackboneJS: Javascript MVC • Is one of the most used Jascript MVC Presentation Frameworks (others are EmberJS, JavascriptMVC, Spine, …) • It's more than an MVC implementation: it offers features like RESTful services, pagination, support for multiple DOM templating libraries, support for key- value observing libraries (KVO)
  • 13. BackboneJS: the Model • Business data representation: properties + operations, it doesn't have any UI knowledge • It extends Backbone.Model base object: – get and set methods to access properties – on method to listen to model changes or errors defined in the initialize method – validate method for properties validation logic – toJSON utility method for JSON serialization
  • 14. BackboneJS: the Model var MyModel = Backbone.Model.extend({ defaults: { property_01: ..., ... }, validate: function(attribs){ if (attribs.property_01 ...){...} }, initialize: function(){ this.on("error", function(model, error){ ... }; this.on("change:property_01", function(){ ... }; ... } }); var myModel = new MyModel(); var prop = myModel.get("property_01"); myModel.set({"propery_01": ...);
  • 15. BackboneJS: the View • It doesn't contain any DOM informations, it's an object that manages Model UI representation • It extends Backbone.View base object: – el attribute to define DOM related element – render method to define DOM rendering using a templating library (HandlebarsJS, Mustache, …), called on model changes – events attribute to listen to DOM events (el element and childrens)
  • 16. BackboneJS: the View var MyView = Backbone.View.extend({ el: $('#id'), render: function(event){ var tmpl = ...; //templating this.$el.html(tmpl(this.model.toJSON())); return this; //this enables calls to be chained }, events: { "click #myBtn": "myBtnClick", ... }, myBtnClick: function(event){ ... }; initialize: function(){ this.model.on('change', this.render); } }); var myView = new MyView({ model: myModel });
  • 17. BackboneJS: Collections • There is a special support for Collections of Models: – get and set methods to access specfic elements – on method to listen to elements changes – fetch method for server REST calls
  • 18. BackboneJS: the Router • This is a special concept: it handles – Application state – Connection between URLs and application events • It extends Backbone.Router base object and define a series of URL route pattern/method pairs • It needs the special Backbone.history object to be started to trigger methods when URL changes
  • 19. BackboneJS: the Router var MyRouter = Backbone.Router.extend({ routes: {'search/:query': 'search', ... }, // http://www.foo.com/#search/bar search: function(query){ ... } }); var myRouter = new MyRouter(); Backbone.history.start();
  • 20. BackboneJS: the Controller • And the very question is: where is my controller? There are any Controller man… • BackboneJS is not a pure MVC implementation: – A View can be seen as a Presenter in the MVP pattern (it contains rendering UI logic) – A View is also flexible to be a classical MVC view (if we don't write any UI logic such as DOM events callbacks) – Controller role is shared between View and Router
  • 21. MVVM pattern • It promotes a deeper separation beetween UI and business logic development: – Views designed by User Experience and Interaction experts – ViewModels and Models developed by sofwtare developer – Bridge between View and ViewModels is defined by declarative View markup data and events (commands) binding
  • 22. KnockoutJS: Javascript MVVM • It's the most used Javascript MVVM Presentation Framework (but there are a few) • It's a relatively recent library, it doesn't offer yet much support for anything else but the presentation functionalities (eg service communication, data fetching, …) • it can be used in a nearly exact Silverlight way
  • 23. KnockoutJS: The Model • Business data anemic representation, it contains only properties and their validation logic, it doesn't have any UI knowledge • It's a plain Javascript object that uses the special observable Knockout method to initialize its properties as observable objects so they can automatically notify their changes and detect their dependencies
  • 24. KnockoutJS: The Model var Todo = function(title, completed) { this.title = ko.observable(title); this.completed = ko.observable(completed); this.editing = ko.observable(false); };
  • 25. KnockoutJS: the View • It's the concrete UI: it's a portion of the HTML page DOM • It's active: it contains data and events binding so must have Model and ViewModel knowledge • It doesn't maintain any state but only the synchronization with the ViewModel • It can use DOM templating
  • 26. KnockoutJS: the View <section id="main" data-bind="visible: todos().length"> <input id="toggle-all" data-bind="checked: allCompleted" type="checkbox"> <label for="toggle-all">Mark all as complete</label> <ul id="todo-list" data-bind="foreach: filteredTodos"> <li data-bind="css: { completed: completed, editing: editing }"> <div class="view"> <input class="toggle" data-bind="checked: completed" type="checkbox"> <label data-bind="text: title, event:{dblclick: $root.editItem}"></label> <button class="destroy" data-bind="click: $root.remove"></button> </div> <input class="edit" data-bind="value: title, valueUpdate:'afterkeydown', enterKey: $root.stopEditing, selectAndFocus: editing, event: {blur: $root.stopEditing}"> </li> </ul> </section>
  • 27. KnockoutJS: the ViewModel • Can be considered as the bridge between the View and the Model, it can convert Model informations to provide the View data in the correct format • It handles the View state and reacts to its events wiring services and Model to orchestrate application logic • It's a plain Javascript object that uses the special observable, computed and observableArray Knockout methods so it can automatically notify View about its changes, it also contains methods that handles View events
  • 28. KnockoutJS: the ViewModel var ViewModel = function(todos) { var self = this; self.todos = ko.observableArray(ko.utils.arrayMap( todos, function(todo) { return new Todo(todo.title, todo.completed); })); ... self.allCompleted = ko.computed(...); ... }); var viewModel = new ViewModel(todos || []); ko.applyBindings(viewModel);
  • 29. KnockoutJS: data bind • The library core is the notification and data bind engine: – The special ko object methods for automatic notification – The special data-bind DOM attribute for markup data-binding with some predefined built-in bindings (they can be extended using ko.bindingHandlers to define new ones)
  • 30. BackboneJS vs KnockoutJS • Really? My answer: – "You cannot be serious" (quote, Jhon McEnroe) • They both accomplish the same tasks and offers the same overall benefits in terms of – Architecture – Maintainability – Testing • Really: it's a matter of taste and experience IMHO (I come from Silverlight so I'm more comfortable with KnockoutJS)
  • 31. Please rate this session Scan the code, go online, rate this session