Where to start•   Consumerisation of technology has had a large impact on how we    build apps•   Affordable portable devi...
Impacts on development•   Multi tenanted development teams•   HTML stack / .net stack / iOS stack / Java stack•   Manageme...
Snooze you loose•   Building x-platform x-device app•   Targeting wp7 and windows 7 tablet•   Performance problems with .n...
A time for change•   Build apps that meet these needs•   Touch based•   Mouse based•   Consumable on anything anywhere•   ...
Somethings never change•   Software craftsmanship•   Still face the same problems•   Changing implementation language does...
Somethings do changeImprovements in•   Browser performance•   HTML•   CSS•   ECMA Script•   Frameworks•   Development tools
And so the journey beginsClient side Architecture   Async communication mechanism with server   MV* framework   Local s...
Client side Architecture   Async communication mechanism with server   MV* framework   Local storage mechanism   Respo...
Async Communication•   Endpoints are REST based•   Endpoints support JSON and Xml – JSON is preferred•   jQuery $.ajax(que...
Client side Architecture   Async communication mechanism with server   MV* framework   Local storage mechanism   Respo...
MV* framework•   Extensive range of JS frameworks that support MVC, MVP and MVVM•   YAFS! – each week there seems to be a ...
MV* framework – KO jsI want something that will make it easy to build complex dynamic UIs witha clean underlying data mode...
MV* framework – backbone jsI want something flexible which offers a minimalist solution to separatingconcerns in my applic...
Client side Architecture   Async communication mechanism with server   MV* framework   Local storage mechanism   Respo...
Local Storage - amplify•   Amplifyjs http://amplifyjs.com/•   Simple to use as everything is all done via key value pairs•...
Client side Architecture   Async communication mechanism with server   MV* framework   Local storage mechanism   Respo...
Responsive layout•   As I eluded earlier supporting x-devices, x-browser means that we    need to up our game•   We want t...
Responsive layout - bootstrap•   Bootstrap http://twitter.github.com/bootstrap/•   Bootstrap provides everything that we n...
Client side Architecture   Async communication mechanism with server   MV* framework   Local storage mechanism   Respo...
View Layout Management•   Layout Manager https://github.com/tbranyen/backbone.layoutmanager•   When building a complex UI ...
Single Page App Design•   Taking Ajax to the next level•   Provide a UX which is closer to an app or desktop app UX•   Our...
Ajax everything…•   Dynamically loading templates•   Html templates are defined on the server and loaded async when    req...
Everything ajax…•   Asynchronous Module Definitions•   Use Requirejs http://requirejs.org/••   Provides a mechanism for in...
Client side Architecture   Async communication mechanism with server   MV* framework   Local storage mechanism   Respo...
Data Management•   Backbone paginator    https://github.com/addyosmani/backbone.paginator•   Pagination of data•   Client ...
Client side Architecture   Async communication mechanism with server   MV* framework   Local storage mechanism   Respo...
UI Interactions•   jQuery does everything that you need and more•   jQuery and Backbone play nice together•   jQuery Mobile
Client side ArchitectureBucket list   Async communication mechanism with server   MV* framework   Local storage mechani...
Tool up•   BDD / TDD•   Grunt•   Sublime Text Editor•   Development server
Tool up•   BDD / TDD•   Grunt•   Sublime Text Editor•   Development server
Jasmine•   Jasmine http://pivotal.github.com/jasmine/•   Does not depend on any other JS framework                        ...
Tool up•   BDD / TDD•   Grunt•   Sublime Text Editor•   Development server
Grunt•   grunt http://gruntjs.com/•   Requires Node – install using npm grunt•   Provides the ability for developers to ha...
GruntBuild Script• Run tests• JSHint code  • http://www.jshint.com/• Uglification / Compression of code  • https://github....
Tool up•   BDD / TDD•   Grunt•   Sublime Text Editor•   Development server
Sublime text editor•   Nuget style package management console•   Support for backbone snippets•   Support for jQuery snipp...
Tool up•   BDD / TDD•   Grunt•   Sublime Text Editor•   Development server
Web Matrix•   Local Server for running web apps•   Awesome for deployment to Azure•   Has its own editor
Backbone                                    viewEventsModelsCollections              router            eventsViewsRouters ...
Router•   Provides methods for routing client-side pages, and connecting them    to actions and events•   Until recently, ...
Routervar Workspace = Backbone.Router.extend({  routes: {     "help":                      "help",     // #help     "searc...
Events•   Events is a module that can be mixed into any object•   Provides the ability to bind and trigger custom named ev...
Models•   Models are at the heart of any js app•   Models contain interactive data as well as a large part of the logic   ...
Collections•   Collections are ordered sets of models•   Bind “change” events to be notified when any model in the collect...
CollectionsFetch()•   Call to populate collection with data
CollectionsSync(crud method, model, options callback)•   CRUD – Create, Read, Update or Delete•   Model – Model to be oper...
CollectionsCRUD to REST• Create -> POST     /collection• Read -> GET        /collection[id]• Update -> PUT      /collectio...
Views•   More convention than they are code•   They dont determine anything about your HTML or CSS for you, and    can be ...
Backbone                      view           router            events                    collection                 model ...
MVVM                 view       View                        events       model               collection                 mo...
Underscore•   http://underscorejs.org/•   80 odd helper functions•   Works seamlessly with jQuery and Backbone•   Provides...
UnderscoreShaping data• each• map• where• sortBy, groupBy
UnderscoreTemplatingWorks in the same way as other templating frameworks<td>    <%=       typeof(model.get("foo")) !== und...
Putting it all together
events dom                                               layout                         view                              ...
Web Request   Initialise App    Router       Collection                                Layout Fetch data   Render Page    ...
Web app•   News reader – uses Guardian API•   Router / Models / Views•   Pagination•   Local Storage•   View Management
Main layout                                 Section List                Section List Item                 Main.html       ...
<div class="nav-collapse sectionListView"></div><div id="sectionHeaderView" class="hero-unit sectionHeaderView"></div>    ...
<div class="nav-collapse sectionListView"></div>  <div id="sectionHeaderView" class="hero-unit sectionHeaderView"></div>  ...
Winjs•   Provides access to winrt interfaces via javascript•   Uses the chakra engine same engine used in IE10•   Introduc...
Winjs and backbone•   Use backbone for all our data•   Use winjs as our UI Framework•   Ability to integrate and weave the...
Putting it all together
eventsdom                      view                                      events       navigation                          ...
App Load     Initialise App   Navigation    Collection               Render          ProcessFetch data                    ...
Winjs app•   Reader port to windows 8•   Changes to note   Change in User Experience impacts how and what data needs to b...
Looking back•   Overview of some useful js frameworks that allow us to create    maintainable client side apps in js/html/...
Looking forwards•   Improvements in the frameworks and plugins•   Improvements in scaffolding for building apps•   Better ...
Building SPA’s (Single Page App) with Backbone.js
Building SPA’s (Single Page App) with Backbone.js
Building SPA’s (Single Page App) with Backbone.js
Building SPA’s (Single Page App) with Backbone.js
Building SPA’s (Single Page App) with Backbone.js
Building SPA’s (Single Page App) with Backbone.js
Building SPA’s (Single Page App) with Backbone.js
Building SPA’s (Single Page App) with Backbone.js
Upcoming SlideShare
Loading in …5
×

Building SPA’s (Single Page App) with Backbone.js

5,184 views

Published on

More info on http://www.techdays.be

Building SPA’s (Single Page App) with Backbone.js

  1. 1. Where to start• Consumerisation of technology has had a large impact on how we build apps• Affordable portable devices means that consumers care more about mobility• Customers desire their product to be available on a wide range of devices for consumers
  2. 2. Impacts on development• Multi tenanted development teams• HTML stack / .net stack / iOS stack / Java stack• Management of source code, testing, maintainability, consistency
  3. 3. Snooze you loose• Building x-platform x-device app• Targeting wp7 and windows 7 tablet• Performance problems with .net client side implementation• Rebuilt in html and js
  4. 4. A time for change• Build apps that meet these needs• Touch based• Mouse based• Consumable on anything anywhere• Development costs
  5. 5. Somethings never change• Software craftsmanship• Still face the same problems• Changing implementation language does not make it easier• Actually some of the problems get bigger…much bigger!• Browser inconsistency
  6. 6. Somethings do changeImprovements in• Browser performance• HTML• CSS• ECMA Script• Frameworks• Development tools
  7. 7. And so the journey beginsClient side Architecture Async communication mechanism with server MV* framework Local storage mechanism Responsive web pages View management Data management UI interactions to enhance the experience
  8. 8. Client side Architecture Async communication mechanism with server MV* framework Local storage mechanism Responsive web pages View management Data management UI interactions to enhance the experience
  9. 9. Async Communication• Endpoints are REST based• Endpoints support JSON and Xml – JSON is preferred• jQuery $.ajax(query options)$.ajax({ type: "POST", url: "some.php", data: { name: "John", location: “Birmingham" }}).done(function( msg ) { alert( "Data Saved: " + msg );});
  10. 10. Client side Architecture Async communication mechanism with server MV* framework Local storage mechanism Responsive web pages View management Data management UI interactions to enhance the experience
  11. 11. MV* framework• Extensive range of JS frameworks that support MVC, MVP and MVVM• YAFS! – each week there seems to be a new one• IMHO there should be more focus on scaffolding tools• Confused! Try this out! http://todomvc.com/
  12. 12. MV* framework – KO jsI want something that will make it easy to build complex dynamic UIs witha clean underlying data model and declarative bindings.It should automatically update my UI on model changes using two-waybindings and support dependency tracking of model data.I should be able to use it with whatever framework I prefer, or even anexisting app.It should also come with templating built-in and be easily extensible.Resource: Addy Osmani
  13. 13. MV* framework – backbone jsI want something flexible which offers a minimalist solution to separatingconcerns in my application.It should support a persistence layer and RESTful sync, models, views(with controllers), event-driven communication, templating and routing.It should be imperative, allowing one to update the View when a modelchanges.I’d like some decisions about the architecture left up to me. Ideally, manylarge companies have used the solution to build non-trivial applicationsResource: Addy Osmani
  14. 14. Client side Architecture Async communication mechanism with server MV* framework Local storage mechanism Responsive web pages View management Data management UI interactions to enhance the experience
  15. 15. Local Storage - amplify• Amplifyjs http://amplifyjs.com/• Simple to use as everything is all done via key value pairs• Amplify works out what browser your app is running in and makes a choice which local storage option to use  Local Storage if available (latest browsers)  Cookie in older browsers
  16. 16. Client side Architecture Async communication mechanism with server MV* framework Local storage mechanism Responsive web pages View management Data management UI interactions to enhance the experience
  17. 17. Responsive layout• As I eluded earlier supporting x-devices, x-browser means that we need to up our game• We want to be pragmatic about it and thus avoid tumbling/cascading conditional blocks of code to handle the different browser
  18. 18. Responsive layout - bootstrap• Bootstrap http://twitter.github.com/bootstrap/• Bootstrap provides everything that we need to build responsive web pages• Provides a 12-column responsive grid• Builds on CSS media queries to provide responsive functionality• Uses LESS to help with maintainability of CSS from a Developer prospective
  19. 19. Client side Architecture Async communication mechanism with server MV* framework Local storage mechanism Responsive web pages View management Data management UI interactions to enhance the experience
  20. 20. View Layout Management• Layout Manager https://github.com/tbranyen/backbone.layoutmanager• When building a complex UI there is always the issue of how we manage our views and also our sub-views• Reusable views• To be pragmatic we want to insure that we adhere to the DRY principle• Backbone does not provide a formalised way for how we do templatingttps://github.com/tbranyen/backbone.layoutmanager
  21. 21. Single Page App Design• Taking Ajax to the next level• Provide a UX which is closer to an app or desktop app UX• Our application UX all happens in a single page and is not spread across multiple pages• Don’t think about a web site think about an app a web app experience
  22. 22. Ajax everything…• Dynamically loading templates• Html templates are defined on the server and loaded async when required• Html templates are associated with the backbone view• Layout manager provides a strategy for managing views
  23. 23. Everything ajax…• Asynchronous Module Definitions• Use Requirejs http://requirejs.org/•• Provides a mechanism for include/import/require• Ability to load nested dependencies• Ease of use for developer but then backed by an optimisation tool that helps with deployment
  24. 24. Client side Architecture Async communication mechanism with server MV* framework Local storage mechanism Responsive web pages View management Data management UI interactions to enhance the experience
  25. 25. Data Management• Backbone paginator https://github.com/addyosmani/backbone.paginator• Pagination of data• Client side pagination• Server side paginationhttps://github.com/addyosmani/backbone.paginator
  26. 26. Client side Architecture Async communication mechanism with server MV* framework Local storage mechanism Responsive web pages View management Data management UI interactions to enhance the experience
  27. 27. UI Interactions• jQuery does everything that you need and more• jQuery and Backbone play nice together• jQuery Mobile
  28. 28. Client side ArchitectureBucket list Async communication mechanism with server MV* framework Local storage mechanism Responsive web pages View management Data management UI interactions to enhance the experience
  29. 29. Tool up• BDD / TDD• Grunt• Sublime Text Editor• Development server
  30. 30. Tool up• BDD / TDD• Grunt• Sublime Text Editor• Development server
  31. 31. Jasmine• Jasmine http://pivotal.github.com/jasmine/• Does not depend on any other JS framework Client side Architecture• Does not require a DOM• Given, When, Then syntax• Works on windows 8!
  32. 32. Tool up• BDD / TDD• Grunt• Sublime Text Editor• Development server
  33. 33. Grunt• grunt http://gruntjs.com/• Requires Node – install using npm grunt• Provides the ability for developers to have a pseudo compilation mechanism• MSBuild analogy where by developers can create a script that performs a series of actions
  34. 34. GruntBuild Script• Run tests• JSHint code • http://www.jshint.com/• Uglification / Compression of code • https://github.com/mishoo/UglifyJS• Bundling of code ready for deployment
  35. 35. Tool up• BDD / TDD• Grunt• Sublime Text Editor• Development server
  36. 36. Sublime text editor• Nuget style package management console• Support for backbone snippets• Support for jQuery snippets• Supports grunt build files• Supports jshint configuration
  37. 37. Tool up• BDD / TDD• Grunt• Sublime Text Editor• Development server
  38. 38. Web Matrix• Local Server for running web apps• Awesome for deployment to Azure• Has its own editor
  39. 39. Backbone viewEventsModelsCollections router eventsViewsRouters collection modelhttp://backbonejs.org/ events
  40. 40. Router• Provides methods for routing client-side pages, and connecting them to actions and events• Until recently, hash fragments (#page) were used to provide these permalinks, but with the arrival of the History API, its now possible to use standard URLs (/page)• For browsers which dont yet support the History API, the Router handles graceful fallback and transparent translation to the fragment version of the URL
  41. 41. Routervar Workspace = Backbone.Router.extend({ routes: { "help": "help", // #help "search/:query": "search", // #search/kiwis "search/:query/p:page": "search" // #search/kiwis/p7 }, help: function() {}, search: function(query, page) {}});
  42. 42. Events• Events is a module that can be mixed into any object• Provides the ability to bind and trigger custom named events• Normally used in the view so that it can update when our model changes this.model.on("destroy", this.close, this); this.model.on(“reset”, this.addAll, this); this.model.on(“add”, this.addOne, this);
  43. 43. Models• Models are at the heart of any js app• Models contain interactive data as well as a large part of the logic surrounding it• Models are databound to the html• Models can also be extended to help contain common functionality• By convention the initialise function gets called with the arguments passed into the constructor
  44. 44. Collections• Collections are ordered sets of models• Bind “change” events to be notified when any model in the collection has been modified• Common change events to listen for  Add  Remove
  45. 45. CollectionsFetch()• Call to populate collection with data
  46. 46. CollectionsSync(crud method, model, options callback)• CRUD – Create, Read, Update or Delete• Model – Model to be operated on• Options – callbacks success and error
  47. 47. CollectionsCRUD to REST• Create -> POST /collection• Read -> GET /collection[id]• Update -> PUT /collection/id• Delete -> DELETE /collection/id
  48. 48. Views• More convention than they are code• They dont determine anything about your HTML or CSS for you, and can be used with any JavaScript templating library• Organize your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page• Bind your views render function to the models "change" event and now everywhere that model data is displayed in the UI, it is always immediately up to date
  49. 49. Backbone view router events collection model events
  50. 50. MVVM view View events model collection model events
  51. 51. Underscore• http://underscorejs.org/• 80 odd helper functions• Works seamlessly with jQuery and Backbone• Provides the ability to shape data similar to how we would use linq or lambda in .net• Provides the ability to add script into our html templates
  52. 52. UnderscoreShaping data• each• map• where• sortBy, groupBy
  53. 53. UnderscoreTemplatingWorks in the same way as other templating frameworks<td> <%= typeof(model.get("foo")) !== undefined ? model.get("foo").toPrecision(4) : %></td>
  54. 54. Putting it all together
  55. 55. events dom layout view manager router events web localrequest storage collection model pagination events
  56. 56. Web Request Initialise App Router Collection Layout Fetch data Render Page View Manager Populate Notify UI that Sync On success Collection data changed Render View
  57. 57. Web app• News reader – uses Guardian API• Router / Models / Views• Pagination• Local Storage• View Management
  58. 58. Main layout Section List Section List Item Main.html View View section/list.html section/item.html Section Header View Story List Viewsection/header.html story/list.html Story List Item View story/item.html
  59. 59. <div class="nav-collapse sectionListView"></div><div id="sectionHeaderView" class="hero-unit sectionHeaderView"></div> Section List View<div id="storyListView" class="storyListView"></div> Main layout section/list.html Main.html <ul class="nav"></ul> Section List Item View <a href="<%= model.get("id") %>"> section/item.html <%= typeof(model.get("webTitle")) !== undefined ? model.get("webTitle") : %> </a><span> <%= typeof(model.get("webTitle")) !== undefined ? model.get("webTitle") : %></span> Section Header View section/header.html Story List View story/list.html Story List Item View story/item.html
  60. 60. <div class="nav-collapse sectionListView"></div> <div id="sectionHeaderView" class="hero-unit sectionHeaderView"></div> Section List View <div id="storyView" class="storyView"></div> Story layout section/list.html story.html Section List Item View section/item.html Section Header View Story List Viewsection/header.html story/list.html <p><img width="20%" src="<%= model.get(fields).thumbnail %>" type="" media=""></p> <h1><%= model.get("fields").headline %></h1> <div style="columns:100px 2; -webkit-columns:100px 2; -moz-columns:100px 2;"> <p><%= model.get("fields").body %></> </div>
  61. 61. Winjs• Provides access to winrt interfaces via javascript• Uses the chakra engine same engine used in IE10• Introduces some rather desirable programming concepts such as namespaces, data binding, background tasks and more• Builds on ECMA script 5 such as promises
  62. 62. Winjs and backbone• Use backbone for all our data• Use winjs as our UI Framework• Ability to integrate and weave the backbone types into winjs binding list types• Ability to abstract backbone implementation behind more complex winjs implementations
  63. 63. Putting it all together
  64. 64. eventsdom view events navigation binding list eventsapp localload storage collection model pagination events
  65. 65. App Load Initialise App Navigation Collection Render ProcessFetch data View Fragment Fragment Populate Convert to Sync On success Collection Binding List Render Notify UI that Fragment data changed
  66. 66. Winjs app• Reader port to windows 8• Changes to note Change in User Experience impacts how and what data needs to be displayed Removal views (css, html and js) and replaced with winjs ui controls Replacing jQuery $Ajax with winjs xhr Replacing router with winjs navigation Extending data list source to be used in conjunction with Backbone collection
  67. 67. Looking back• Overview of some useful js frameworks that allow us to create maintainable client side apps in js/html/css• Building on our experiences with xaml and .net, databinding, composite UI and separation of view model controller designs• Ability to reuse underpinning modules in browser and win8
  68. 68. Looking forwards• Improvements in the frameworks and plugins• Improvements in scaffolding for building apps• Better tools to help manage larger client side apps• Better support for winjs binding list• Better support for jQuery

×