Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.

JavaScript Application Architecture with Backbone.js

53.404 Aufrufe

Veröffentlicht am

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.


You can download the slides as PDF without having to log in at SlideShare:

Veröffentlicht in: Technologie, Bildung

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 isMathias Schäfer (molily) molily.deSoftware developer at 9elements.com
  3. 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
  4. 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
  5. Plenty of OptionsBackbone, Spine, Knockout, Angular,JavaScriptMVCDojo,YUISproutcore, Ember, Ext JS, QooxdooGWT, Cappucino
  6. 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
  7. Introducing Backbone.js
  8. Backbone.jsA simple small library (1.290 LOC) toseparate business and user interface logicGrowing popularityQuite stableActively developedFree and open source
  9. Backbone DependenciesUnderscoreas OOP and functional utility beltjQuery, Zepto, in theory Ender…for DOM Scripting and Ajax_.template, Mustache, Handlebars…for HTML templating
  10. Backbone ClassesBackbone.EventsBackbone.ModelBackbone.CollectionBackbone.ViewBackbone.HistoryBackbone.Router
  11. Backbone.EventsA mixin which allows to dispatch events andregister callbacksBackbone’s key feature, included byModel, Collection, View and HistoryMethods: on, off, trigger
  12. Backbone.ModelData storage and business logicKey feature: the attributes hashChanges on the attributes will fire changeevents
  13. Backbone.ModelModels may be retrieved from andsaved to a data storageStandard sync uses RESTful HTTPValidation constraints
  14. Backbone.Modelvar Car = Backbone.Model.extend();var car = new Car({ name: DeLorean DMC-12});alert( car.get(name) );
  15. Backbone.CollectionA list of modelsFires add, remove and reset eventsImplements Underscore list helpers(map, reduce, sort, filter…)
  16. Backbone.ViewA view owns a DOM elementKnows about its model or collectionHandles DOM events (user input)Observes model events (binding)Invokes model methods
  17. 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()));
  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 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.
  20. 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
  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-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.
  23. ApplicationArchitectureon top of Backbone.js
  24. 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”
  25. True Story http://news.ycombinator.com/item?id=3532542
  26. 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.
  27. 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.
  28. 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
  29. https://github.com/moviepilot/chaplin
  30. Meet ChaplinDerived from Moviepilot.com,a real-world single-page applicationAn 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 callsas well as object compositionCollectionView for rendering collections
  32. 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
  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 andviewsApplicationView as dispatcher andcontroller managerCreates and removes controllers,tracks the current stateRouter – ApplicationView – Controllers
  35. 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
  36. 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
  37. How to handle asynchronous dependencies?Backbone’s own event handlingPublish/SubscribeMixin jQuery Deferreds into modelsFunction 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