• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
JavaScript Application Architecture with Backbone.js
 

JavaScript Application Architecture with Backbone.js

on

  • 34,883 views

Slides of my talk at the JavaScript Conference, February 27th, 2012 in Düsseldorf, Germany ...

Slides of my talk at the JavaScript Conference, February 27th, 2012 in Düsseldorf, Germany

Several JavaScript libraries which implement the Model-View-Controller pattern recently gained attention. Only few of these libraries offer a superstructure which manages the individual models, views and controllers. It’s easy to set up a simple MVC example, but an application with multiple complex interfaces will need a sophisticated overall architecture.

The talk started with the popular Backbone.js library as a basis, discussed its shortcomings and presented Chaplin.js, a field-tested application architecture.

http://chaplinjs.org/
https://github.com/chaplinjs/chaplin

You can download the slides as PDF without having to log in at SlideShare:
http://molily.de/assets/jsconf.pdf

Statistics

Views

Total Views
34,883
Views on SlideShare
27,634
Embed Views
7,249

Actions

Likes
74
Downloads
518
Comments
9

22 Embeds 7,249

http://mobicon.tistory.com 3621
http://molily.de 2889
http://www.scoop.it 477
http://lanyrd.com 127
http://fe.com 44
http://web.vabx.com 32
http://www.techgig.com 14
http://kathrynaaker.tumblr.com 9
http://lions.rr.com 8
http://localhost 5
http://us-w1.rockmelt.com 4
http://webcache.googleusercontent.com 3
http://beta.jolicloud.co 3
http://127.0.0.1 3
https://twitter.com 2
http://www.lifeyun.com 2
https://duckduckgo.com 1
http://feeds.feedburner.com 1
http://search.yahoo.com 1
http://www.google.com 1
http://pinterest.com 1
http://www.pearltrees.com 1
More...

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

CC Attribution License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

19 of 9 previous next Post a comment

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

JavaScript Application Architecture with Backbone.js JavaScript Application Architecture with Backbone.js Presentation Transcript

  • JavaScript Application Architecture with Backbone.js JavaScript Conference 2012 Düsseldorf Mathias Schäfer 9elements
  • Hello my name isMathias Schäfer (molily) molily.deSoftware developer at 9elements.com
  • JavaScript Use Cases by Complexity1. Unobtrusive JavaScriptForm validation, tabs, overlays, slideshows, date pickers, menus, autocompletion2. JavaScript-driven InterfacesConfigurators, form widgets, heavy Ajax, like Facebook3. Single Page ApplicationsDesktop-class applications and games, like GMail
  • Single-purpose Libraries vs. Full-stack SolutionsDOM scripting Application structureModel-view-binding Routing & HistoryHTML templating Building & PackagingFunctional & OOP Unit testinghelpers and shims LintsModularization &dependancy management Documentation
  • Plenty of OptionsBackbone, Spine, Knockout, Angular,JavaScriptMVCDojo,YUISproutcore, Ember, Ext JS, QooxdooGWT, Cappucino
  • Problems We FaceThere’s no golden pathFew conventions and standardsCountless interpretations of traditionalpatterns like MVCReinventing the wheelIf you choose one technology stack,you’re trapped
  • Introducing Backbone.js
  • Backbone.jsA simple small library (1.290 LOC) toseparate business and user interface logicGrowing popularityQuite stableActively developedFree and open source
  • Backbone DependenciesUnderscoreas OOP and functional utility beltjQuery, Zepto, in theory Ender…for DOM Scripting and Ajax_.template, Mustache, Handlebars…for HTML templating
  • Backbone ClassesBackbone.EventsBackbone.ModelBackbone.CollectionBackbone.ViewBackbone.HistoryBackbone.Router
  • Backbone.EventsA mixin which allows to dispatch events andregister callbacksBackbone’s key feature, included byModel, Collection, View and HistoryMethods: on, off, trigger
  • Backbone.ModelData storage and business logicKey feature: the attributes hashChanges on the attributes will fire changeevents
  • Backbone.ModelModels may be retrieved from andsaved to a data storageStandard sync uses RESTful HTTPValidation constraints
  • Backbone.Modelvar Car = Backbone.Model.extend();var car = new Car({ name: DeLorean DMC-12});alert( car.get(name) );
  • Backbone.CollectionA list of modelsFires add, remove and reset eventsImplements Underscore list helpers(map, reduce, sort, filter…)
  • Backbone.ViewA view owns a DOM elementKnows about its model or collectionHandles DOM events (user input)Observes model events (binding)Invokes model methods
  • The Render PatternViews typically render model data intoHTML using a template enginemodel 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 BindingYou need to setup binding manually.A view might listen to model changes andthen render itself from scratch or update thespecific DOM.A view might listen to user input and callmodel methods or dispatch events at themodel.
  • Backbone.Router and Backbone.HistoryA Router maps URIs to its methodsHistory is the actual workhorse, observesURI changes and fires callbacksHash URIs (location.hash, hashchange) orHTML5 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-valuebinding 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 aRESTful JSON interface. Text That’s it (add routing). And that’s all.
  • ApplicationArchitectureon top of Backbone.js
  • Lowering ExpectationsBackbone is minimalistic by design and not afull-fledged solution.Backbone provides no top-level patterns tostructure 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 withspecific transitions between them.A screen typically consists of multiple views.Modules depend on each other andcommunicate with each other.A lot of async I/O happens.The “Todo List Example” is not such an app.
  • Backbone as a BasisIf 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 GithubThoraxhttps://github.com/walmartlabs/thoraxMarionettehttps://github.com/derickbailey/backbone.marionetteBackbone Cellarhttps://github.com/ccoenraets/backbone-cellarLayoutmanagerhttps://github.com/tbranyen/backbone.layoutmanagerAurahttps://github.com/addyosmani/backbone-aura
  • https://github.com/moviepilot/chaplin
  • Meet ChaplinDerived from Moviepilot.com,a real-world single-page applicationAn 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 callsas well as object compositionCollectionView for rendering collections
  • How to build modules with loosecoupling for a scalable architecture?Module encapsulation and dependencymanagement via RequireJS (AMD)Share information using a Mediator objectCross-module communication usingthe 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 andviewsApplicationView as dispatcher andcontroller managerCreates and removes controllers,tracks the current stateRouter – ApplicationView – Controllers
  • How to implement user authentication?SessionController for user managementCreates the login dialogsPub/Sub-driven login process:!login, login, !logout, logout eventsClient-side login with OAuth providers likeFacebook, Google or Twitter
  • How to boost performance and prevent memory leaks?Strict memory management andstandardized object disposalAll controllers, models, collections, viewsimplement a dispose destructorCreate core classes and an abstration layerwhich allow for automatic disposal
  • How to handle asynchronous dependencies?Backbone’s own event handlingPublish/SubscribeMixin jQuery Deferreds into modelsFunction 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