SlideShare una empresa de Scribd logo
1 de 22
Descargar para leer sin conexión
MVC on the server and
     on the client
 How to integrate Spring MVC and
           Backbone.js



                 Sebastiano Armeli-Battana
                         @sebarmeli

July 10 , 2012                           JAXConf, San Francisco
Model - View - Controller

Architectural Design Pattern                 Model




Business logic / presentation layer
                                      View           Controller


Reusability


Components isolation
Passive and Active MVC
                        View                Model



Passive Approach
                               Controller




                      Controller            View

Active Approach
                                            Observer
                                             pattern
                                   Model
Java and MVC

Model                       POJO


View                         JSP


Controller                  Servlet
Spring MVC
Front Controller pattern
Getting started
web.xml
<servlet>
                <servlet-name>dispatcher</servlet-name>
                <servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
        </servlet>

       <servlet-mapping>
               <servlet-name>dispatcher</servlet-name>
               <url-pattern>/</url-pattern>
       </servlet-mapping>
Spring MVC 3 configurations
dispatcher-servlet.xml
<context:component-scan base-package=”com.example”

<mvc:annotation-driven />

<mvc:view-controller path=”/page1” view-name=”view1” />

<mvc:resources mapping=”/resources/**” location=”/resources” />


<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
   <property name=”mediaTypes”>
        ...
   </property>
   <property name=”viewResolvers”>
        ...
   </property>
</bean>
Spring MVC in action
     @Controller
     public class ContactsController {

         @Autowired
         private ContactService service;
  CONTROLLER
       @RequestMapping(value=”/list”, method = RequestMethod.GET)
         public @ResponseBody List<Contact> getContacts() {

             return service.getContacts();
         }
     }




Service Layer (@Service)
                                                  VIEW
   DAO (@Repository)                  [{
                                       “id” : 31,
                                       “firstname” : “LeBron”,
                                       “lastname” : “James”,

      MODEL
                                       “telephone” : “111-222-3333”
                                      }]
What about the Model?
         @Entity
         @Table(name=”Contacts”)
         public class Contact {

         @Id
         @Column(name = ”ID”)
         @GeneratedValue
         private Integer id;

         @Column(name = “FIRSTNAME”)
         private String firstname;

         public String getFirstname(){
           return firstname;
         }

         public void setFirstname(){
           this.firstname = firstname;
         }

         ...
         }
Why MVC in JavaScript ??

AJAX application with lots of JS code


Managing efficiently jQuery selectors and callbacks


Decoupling components


Simplify communication with RESTful WS
JavaScript and MVC

Model                    JS object


View                      HTML
                         Template

Controller               JS object
JavaScript ‘MVC’ / ‘MV*’ Library


Dependencies:
     - Underscore.js               $(function(){

 - json2.js                         // stuff here
                                    Backbone.history.start();
     - jQuery / Zepto              });




Single Page Application (SPA)


Connection to API over RESTful JSON interface
Model
Represents data (JSON)    {
                           “id” : 31,
                           “firstname” : “LeBron”,
                           “lastname” : “James”,
                           “telephone” : “111-222-3333”
                          }



Key-value attributes      MyApp.Contact = Backbone.Model.extend({

                          defaults: {
                             firstname : “”,
                             lastname : “”,
                             telephone : “”
                          },
Domain-specific methods   getFullName: function() {
                             return this.fullname + this.lastname;
                          },

                          validate: function(){}

                          });
Custom events &           var newContact = new MyApp.Contact();
Validation                newContact.set({‘firstname’ : ‘Lebron'});
Collection
Set of models             MyApp.Contacts = Backbone.Collection.extend({

                           model: MyAppp.Contact,

                           url: ‘/list’

                          });

url / url()               var collection = new MyApp.Contacts(),
                           model1 = new MyApp.Contact();

                          collection.add(model1);




create() / add() / remove()/ reset()



get() / getByCid()
Router

Routing client-side “states”
                         MyApp.AppRouter = Backbone.Router.extend({

                          routes: {
                             “” : “index”,
                             “list-contacts” : “listContacts”
“routes” map              },

                          index : function() {
                            // stuff here
                          }

                          listContacts : function() {
                             // stuff here
List of actions           }
                         });

                         var router = new MyApp.AppRouter();
View

Logical view     MyApp.ListContactsView = Backbone.View.extend({

                 className: ‘list’,

                 initialize: function(){
                    // stuff here

‘el’ attribute   },

                 events: {
                   “click a”: “goToLink”
                 }


Event handlers   goToLink : function() {}

                  render : function(){
                 this.$el.html(“<p>Something</p>”);
                  }
                 });

render()         var view = new MyApp.ListContactsView();
                 view.render();
View + HTML
                                                 Template
  Pick one client-side templating engine!
  (E.g. Handlebars.js, Haml-js, ICanHaz.js)

  Isolate HTML into Template
View                                                  ICanHaz.js
MyApp.ContactsView = Backbone.View.extend({

 ...
                                              HTML template
 render : function(){
                                              <script type=”text/html”
var obj = this.model.toJSON(),                id=”contactTemplate”>
 template = ich.contactTemplate(obj);         <p>First name : {{firstname}}</p>
                                              <p>Last name : {{lastname}}</p>
this.$el.html(template);                      <p>Telephone : {{telephone}}</p>
 }                                            script>
});

var view = new MyApp.ContactsView();
view.render();
Model-View binding

var view = Backbone.View.extend({

initialize: function(){

this.model.bind(“change”, this.render, this);

},

render : function(){}

});
Backbone.js and REST
Backbone.sync(): CRUD => HTTP Methods
POST

       collection.create(model) / model.save()
GET

          collection.fetch() / model.fetch()
PUT

                    model.save()
DELETE

                  model.destroy()


(jQuery/Zepto).ajax()
‘My Contacts’ Application

                      REST API

                  URI           HTTP Method

                  /list            GET
                  /list           POST
            /list/{contactId}      PUT
            /list/{contactId}    DELETE
Questions?

Más contenido relacionado

La actualidad más candente

Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
Jarod Ferguson
 

La actualidad más candente (19)

Data binding w Androidzie
Data binding w AndroidzieData binding w Androidzie
Data binding w Androidzie
 
Injection de dépendances dans Symfony >= 3.3
Injection de dépendances dans Symfony >= 3.3Injection de dépendances dans Symfony >= 3.3
Injection de dépendances dans Symfony >= 3.3
 
Speaking Eloquent Eloquently
Speaking Eloquent EloquentlySpeaking Eloquent Eloquently
Speaking Eloquent Eloquently
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Metaworks3
Metaworks3Metaworks3
Metaworks3
 
droidQuery: The Android port of jQuery
droidQuery: The Android port of jQuerydroidQuery: The Android port of jQuery
droidQuery: The Android port of jQuery
 
Modules and injector
Modules and injectorModules and injector
Modules and injector
 
Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databinding
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
 
Before there was Hoop Dreams, there was McDonald's: Strange and Beautiful
Before there was Hoop Dreams, there was McDonald's: Strange and BeautifulBefore there was Hoop Dreams, there was McDonald's: Strange and Beautiful
Before there was Hoop Dreams, there was McDonald's: Strange and Beautiful
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
 
Jsf
JsfJsf
Jsf
 
Web 6 | JavaScript DOM
Web 6 | JavaScript DOMWeb 6 | JavaScript DOM
Web 6 | JavaScript DOM
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom Tags
 

Destacado

From Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEEFrom Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEE
jaxconf
 
The economies of scaling software - Abdel Remani
The economies of scaling software - Abdel RemaniThe economies of scaling software - Abdel Remani
The economies of scaling software - Abdel Remani
jaxconf
 

Destacado (16)

The Evolution of Java Persistence in EclipseLink: Shaun Smith
The Evolution of Java Persistence in EclipseLink: Shaun SmithThe Evolution of Java Persistence in EclipseLink: Shaun Smith
The Evolution of Java Persistence in EclipseLink: Shaun Smith
 
Architecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko GargentaArchitecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko Gargenta
 
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
 
JSF2 Composite Components - Ian Hlavats
JSF2 Composite Components - Ian HlavatsJSF2 Composite Components - Ian Hlavats
JSF2 Composite Components - Ian Hlavats
 
From Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEEFrom Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEE
 
Understanding Java Garbage Collection and What You Can Do About It: Gil Tene
Understanding Java Garbage Collection and What You Can Do About It: Gil TeneUnderstanding Java Garbage Collection and What You Can Do About It: Gil Tene
Understanding Java Garbage Collection and What You Can Do About It: Gil Tene
 
Future of the Web - Yehuda Katz
Future of the Web - Yehuda KatzFuture of the Web - Yehuda Katz
Future of the Web - Yehuda Katz
 
The New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
The New Reality: the Role of PaaS in Technology Innovation - Franklin HerbasThe New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
The New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long
 
The Spring 4 Update - Josh Long
The Spring 4 Update - Josh LongThe Spring 4 Update - Josh Long
The Spring 4 Update - Josh Long
 
The economies of scaling software - Abdel Remani
The economies of scaling software - Abdel RemaniThe economies of scaling software - Abdel Remani
The economies of scaling software - Abdel Remani
 
Building an Impenetrable ZooKeeper - Kathleen Ting
Building an Impenetrable ZooKeeper - Kathleen TingBuilding an Impenetrable ZooKeeper - Kathleen Ting
Building an Impenetrable ZooKeeper - Kathleen Ting
 
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
 
What you need to know about Lambdas - Jamie Allen
What you need to know about Lambdas - Jamie AllenWhat you need to know about Lambdas - Jamie Allen
What you need to know about Lambdas - Jamie Allen
 
Java PaaS Comparisons - Khanderao Kand
Java PaaS Comparisons - Khanderao KandJava PaaS Comparisons - Khanderao Kand
Java PaaS Comparisons - Khanderao Kand
 
Apache Hadoop and its role in Big Data architecture - Himanshu Bari
Apache Hadoop and its role in Big Data architecture - Himanshu BariApache Hadoop and its role in Big Data architecture - Himanshu Bari
Apache Hadoop and its role in Big Data architecture - Himanshu Bari
 

Similar a MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone.js: Sebastiano Armeli-Battana

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
Spike Brehm
 

Similar a MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone.js: Sebastiano Armeli-Battana (20)

Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
Emberjs as a rails_developer
Emberjs as a rails_developer Emberjs as a rails_developer
Emberjs as a rails_developer
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
 
Unit 07: Design Patterns and Frameworks (3/3)
Unit 07: Design Patterns and Frameworks (3/3)Unit 07: Design Patterns and Frameworks (3/3)
Unit 07: Design Patterns and Frameworks (3/3)
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
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
 
Java beans
Java beansJava beans
Java beans
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2py
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
 
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
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
 
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone.js: Sebastiano Armeli-Battana

  • 1. MVC on the server and on the client How to integrate Spring MVC and Backbone.js Sebastiano Armeli-Battana @sebarmeli July 10 , 2012 JAXConf, San Francisco
  • 2. Model - View - Controller Architectural Design Pattern Model Business logic / presentation layer View Controller Reusability Components isolation
  • 3. Passive and Active MVC View Model Passive Approach Controller Controller View Active Approach Observer pattern Model
  • 4. Java and MVC Model POJO View JSP Controller Servlet
  • 6. Getting started web.xml <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
  • 7. Spring MVC 3 configurations dispatcher-servlet.xml <context:component-scan base-package=”com.example” <mvc:annotation-driven /> <mvc:view-controller path=”/page1” view-name=”view1” /> <mvc:resources mapping=”/resources/**” location=”/resources” /> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name=”mediaTypes”> ... </property> <property name=”viewResolvers”> ... </property> </bean>
  • 8. Spring MVC in action @Controller public class ContactsController { @Autowired private ContactService service; CONTROLLER @RequestMapping(value=”/list”, method = RequestMethod.GET) public @ResponseBody List<Contact> getContacts() { return service.getContacts(); } } Service Layer (@Service) VIEW DAO (@Repository) [{ “id” : 31, “firstname” : “LeBron”, “lastname” : “James”, MODEL “telephone” : “111-222-3333” }]
  • 9. What about the Model? @Entity @Table(name=”Contacts”) public class Contact { @Id @Column(name = ”ID”) @GeneratedValue private Integer id; @Column(name = “FIRSTNAME”) private String firstname; public String getFirstname(){ return firstname; } public void setFirstname(){ this.firstname = firstname; } ... }
  • 10.
  • 11. Why MVC in JavaScript ?? AJAX application with lots of JS code Managing efficiently jQuery selectors and callbacks Decoupling components Simplify communication with RESTful WS
  • 12. JavaScript and MVC Model JS object View HTML Template Controller JS object
  • 13. JavaScript ‘MVC’ / ‘MV*’ Library Dependencies: - Underscore.js $(function(){ - json2.js // stuff here Backbone.history.start(); - jQuery / Zepto }); Single Page Application (SPA) Connection to API over RESTful JSON interface
  • 14. Model Represents data (JSON) { “id” : 31, “firstname” : “LeBron”, “lastname” : “James”, “telephone” : “111-222-3333” } Key-value attributes MyApp.Contact = Backbone.Model.extend({ defaults: { firstname : “”, lastname : “”, telephone : “” }, Domain-specific methods getFullName: function() { return this.fullname + this.lastname; }, validate: function(){} }); Custom events & var newContact = new MyApp.Contact(); Validation newContact.set({‘firstname’ : ‘Lebron'});
  • 15. Collection Set of models MyApp.Contacts = Backbone.Collection.extend({ model: MyAppp.Contact, url: ‘/list’ }); url / url() var collection = new MyApp.Contacts(), model1 = new MyApp.Contact(); collection.add(model1); create() / add() / remove()/ reset() get() / getByCid()
  • 16. Router Routing client-side “states” MyApp.AppRouter = Backbone.Router.extend({ routes: { “” : “index”, “list-contacts” : “listContacts” “routes” map }, index : function() { // stuff here } listContacts : function() { // stuff here List of actions } }); var router = new MyApp.AppRouter();
  • 17. View Logical view MyApp.ListContactsView = Backbone.View.extend({ className: ‘list’, initialize: function(){ // stuff here ‘el’ attribute }, events: { “click a”: “goToLink” } Event handlers goToLink : function() {} render : function(){ this.$el.html(“<p>Something</p>”); } }); render() var view = new MyApp.ListContactsView(); view.render();
  • 18. View + HTML Template Pick one client-side templating engine! (E.g. Handlebars.js, Haml-js, ICanHaz.js) Isolate HTML into Template View ICanHaz.js MyApp.ContactsView = Backbone.View.extend({ ... HTML template render : function(){ <script type=”text/html” var obj = this.model.toJSON(), id=”contactTemplate”> template = ich.contactTemplate(obj); <p>First name : {{firstname}}</p> <p>Last name : {{lastname}}</p> this.$el.html(template); <p>Telephone : {{telephone}}</p> } script> }); var view = new MyApp.ContactsView(); view.render();
  • 19. Model-View binding var view = Backbone.View.extend({ initialize: function(){ this.model.bind(“change”, this.render, this); }, render : function(){} });
  • 20. Backbone.js and REST Backbone.sync(): CRUD => HTTP Methods POST collection.create(model) / model.save() GET collection.fetch() / model.fetch() PUT model.save() DELETE model.destroy() (jQuery/Zepto).ajax()
  • 21. ‘My Contacts’ Application REST API URI HTTP Method /list GET /list POST /list/{contactId} PUT /list/{contactId} DELETE