SlideShare ist ein Scribd-Unternehmen logo
1 von 38
Downloaden Sie, um offline zu lesen
JavaScript Application
    Architecture
    with Backbone.js
    JavaScript Conference 2012
             Düsseldorf

         Mathias Schäfer
           9elements
Hello
 my name is

Mathias Schäfer (molily)
       molily.de


Software developer at
   9elements.com
JavaScript Use Cases
            by Complexity

1. Unobtrusive JavaScript
Form validation, tabs, overlays, slideshows, date pickers, menus, autocompletion

2. JavaScript-driven Interfaces
Configurators, form widgets, heavy Ajax, like Facebook

3. Single Page Applications
Desktop-class applications and games, like GMail
Single-purpose Libraries vs.
       Full-stack Solutions
DOM scripting           Application structure

Model-view-binding      Routing & History

HTML templating         Building & Packaging

Functional & OOP        Unit testing
helpers and shims
                        Lints
Modularization &
dependancy management   Documentation
Plenty of Options

Backbone, Spine, Knockout, Angular,
JavaScriptMVC
Dojo,YUI
Sproutcore, Ember, Ext JS, Qooxdoo
GWT, Cappucino
Problems We Face
There’s no golden path
Few conventions and standards
Countless interpretations of traditional
patterns like MVC
Reinventing the wheel
If you choose one technology stack,
you’re trapped
Introducing Backbone.js
Backbone.js

A simple small library (1.290 LOC) to
separate business and user interface logic
Growing popularity
Quite stable
Actively developed
Free and open source
Backbone Dependencies

Underscore
as OOP and functional utility belt

jQuery, Zepto, in theory Ender…
for DOM Scripting and Ajax

_.template, Mustache, Handlebars…
for HTML templating
Backbone Classes

Backbone.Events
Backbone.Model
Backbone.Collection
Backbone.View
Backbone.History
Backbone.Router
Backbone.Events


A mixin which allows to dispatch events and
register callbacks
Backbone’s key feature, included by
Model, Collection, View and History
Methods: on, off, trigger
Backbone.Model


Data storage and business logic
Key feature: the attributes hash
Changes on the attributes will fire change
events
Backbone.Model


Models may be retrieved from and
saved to a data storage
Standard sync uses RESTful HTTP
Validation constraints
Backbone.Model


var Car = Backbone.Model.extend();
var car = new Car({
  name: 'DeLorean DMC-12'
});
alert( car.get('name') );
Backbone.Collection


A list of models
Fires add, remove and reset events
Implements Underscore list helpers
(map, reduce, sort, filter…)
Backbone.View

A view owns a DOM element
Knows about its model or collection
Handles DOM events (user input)
Observes model events (binding)
Invokes model methods
The Render Pattern

Views typically render model data into
HTML using a template engine
model attributes { foo: 'Hello World.' }
template         <p>{{foo}}</p>
output           <p>Hello World</p>
this.$el.html(this.template(this.model.toJSON()));
var CarView = Backbone.View.extend({
  initialize: function () {
     this.model.on('change', this.render, this);
  },
  render: function () {
     this.$el.html('Name: ' + this.model.get('name));
  }
});
var carView = new CarView({
  model: car,
  el: $('#car')
});
carView.render();
Model View Binding

You need to setup binding manually.
A view might listen to model changes and
then render itself from scratch or update the
specific DOM.
A view might listen to user input and call
model methods or dispatch events at the
model.
Backbone.Router and
     Backbone.History
A Router maps URIs to its methods
History is the actual workhorse, observes
URI changes and fires callbacks
Hash URIs (location.hash, hashchange) or
HTML5 History (pushState, popstate)
Routers usually create models and views
DOM UI
        creates and
        handles input

                    renders
 View                          Template
        observes and
        modifies


 Model
     queries and               This is how it
     syncs with
                              could look like.
Database
Backbone.js gives structure to web applications by providing models with key-value
binding and custom events, collections with a rich API of enumerable functions,
views with declarative event handling, and connects it all to your existing API over a
RESTful JSON interface.
                                       Text


                          That’s it (add routing).
                                   And that’s all.
Application
Architecture
on top of Backbone.js
Lowering Expectations

Backbone is minimalistic by design and not a
full-fledged solution.
Backbone provides no top-level patterns to
structure an application.
Not MVC, MVP or MVVM.
“There’s More Than One Way To Do It” vs.
“Convention Over Configuration”
True Story




  http://news.ycombinator.com/item?id=3532542
What is an Application?
An application has numerous screens with
specific transitions between them.
A screen typically consists of multiple views.
Modules depend on each other and
communicate with each other.
A lot of async I/O happens.
The “Todo List Example” is not such an app.
Backbone as a Basis


If you’re planning an application,
Backbone is just the beginning.
Build yourself an abstraction layer,
but don’t reinvent the wheel.
Standing on the
          Shoulders of Github
Thorax
https://github.com/walmartlabs/thorax

Marionette
https://github.com/derickbailey/backbone.marionette

Backbone Cellar
https://github.com/ccoenraets/backbone-cellar

Layoutmanager
https://github.com/tbranyen/backbone.layoutmanager

Aura
https://github.com/addyosmani/backbone-aura
https://github.com/moviepilot/chaplin
Meet Chaplin


Derived from Moviepilot.com,
a real-world single-page application
An example architecture,
not a ready-to-use library
How to DRY, enforce conventions,
   and write readable code?

Decide how create objects, fetch data,
render views, subscribe to events etc.
Extend the core classes of Backbone (Model,
Collection, View)
CoffeeScript class hierarchies with super calls
as well as object composition
CollectionView for rendering collections
How to build modules with loose
coupling for a scalable architecture?


Module encapsulation and dependency
management via RequireJS (AMD)
Share information using a Mediator object
Cross-module communication using
the Publish/Subscribe pattern
How to bundle the code for a specific
 screen (models, collections, views)?

 Backbone.Router maps URLs to its own
 methods
 Better separate routing and the code which
 creates the models and views
 Introduce Controllers and reinvent the Router
 A controller represents a screen of the
 application
How to manage top-level state?

ApplicationController for core models and
views
ApplicationView as dispatcher and
controller manager
Creates and removes controllers,
tracks the current state
Router – ApplicationView – Controllers
How to implement user
          authentication?

SessionController for user management
Creates the login dialogs
Pub/Sub-driven login process:
!login, login, !logout, logout events
Client-side login with OAuth providers like
Facebook, Google or Twitter
How to boost performance and
    prevent memory leaks?

Strict memory management and
standardized object disposal
All controllers, models, collections, views
implement a dispose destructor
Create core classes and an abstration layer
which allow for automatic disposal
How to handle asynchronous
          dependencies?


Backbone’s own event handling
Publish/Subscribe
Mixin jQuery Deferreds into models
Function wrappers and accumulators
(deferMethods, deferMethodsUntilLogin, wrapAccumulators…)
Fo Gi
                                      on
                                       rk thu
                                         m b!
Questions? Ideas? Opinions?




                                           e
    I’m molily on Twitter & Github
   mathias.schaefer@9elements.com
      contact@9elements.com

Weitere ähnliche Inhalte

Kürzlich hochgeladen

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
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
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
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
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
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
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
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
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
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 

Kürzlich hochgeladen (20)

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
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
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
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
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
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
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
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 

Empfohlen

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Empfohlen (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

JavaScript Application Architecture with Backbone.js

  • 1. JavaScript Application Architecture with Backbone.js JavaScript Conference 2012 Düsseldorf Mathias Schäfer 9elements
  • 2. Hello my name is Mathias Schäfer (molily) molily.de Software developer at 9elements.com
  • 3. JavaScript Use Cases by Complexity 1. Unobtrusive JavaScript Form validation, tabs, overlays, slideshows, date pickers, menus, autocompletion 2. JavaScript-driven Interfaces Configurators, form widgets, heavy Ajax, like Facebook 3. Single Page Applications Desktop-class applications and games, like GMail
  • 4. Single-purpose Libraries vs. Full-stack Solutions DOM scripting Application structure Model-view-binding Routing & History HTML templating Building & Packaging Functional & OOP Unit testing helpers and shims Lints Modularization & dependancy management Documentation
  • 5. Plenty of Options Backbone, Spine, Knockout, Angular, JavaScriptMVC Dojo,YUI Sproutcore, Ember, Ext JS, Qooxdoo GWT, Cappucino
  • 6. Problems We Face There’s no golden path Few conventions and standards Countless interpretations of traditional patterns like MVC Reinventing the wheel If you choose one technology stack, you’re trapped
  • 8. Backbone.js A simple small library (1.290 LOC) to separate business and user interface logic Growing popularity Quite stable Actively developed Free and open source
  • 9. Backbone Dependencies Underscore as OOP and functional utility belt jQuery, Zepto, in theory Ender… for DOM Scripting and Ajax _.template, Mustache, Handlebars… for HTML templating
  • 11. Backbone.Events A mixin which allows to dispatch events and register callbacks Backbone’s key feature, included by Model, Collection, View and History Methods: on, off, trigger
  • 12. Backbone.Model Data storage and business logic Key feature: the attributes hash Changes on the attributes will fire change events
  • 13. Backbone.Model Models may be retrieved from and saved to a data storage Standard sync uses RESTful HTTP Validation constraints
  • 14. Backbone.Model var Car = Backbone.Model.extend(); var car = new Car({ name: 'DeLorean DMC-12' }); alert( car.get('name') );
  • 15. Backbone.Collection A list of models Fires add, remove and reset events Implements Underscore list helpers (map, reduce, sort, filter…)
  • 16. Backbone.View A view owns a DOM element Knows about its model or collection Handles DOM events (user input) Observes model events (binding) Invokes model methods
  • 17. The Render Pattern Views typically render model data into HTML using a template engine model attributes { foo: 'Hello World.' } template <p>{{foo}}</p> output <p>Hello World</p> this.$el.html(this.template(this.model.toJSON()));
  • 18. var CarView = Backbone.View.extend({ initialize: function () { this.model.on('change', this.render, this); }, render: function () { this.$el.html('Name: ' + this.model.get('name)); } }); var carView = new CarView({ model: car, el: $('#car') }); carView.render();
  • 19. Model View Binding You need to setup binding manually. A view might listen to model changes and then render itself from scratch or update the specific DOM. A view might listen to user input and call model methods or dispatch events at the model.
  • 20. Backbone.Router and Backbone.History A Router maps URIs to its methods History is the actual workhorse, observes URI changes and fires callbacks Hash URIs (location.hash, hashchange) or HTML5 History (pushState, popstate) Routers usually create models and views
  • 21. DOM UI creates and handles input renders View Template observes and modifies Model queries and This is how it syncs with could look like. Database
  • 22. Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface. Text That’s it (add routing). And that’s all.
  • 24. Lowering Expectations Backbone is minimalistic by design and not a full-fledged solution. Backbone provides no top-level patterns to structure an application. Not MVC, MVP or MVVM. “There’s More Than One Way To Do It” vs. “Convention Over Configuration”
  • 25. True Story http://news.ycombinator.com/item?id=3532542
  • 26. What is an Application? An application has numerous screens with specific transitions between them. A screen typically consists of multiple views. Modules depend on each other and communicate with each other. A lot of async I/O happens. The “Todo List Example” is not such an app.
  • 27. Backbone as a Basis If you’re planning an application, Backbone is just the beginning. Build yourself an abstraction layer, but don’t reinvent the wheel.
  • 28. Standing on the Shoulders of Github Thorax https://github.com/walmartlabs/thorax Marionette https://github.com/derickbailey/backbone.marionette Backbone Cellar https://github.com/ccoenraets/backbone-cellar Layoutmanager https://github.com/tbranyen/backbone.layoutmanager Aura https://github.com/addyosmani/backbone-aura
  • 30. Meet Chaplin Derived from Moviepilot.com, a real-world single-page application An example architecture, not a ready-to-use library
  • 31. How to DRY, enforce conventions, and write readable code? Decide how create objects, fetch data, render views, subscribe to events etc. Extend the core classes of Backbone (Model, Collection, View) CoffeeScript class hierarchies with super calls as well as object composition CollectionView for rendering collections
  • 32. How to build modules with loose coupling for a scalable architecture? Module encapsulation and dependency management via RequireJS (AMD) Share information using a Mediator object Cross-module communication using the Publish/Subscribe pattern
  • 33. How to bundle the code for a specific screen (models, collections, views)? Backbone.Router maps URLs to its own methods Better separate routing and the code which creates the models and views Introduce Controllers and reinvent the Router A controller represents a screen of the application
  • 34. How to manage top-level state? ApplicationController for core models and views ApplicationView as dispatcher and controller manager Creates and removes controllers, tracks the current state Router – ApplicationView – Controllers
  • 35. How to implement user authentication? SessionController for user management Creates the login dialogs Pub/Sub-driven login process: !login, login, !logout, logout events Client-side login with OAuth providers like Facebook, Google or Twitter
  • 36. How to boost performance and prevent memory leaks? Strict memory management and standardized object disposal All controllers, models, collections, views implement a dispose destructor Create core classes and an abstration layer which allow for automatic disposal
  • 37. How to handle asynchronous dependencies? Backbone’s own event handling Publish/Subscribe Mixin jQuery Deferreds into models Function wrappers and accumulators (deferMethods, deferMethodsUntilLogin, wrapAccumulators…)
  • 38. Fo Gi on rk thu m b! Questions? Ideas? Opinions? e I’m molily on Twitter & Github mathias.schaefer@9elements.com contact@9elements.com

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n