Scalable JavaScript Application Architecture            Nicholas C. Zakas | @slicknet
New
ModelView           Controller
Building an application      framework
An application framework is like a playground for your codeProvides structure around otherwise unrelated activities       ...
Isnt that what JavaScript        libraries do?
flickr.com/photos/skistz/398429879/                                                  jQuery                               ...
Application   CoreBase Library
Module Theory Everything is a module
module (n)1 : a standard or unit of measurement2 : the size of some one part taken as a unit of measure by which thepropor...
module (n)1 : a standard or unit of measurement2 : the size of some one part taken as a unit of measure by which thepropor...
How does this apply to web      applications?
web application module (n)1 : an independent unit of functionality that is part of the totalstructure of a web application...
Web application modules consist of   HTML + CSS + JavaScript
Any single module should be ableto live on its own
Loose coupling allows you to make changes to   one module without affecting the others                              flickr...
flickr.com/photos/renfield/3414246938/                    Each module has its own sandbox     An interface with which the ...
Module Module                  ModuleModule     Sandbox        Module          Application             Core          Base ...
Module Module                                    ModuleModule               Sandbox                  Module  Modules have ...
Core.register("module-name", function(sandbox){      return {          init: function(){               //constructor      ...
Which parts know about the web    application being built?
None of them
Each part of the architecture is like a puzzle piece           No single piece needs to know what the picture is      All ...
What is a modules job?
Hello, Im the weather module.Its my job to tell you the weather.
Hello, Im the stocks module.Its my job to tell you about thestock market.
Each modules job is to create a  meaningful user experience
flickr.com/photos/eljay/2392332379/                   The web application is created                as a result of all par...
Module Module             ModuleModule    Sandbox    Module
Module Module                                      ModuleModule                                            Module   Module...
DataModule                         View  Modules manage data and views Though may not have actual objects representing eit...
Data                                                  WidgetModule                         View                     Widget...
Data                                                   MenuModule                         View                      Tabs  ...
DataModule                        View                                                      Menu                        Da...
Modules can’t do whatever they     want to do their job
flickr.com/photos/tedsblog/43433812/         Modules are like little kidsThey need a strict set of rules so they dont get ...
Module RulesHands to yourself– Only call your own methods or those on the sandbox– Dont access DOM elements outside of you...
Modules must stay within their own sandboxes                  No matter how restrictive or uncomfortable it may seemflickr...
Module Module                  ModuleModule     Sandbox        Module          Application             Core          Base ...
SandboxThe sandbox ensures a consistent interface     Modules can rely on the methods to always be there
Module Module                  ModuleModule     Sandbox        Module          Application             Core          Base ...
Module Module                                      ModuleModule               Sandbox                   Module  Modules on...
The sandbox also acts like a security guardKnows what the modules are allowed to access and do on the framework           ...
Core.register("module-name", function(sandbox){      return {          init: function(){                //not sure if Im a...
Sandbox JobsConsistency– Interface must be dependableSecurity– Determine which parts of the framework a module can  access...
Take the time to design the correct sandbox interface       It cant change later
Module Module                  ModuleModule     Sandbox        Module          Application             Core          Base ...
Application                CoreThe application core manages modules               Thats it
Application          Coreaka Application Controller
The application core tells a module whenit should initialize and when it should shutdown                                 f...
Core = function(){  var moduleData = {}; return {     register: function(moduleId, creator){        moduleData[moduleId] =...
Core = function(){ return {   //more code here...   startAll: function(){      for (var moduleId in moduleData){        if...
//register modulesCore.register("module1",   function(sandbox){   /*...*/   });Core.register("module2",   function(sandbox...
The application core managescommunication between modules             flickr.com/photos/markhillary/353738538/
TimelineFilter = {    changeFilter: function(filter){        Timeline.applyFilter(filter);    }};                         ...
Core.register("timeline-filter", function(sandbox){      return {          changeFilter: function(filter){               s...
Core.register("timeline", function(sandbox){      return {          init: function(){               sandbox.listen([      ...
When modules are loosely coupled,    removing a module doesnt break the othersNo direct access to another module = no brea...
The application core handles errorsUses available information to determine best course of action                          ...
Core = function(){ var moduleData = {}, debug = false; function createInstance(moduleId){   var instance =     moduleData[...
Learn morehttp://www.slideshare.net/nzakas/enterprise-javascript-error-handling-presentation
Application Core JobsManage module lifecycle– Tell modules when to start and stop doing their jobEnable inter-module commu...
Why not?
Web applications changeOften in ways that you couldnt possibly anticipate
Plan for extension
flickr.com/photos/pointnshoot/1443575327/     Anything built for extension can never be                      obsoleteExten...
Module  Module                   ModuleModule       Sandbox        Module            ApplicationExtension                 ...
What Extensions?•   Error handling•   Ajax communication•   New module capabilities•   General utilities•   Anything!
Ajax communication comes in different forms     Tends to be tied to something available on the server
Request format                 Entrypoint                    Response formatThree parts must be in sync for Ajax to work  ...
Module  Module                   ModuleModule       Sandbox        Module            ApplicationExtension                 ...
GET ?name=value&name=value          /ajax     Request format               Entrypoint     Response format<response>   <sta...
Entrypointvar xhr = new XMLHttpRequest();xhr.open("get", "/ajax?name=value", true);                                       ...
Library  reference               Entrypointvar id = Y.io("/ajax?name=value", {  method: "get",                           R...
var id = sandbox.request({ name: "value" }, {  success: function(response){     handleSuccess(response.data);  },  failure...
Request format                 Entrypoint                  Response formatAjax extension encapsulates all details Any of t...
GET ?name=value&name=value    /request        Request format           Entrypoint       Response format{    status: "ok|er...
Module  Module                   ModuleModule       Sandbox        Module            ApplicationExtension                 ...
Ajax Extension JobsHide Ajax communication details– Modules dont need to know any of itProvide common request interface– M...
Module  Module                   ModuleModule       Sandbox        Module            ApplicationExtension                 ...
The base library provides basic functionality                  Ironic, huh?                Base Library
flickr.com/photos/kartik_m/2724121901/ Most applications are too tightly coupled            to the base libraryDevelopers ...
High-Performance JavaScript, OSCON 2007             Joseph Smarr, Plaxo, Inc.
Learn morehttp://josephsmarr.com/2007/07/25/high-performance-javascript-oscon-2007/
Ideally, only the application corehas any idea what base library is            being used
Module Module                 ModuleModule     Sandbox       Module          Application             Core             Dojo
Module Module                 ModuleModule     Sandbox       Module          Application             Core             YUI
Base Library JobsBrowser normalization– Abstract away differences in browsers with common  interfaceGeneral-purpose utilit...
Module  Module                   ModuleModule       Sandbox        Module            ApplicationExtension                 ...
Architecture Knowledge
Module  Module                   ModuleModule       Sandbox        Module            ApplicationExtension                 ...
Only the base library knows which browser               is being used    No other part of the architecture should need to ...
Only the application core knows which      base library is being used  No other part of the architecture should need to kn...
Sandbox                       Application                          CoreOnly the sandbox knows which application core      ...
Module      Module                                      Module   Module                  Sandbox                   Module ...
Module  Module                     Module Module        Sandbox         Module              ApplicationExtension          ...
Advantages
flickr.com/photos/kgoldendragon613/278240446/Multiple different applications can be created          with the same framewo...
Each part can be tested separatelyYou just need to verify that each is doing its unique job                               ...
A scalable JavaScript architectureallows you to replace any blockwithout fear of toppling the tower                flickr....
Implementations
https://github.com/legalbox/lb_js_scalableApp
http://scaleapp.org
http://tcorral.github.com/Hydra.js/
http://alanlindsay.me/kerneljs/
http://terrifically.org/
http://addyosmani.github.com/aura/
The End
Etcetera•My blog:        nczonline.net•Twitter:        @slicknet•These Slides:   slideshare.net/nzakas
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
Upcoming SlideShare
Loading in...5
×

Scalable JavaScript Application Architecture 2012

44,644

Published on

An update to the Scalable JavaScript presentation of 2009. Describes how to piece together a JavaScript application framework designed for maintainability.

Published in: Technology
10 Comments
135 Likes
Statistics
Notes
No Downloads
Views
Total Views
44,644
On Slideshare
0
From Embeds
0
Number of Embeds
21
Actions
Shares
0
Downloads
663
Comments
10
Likes
135
Embeds 0
No embeds

No notes for slide
  • Over the past couple of years, we&apos;ve seen JavaScript development earn recognition as a true discipline. The idea that you should architect your code, use patterns and good programming practices has really elevated the role of the front end engineer. In my opinion, part of this elevation has been the adoption of what has traditionally been considered back end methodologies. We now focus on performance and algorithms, there&apos;s unit testing for JavaScript, and so much more. One of the areas that I&apos;ve seen a much slower than adoption that I&apos;d like is in the area of error handling.How many people have an error handling strategy for their backend? How many have dashboards that display problems with uptime and performance? How many have anything similar for the front end?Typically, the front end has been this black hole of information. You may get a few customer reports here and there, but you have no information about what&apos;s going on, how often it&apos;s occurring, or how many people have been affected.
  • So what have we talked about? Maintainable JavaScript is made up of four components.First is Code Conventions that describe the format of the code you’re writing.Second is Loose Coupling – keeping HTML, JavaScript, and CSS on separate layers and keeping application logic out of event handlers.Third is Programming Practices that ensure your code is readable and easily debugged.Fourth is creating a Build Process
  • Scalable JavaScript Application Architecture 2012

    1. 1. Scalable JavaScript Application Architecture Nicholas C. Zakas | @slicknet
    2. 2. New
    3. 3. ModelView Controller
    4. 4. Building an application framework
    5. 5. An application framework is like a playground for your codeProvides structure around otherwise unrelated activities flickr.com/photos/osterwalder/152697503/
    6. 6. Isnt that what JavaScript libraries do?
    7. 7. flickr.com/photos/skistz/398429879/ jQuery YUI DojoA JavaScript library is like a toolbox You can build any number of things using the tools
    8. 8. Application CoreBase Library
    9. 9. Module Theory Everything is a module
    10. 10. module (n)1 : a standard or unit of measurement2 : the size of some one part taken as a unit of measure by which theproportions of an architectural composition are regulated3 a : any in a series of standardized units for use together: as (1) : aunit of furniture or architecture (2) : an educational unit which coversa single subject or topic b : a usually packaged functional assemblyof electronic components for use with other such assemblies4 : an independently operable unit that is a part of the total structureof a space vehicle5 a : a subset of an additive group that is also a group under additionb : a mathematical set that is a commutative group under additionand that is closed under multiplication which is distributive from theleft or right or both by elements of a ring and for which a(bx) = (ab)xor (xb)a = x(ba) or both where a and b are elements of the ring and xbelongs to the set Source: Merriam-Webster Dictionary
    11. 11. module (n)1 : a standard or unit of measurement2 : the size of some one part taken as a unit of measure by which theproportions of an architectural composition are regulated3 a : any in a series of standardized units for use together: as (1) : aunit of furniture or architecture (2) : an educational unit which coversa single subject or topic b : a usually packaged functional assemblyof electronic components for use with other such assemblies4 : an independently operable unit that is a part of the total structureof a space vehicle5 a : a subset of an additive group that is also a group under additionb : a mathematical set that is a commutative group under additionand that is closed under multiplication which is distributive from theleft or right or both by elements of a ring and for which a(bx) = (ab)xor (xb)a = x(ba) or both where a and b are elements of the ring and xbelongs to the set Source: Merriam-Webster Dictionary
    12. 12. How does this apply to web applications?
    13. 13. web application module (n)1 : an independent unit of functionality that is part of the totalstructure of a web application Source: Me
    14. 14. Web application modules consist of HTML + CSS + JavaScript
    15. 15. Any single module should be ableto live on its own
    16. 16. Loose coupling allows you to make changes to one module without affecting the others flickr.com/photos/quinnanya/3575417671/
    17. 17. flickr.com/photos/renfield/3414246938/ Each module has its own sandbox An interface with which the module can interact to ensure loose coupling
    18. 18. Module Module ModuleModule Sandbox Module Application Core Base Library
    19. 19. Module Module ModuleModule Sandbox Module Modules have limited knowledge Each module knows about their sandbox and thats it
    20. 20. Core.register("module-name", function(sandbox){ return { init: function(){ //constructor }, destroy: function(){ //destructor } };});
    21. 21. Which parts know about the web application being built?
    22. 22. None of them
    23. 23. Each part of the architecture is like a puzzle piece No single piece needs to know what the picture is All that matters is that the piece does its own job correctly flickr.com/photos/generated/501445202/
    24. 24. What is a modules job?
    25. 25. Hello, Im the weather module.Its my job to tell you the weather.
    26. 26. Hello, Im the stocks module.Its my job to tell you about thestock market.
    27. 27. Each modules job is to create a meaningful user experience
    28. 28. flickr.com/photos/eljay/2392332379/ The web application is created as a result of all parts doing their job
    29. 29. Module Module ModuleModule Sandbox Module
    30. 30. Module Module ModuleModule Module Modules contain business logic related to the module’s particular job
    31. 31. DataModule View Modules manage data and views Though may not have actual objects representing either
    32. 32. Data WidgetModule View Widget Widget Widgets are reusable pieces of UI They contain no business logic or data
    33. 33. Data MenuModule View Tabs Carousel Widgets are reusable pieces of UI They contain no business logic or data
    34. 34. DataModule View Menu DataModule Tabs View Carousel Widgets are part of a view toolkit All modules can use widgets within their views
    35. 35. Modules can’t do whatever they want to do their job
    36. 36. flickr.com/photos/tedsblog/43433812/ Modules are like little kidsThey need a strict set of rules so they dont get into trouble
    37. 37. Module RulesHands to yourself– Only call your own methods or those on the sandbox– Dont access DOM elements outside of your box– Dont access non-native global objectsAsk, dont take– Anything else you need, ask the sandboxDont leave your toys around– Dont create global objectsDont talk to strangers– Dont directly reference other modules
    38. 38. Modules must stay within their own sandboxes No matter how restrictive or uncomfortable it may seemflickr.com/photos/madaise/3406217980/
    39. 39. Module Module ModuleModule Sandbox Module Application Core Base Library
    40. 40. SandboxThe sandbox ensures a consistent interface Modules can rely on the methods to always be there
    41. 41. Module Module ModuleModule Sandbox Module Application Core Base Library
    42. 42. Module Module ModuleModule Sandbox Module Modules only know the sandbox The rest of the architecture doesnt exist to them
    43. 43. The sandbox also acts like a security guardKnows what the modules are allowed to access and do on the framework flickr.com/photos/heraklit/169566548/
    44. 44. Core.register("module-name", function(sandbox){ return { init: function(){ //not sure if Im allowed... if (sandbox.iCanHazCheezburger()){ alert("thx u"); } }, destroy: function(){ //destructor } };});
    45. 45. Sandbox JobsConsistency– Interface must be dependableSecurity– Determine which parts of the framework a module can accessCommunication– Translate module requests into core actions
    46. 46. Take the time to design the correct sandbox interface It cant change later
    47. 47. Module Module ModuleModule Sandbox Module Application Core Base Library
    48. 48. Application CoreThe application core manages modules Thats it
    49. 49. Application Coreaka Application Controller
    50. 50. The application core tells a module whenit should initialize and when it should shutdown flickr.com/photos/bootbearwdc/20817093/ flickr.com/photos/bootbearwdc/20810695/
    51. 51. Core = function(){ var moduleData = {}; return { register: function(moduleId, creator){ moduleData[moduleId] = { creator: creator, instance: null }; }, start: function(moduleId){ moduleData[moduleId].instance = moduleData[moduleId].creator(new Sandbox(this)); moduleData[moduleId].instance.init(); }, stop: function(moduleId){ var data = moduleData[moduleId]; if (data.instance){ data.instance.destroy(); data.instance = null; } } }}();
    52. 52. Core = function(){ return { //more code here... startAll: function(){ for (var moduleId in moduleData){ if (moduleData.hasOwnProperty(moduleId)){ this.start(moduleId); } } }, stopAll: function(){ for (var moduleId in moduleData){ if (moduleData.hasOwnProperty(moduleId)){ this.stop(moduleId); } } }, //more code here... };}();
    53. 53. //register modulesCore.register("module1", function(sandbox){ /*...*/ });Core.register("module2", function(sandbox){ /*...*/ });Core.register("module3", function(sandbox){ /*...*/ });Core.register("module4", function(sandbox){ /*...*/ });//start the application by starting all modulesCore.startAll();
    54. 54. The application core managescommunication between modules flickr.com/photos/markhillary/353738538/
    55. 55. TimelineFilter = { changeFilter: function(filter){ Timeline.applyFilter(filter); }}; Tight CouplingStatusPoster = { postStatus: function(status){ Timeline.post(status); }}; Tight CouplingTimeline = { applyFilter: function(filter){ //implementation }, post: function(status){ //implementation }};
    56. 56. Core.register("timeline-filter", function(sandbox){ return { changeFilter: function(filter){ sandbox.notify({ type: "timeline-filter-change", data: filter }); Loose } }; Coupling});Core.register("status-poster", function(sandbox){ return { postStatus: function(statusText){ sandbox.notify({ type: "new-status", data: statusText }); Loose } }; Coupling});
    57. 57. Core.register("timeline", function(sandbox){ return { init: function(){ sandbox.listen([ "timeline-filter-change", "post-status" ], this.handleNotification, this); Loose }, Coupling handleNotification: function(note){ switch(note.type){ case "timeline-filter-change": this.applyFilter(note.data); return; case "post-status": this.post(note.data); return; } } };});
    58. 58. When modules are loosely coupled, removing a module doesnt break the othersNo direct access to another module = no breaking should the module disappear
    59. 59. The application core handles errorsUses available information to determine best course of action flickr.com/photos/brandonschauer/3168761995/
    60. 60. Core = function(){ var moduleData = {}, debug = false; function createInstance(moduleId){ var instance = moduleData[moduleId].creator(new Sandbox(this)), name, method; if (!debug){ for (name in instance){ method = instance[name]; if (typeof method == "function"){ instance[name] = function(name, method){ return function(){ try { return method.apply(this, arguments);} catch(ex) {log(1, name + "(): " + ex.message);} }; }(name, method); } } } return instance; } //more code here}();
    61. 61. Learn morehttp://www.slideshare.net/nzakas/enterprise-javascript-error-handling-presentation
    62. 62. Application Core JobsManage module lifecycle– Tell modules when to start and stop doing their jobEnable inter-module communication– Allow loose coupling between modules that are related to one anotherGeneral error handling– Detect, trap, and report errors in the systemBe extensible– The first three jobs are not enough!
    63. 63. Why not?
    64. 64. Web applications changeOften in ways that you couldnt possibly anticipate
    65. 65. Plan for extension
    66. 66. flickr.com/photos/pointnshoot/1443575327/ Anything built for extension can never be obsoleteExtensions augment the capabilities of the core to keep it relevant and useful
    67. 67. Module Module ModuleModule Sandbox Module ApplicationExtension Extension Core Base Library
    68. 68. What Extensions?• Error handling• Ajax communication• New module capabilities• General utilities• Anything!
    69. 69. Ajax communication comes in different forms Tends to be tied to something available on the server
    70. 70. Request format Entrypoint Response formatThree parts must be in sync for Ajax to work Modules shouldnt know anything about any of this
    71. 71. Module Module ModuleModule Sandbox Module ApplicationExtension Ajax/XML Core Base Library
    72. 72. GET ?name=value&name=value /ajax Request format Entrypoint Response format<response> <status>ok|error</status> <data> <results> <result name="..." /> <result name="..." /> </results> </data></response>
    73. 73. Entrypointvar xhr = new XMLHttpRequest();xhr.open("get", "/ajax?name=value", true); Requestxhr.onreadystatechange = function(){ format if (xhr.readyState == 4){ if (xhr.status == 200 || xhr.status == 304){ var statusNode = xhr.responseXML.getElementsByTagName("status")[0], dataNode = xhr.responseXML.getElementsByTagName("data")[0]; if (statusNode.firstChild.nodeValue == "ok"){ handleSuccess(processData(dataNode)); } else { Response handleFailure(); format } } else { handleFailure(); } }};xhr.send(null); Basic implementation Lowest-level Ajax with XMLHttpRequest
    74. 74. Library reference Entrypointvar id = Y.io("/ajax?name=value", { method: "get", Request on: { format success: function(req){ var statusNode = req.responseXML.getElementsByTagName("status")[0], dataNode = req.responseXML.getElementsByTagName("data")[0]; if (statusNode.firstChild.nodeValue == "ok"){ handleSuccess(processData(dataNode)); } else { Response handleFailure(); format } }, failure: function(req){ handleFailure(); } }}); Implementation using a library Hides some of the ugliness but still tightly coupled to Ajax implementation
    75. 75. var id = sandbox.request({ name: "value" }, { success: function(response){ handleSuccess(response.data); }, failure: function(response){ handleFailure(); }}); Implementation using sandbox Passes through to core - hides all Ajax communication details
    76. 76. Request format Entrypoint Response formatAjax extension encapsulates all details Any of these three can change without affecting modules
    77. 77. GET ?name=value&name=value /request Request format Entrypoint Response format{ status: "ok|error", data: { results: [ "...", "..." ] }}
    78. 78. Module Module ModuleModule Sandbox Module ApplicationExtension Ajax/JSON Core Base Library
    79. 79. Ajax Extension JobsHide Ajax communication details– Modules dont need to know any of itProvide common request interface– Modules use this interface to specify data to send to the serverProvide common response interface– Modules use this interface to retrieve data from the responseManage server failures– Modules only care if they got what they wanted or not, dont care why
    80. 80. Module Module ModuleModule Sandbox Module ApplicationExtension Extension Core Base Library
    81. 81. The base library provides basic functionality Ironic, huh? Base Library
    82. 82. flickr.com/photos/kartik_m/2724121901/ Most applications are too tightly coupled to the base libraryDevelopers get upset when they cant touch the base library directly
    83. 83. High-Performance JavaScript, OSCON 2007 Joseph Smarr, Plaxo, Inc.
    84. 84. Learn morehttp://josephsmarr.com/2007/07/25/high-performance-javascript-oscon-2007/
    85. 85. Ideally, only the application corehas any idea what base library is being used
    86. 86. Module Module ModuleModule Sandbox Module Application Core Dojo
    87. 87. Module Module ModuleModule Sandbox Module Application Core YUI
    88. 88. Base Library JobsBrowser normalization– Abstract away differences in browsers with common interfaceGeneral-purpose utilities– Parsers/serializers for XML, JSON, etc.– Object manipulation– DOM manipulation– Ajax communicationProvide low-level extensibility
    89. 89. Module Module ModuleModule Sandbox Module ApplicationExtension Extension CoreExtension Base Library Extension
    90. 90. Architecture Knowledge
    91. 91. Module Module ModuleModule Sandbox Module ApplicationExtension Extension CoreExtension Base Library Extension
    92. 92. Only the base library knows which browser is being used No other part of the architecture should need to know Base Library
    93. 93. Only the application core knows which base library is being used No other part of the architecture should need to know Application Core Base Library
    94. 94. Sandbox Application CoreOnly the sandbox knows which application core is being used No other part of the architecture should need to know
    95. 95. Module Module Module Module Sandbox Module The modules know nothing except that the sandbox existsThey have no knowledge of one another or the rest of the architecture
    96. 96. Module Module Module Module Sandbox Module ApplicationExtension Extension CoreExtension Base Library ExtensionNo part knows about the web application
    97. 97. Advantages
    98. 98. flickr.com/photos/kgoldendragon613/278240446/Multiple different applications can be created with the same framework Minimize ramp-up time by reusing existing components
    99. 99. Each part can be tested separatelyYou just need to verify that each is doing its unique job flickr.com/photos/misocrazy/151021636/
    100. 100. A scalable JavaScript architectureallows you to replace any blockwithout fear of toppling the tower flickr.com/photos/aku-ma/2424194422/
    101. 101. Implementations
    102. 102. https://github.com/legalbox/lb_js_scalableApp
    103. 103. http://scaleapp.org
    104. 104. http://tcorral.github.com/Hydra.js/
    105. 105. http://alanlindsay.me/kerneljs/
    106. 106. http://terrifically.org/
    107. 107. http://addyosmani.github.com/aura/
    108. 108. The End
    109. 109. Etcetera•My blog: nczonline.net•Twitter: @slicknet•These Slides: slideshare.net/nzakas
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×