SlideShare une entreprise Scribd logo
1  sur  108
Télécharger pour lire hors ligne
Scalable JavaScript Application Architecture            Nicholas C. Zakas | @slicknet
Whos this guy? Ex-tech lead            Co-Creator                Contributor,   Yahoo!                csslint.net            Creator of YUI TestAuthor          Lead Author       Contributor           Lead Author
@slicknet
Single-page apps
ModelView           Controller
Single-page apps        &Multi-page apps
Building an application      framework
An application framework is like a playground for your codeProvides structure around otherwise unrelated activities                                          flickr.com/photos/osterwalder/152697503/
Isnt that what JavaScript        libraries do?
flickr.com/photos/skistz/398429879/A JavaScript library is like a toolbox You can build any number of things using the tools
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 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
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
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                                                                     Source: Me
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.com/photos/quinnanya/3575417671/
flickr.com/photos/renfield/3414246938/                    Each module has its own sandbox     An interface with which the module can interact to ensure loose coupling
Module Module                  ModuleModule     Sandbox        Module          Application             Core          Base Library
Application ArchitectureModulesSandboxApplication CoreBase Library
Module Module                                    ModuleModule               Sandbox                  Module  Modules have limited knowledge  Each module knows about their sandbox and thats it
Core.register("module-name", function(sandbox){      return {          init: function(){              //constructor          },           destroy: function(){               //destructor           }      };});
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 that matters is that the piece does its own job correctly                                                    flickr.com/photos/generated/501445202/
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 parts doing their job
This doesnt mean modules can 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 into trouble
Module Rules• Hands 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 objects• Ask, dont take   Anything else you need, ask the sandbox• Dont leave your toys around   Dont create global objects• Dont talk to strangers   Dont directly reference other modules
Modules must stay within their own sandboxes                  No matter how restrictive or uncomfortable it may seemflickr.com/photos/madaise/3406217980/
Application ArchitectureModulesSandboxApplication CoreBase Library
Module Module                  ModuleModule     Sandbox        Module          Application             Core          Base Library
SandboxThe sandbox ensures a consistent interface     Modules can rely on the methods to always be there
Module Module                  ModuleModule     Sandbox        Module          Application             Core          Base Library
Module Module                                      ModuleModule               Sandbox                   Module  Modules only know the sandbox   The rest of the architecture doesnt exist to them
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/
Core.register("module-name", function(sandbox){      return {          init: function(){                //not sure if Im allowed...                if (sandbox.iCanHazCheezburger()){                    alert("thx u");                }           },           destroy: function(){               //destructor           }      };});
Sandbox Jobs• Consistency• Security• Communication
Take the time to design the correct sandbox interface       It cant change later
Application ArchitectureModulesSandboxApplication CoreBase Library
Module Module                  ModuleModule     Sandbox        Module          Application             Core          Base Library
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                                 flickr.com/photos/bootbearwdc/20817093/                                 flickr.com/photos/bootbearwdc/20810695/
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;         }       }  }}();
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...  };}();
//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();
The application core managescommunication between modules             flickr.com/photos/markhillary/353738538/
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    }};
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});
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;               }           }      };});
When modules are loosely coupled,    removing a module doesnt break the othersNo direct access to another module = no breaking should the module disappear
The application core handles errorsUses available information to determine best course of action                                         flickr.com/photos/brandonschauer/3168761995/
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}();
Learn morehttp://www.slideshare.net/nzakas/enterprise-javascript-error-handling-presentation
Application Core Jobs•   Manage module lifecycle•   Enable inter-module communication•   General error handling•   Be extensible
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                      obsoleteExtensions augment the capabilities of the core to keep it relevant and useful
Module  Module                   ModuleModule       Sandbox        Module            ApplicationExtension                   Extension               Core            Base Library
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      Modules shouldnt know anything about any of this
Module  Module                   ModuleModule       Sandbox        Module            ApplicationExtension                   Ajax/XML               Core            Base Library
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>
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
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
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
Request format                 Entrypoint                  Response formatAjax extension encapsulates all details Any of these three can change without affecting modules
GET ?name=value&name=value    /request        Request format           Entrypoint       Response format{    status: "ok|error",    data: {      results: [        "...",        "..."      ]    }}
Module  Module                   ModuleModule       Sandbox        Module            ApplicationExtension                   Ajax/JSON               Core            Base Library
Ajax Extension Jobs•   Hide Ajax communication details•   Provide common request interface•   Provide common response interface•   Manage server failures
Application ArchitectureModulesSandboxApplication CoreBase Library
Module  Module                   ModuleModule       Sandbox        Module            ApplicationExtension                   Extension               Core            Base Library
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 get upset when they cant touch the base library directly
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 Jobs• Browser normalization• General-purpose utilities     Parsers/serializers for XML, JSON, etc.     Object manipulation     DOM manipulation     Ajax communication• Provide low-level extensibility
Module  Module                   ModuleModule       Sandbox        Module            ApplicationExtension                   Extension               CoreExtension   Base Library    Extension
Architecture Knowledge
Module  Module                   ModuleModule       Sandbox        Module            ApplicationExtension                   Extension               CoreExtension   Base Library    Extension
Only the base library knows which browser               is being used    No other part of the architecture should need to know                    Base Library
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
Sandbox                       Application                          CoreOnly the sandbox knows which application core                is being used      No other part of the architecture should need to know
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
Module  Module                     ModuleModule         Sandbox        Module              ApplicationExtension                     Extension                 CoreExtension    Base Library     ExtensionNo part knows about the web application
Advantages
flickr.com/photos/kgoldendragon613/278240446/Multiple different applications can be created          with the same framework     Minimize ramp-up time by reusing existing components
Each part can be tested separatelyYou just need to verify that each is doing its unique job                                             flickr.com/photos/misocrazy/151021636/
A scalable JavaScript architectureallows you to replace any blockwithout fear of toppling the tower                flickr.com/photos/aku-ma/2424194422/
The End
Etcetera•My blog:      www.nczonline.net•Twitter:      @slicknet•These Slides: slideshare.net/nzakas

Contenu connexe

Tendances

Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
Javascript under the hood 1
Javascript under the hood 1Javascript under the hood 1
Javascript under the hood 1Thang Tran Duc
 
Easy tests with Selenide and Easyb
Easy tests with Selenide and EasybEasy tests with Selenide and Easyb
Easy tests with Selenide and EasybIakiv Kramarenko
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 
Angular Routing Guard
Angular Routing GuardAngular Routing Guard
Angular Routing GuardKnoldus Inc.
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency InjectionNir Kaufman
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions WebStackAcademy
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Knoldus Inc.
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS DirectivesEyal Vardi
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsasync_io
 

Tendances (20)

Angular 8
Angular 8 Angular 8
Angular 8
 
Javascript under the hood 1
Javascript under the hood 1Javascript under the hood 1
Javascript under the hood 1
 
Easy tests with Selenide and Easyb
Easy tests with Selenide and EasybEasy tests with Selenide and Easyb
Easy tests with Selenide and Easyb
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Angular Routing Guard
Angular Routing GuardAngular Routing Guard
Angular Routing Guard
 
Web api
Web apiWeb api
Web api
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Angular introduction students
Angular introduction studentsAngular introduction students
Angular introduction students
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
jQuery
jQueryjQuery
jQuery
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
 
Angular
AngularAngular
Angular
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 

Similaire à Build Scalable JavaScript Apps with Modular Architecture

From java to rails
From java to railsFrom java to rails
From java to railsjokry
 
AMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosAMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosDan D'Urso
 
Intro to Table-Grouping™ technology
Intro to Table-Grouping™ technologyIntro to Table-Grouping™ technology
Intro to Table-Grouping™ technologyDavid McFarlane
 
Webinar: Top 5 Mistakes Your Don't Want to Make When Moving to the Cloud
Webinar: Top 5 Mistakes Your Don't Want to Make When Moving to the CloudWebinar: Top 5 Mistakes Your Don't Want to Make When Moving to the Cloud
Webinar: Top 5 Mistakes Your Don't Want to Make When Moving to the CloudInternap
 
Azri solutions leaner techniques for faster portals get drupalled
Azri solutions leaner techniques for faster portals   get drupalledAzri solutions leaner techniques for faster portals   get drupalled
Azri solutions leaner techniques for faster portals get drupalledOpenSourceIndia
 
Azri solutions leaner techniques for faster portals get drupalled
Azri solutions leaner techniques for faster portals   get drupalledAzri solutions leaner techniques for faster portals   get drupalled
Azri solutions leaner techniques for faster portals get drupalledsuniltomar04
 
Ashish pandey huawei osi_days2011_cgroups_understanding_better
Ashish pandey huawei osi_days2011_cgroups_understanding_betterAshish pandey huawei osi_days2011_cgroups_understanding_better
Ashish pandey huawei osi_days2011_cgroups_understanding_bettersuniltomar04
 
Ashish pandey huawei osi_days2011_cgroups_understanding_better
Ashish pandey huawei osi_days2011_cgroups_understanding_betterAshish pandey huawei osi_days2011_cgroups_understanding_better
Ashish pandey huawei osi_days2011_cgroups_understanding_betterOpenSourceIndia
 
Flash tutorials loading external images
Flash tutorials  loading external imagesFlash tutorials  loading external images
Flash tutorials loading external imagesSMK Negeri 6 Malang
 
Hacker tooltalk: Social Engineering Toolkit (SET)
Hacker tooltalk: Social Engineering Toolkit (SET)Hacker tooltalk: Social Engineering Toolkit (SET)
Hacker tooltalk: Social Engineering Toolkit (SET)Chris Hammond-Thrasher
 
Mas overview dirks at cni dec11b
Mas overview dirks at cni   dec11bMas overview dirks at cni   dec11b
Mas overview dirks at cni dec11bLee Dirks
 
Mobile Cloud Architectures
Mobile Cloud ArchitecturesMobile Cloud Architectures
Mobile Cloud ArchitecturesDavid Coallier
 
Dhs sequence of_learning
Dhs sequence of_learningDhs sequence of_learning
Dhs sequence of_learningJaneyMay
 
Dhs sequence of_learning
Dhs sequence of_learningDhs sequence of_learning
Dhs sequence of_learningJaneyMay
 
Using Database Constraints Wisely
Using Database Constraints WiselyUsing Database Constraints Wisely
Using Database Constraints Wiselybarunio
 
Vineet Choudhry Portfolio
Vineet Choudhry PortfolioVineet Choudhry Portfolio
Vineet Choudhry PortfolioRakesh Ranjan
 
Tijdschriften publiceren met onderzoeksdata: Enhanced Journals Made Easy
Tijdschriften publiceren met onderzoeksdata: Enhanced Journals Made EasyTijdschriften publiceren met onderzoeksdata: Enhanced Journals Made Easy
Tijdschriften publiceren met onderzoeksdata: Enhanced Journals Made EasyDriek Heesakkers
 
Sriram simplify os_sdevelopment
Sriram simplify os_sdevelopmentSriram simplify os_sdevelopment
Sriram simplify os_sdevelopmentsuniltomar04
 

Similaire à Build Scalable JavaScript Apps with Modular Architecture (20)

From java to rails
From java to railsFrom java to rails
From java to rails
 
AMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosAMP110 Microsoft Access Macros
AMP110 Microsoft Access Macros
 
Intro to Table-Grouping™ technology
Intro to Table-Grouping™ technologyIntro to Table-Grouping™ technology
Intro to Table-Grouping™ technology
 
Webinar: Top 5 Mistakes Your Don't Want to Make When Moving to the Cloud
Webinar: Top 5 Mistakes Your Don't Want to Make When Moving to the CloudWebinar: Top 5 Mistakes Your Don't Want to Make When Moving to the Cloud
Webinar: Top 5 Mistakes Your Don't Want to Make When Moving to the Cloud
 
Azri solutions leaner techniques for faster portals get drupalled
Azri solutions leaner techniques for faster portals   get drupalledAzri solutions leaner techniques for faster portals   get drupalled
Azri solutions leaner techniques for faster portals get drupalled
 
Azri solutions leaner techniques for faster portals get drupalled
Azri solutions leaner techniques for faster portals   get drupalledAzri solutions leaner techniques for faster portals   get drupalled
Azri solutions leaner techniques for faster portals get drupalled
 
Ashish pandey huawei osi_days2011_cgroups_understanding_better
Ashish pandey huawei osi_days2011_cgroups_understanding_betterAshish pandey huawei osi_days2011_cgroups_understanding_better
Ashish pandey huawei osi_days2011_cgroups_understanding_better
 
Ashish pandey huawei osi_days2011_cgroups_understanding_better
Ashish pandey huawei osi_days2011_cgroups_understanding_betterAshish pandey huawei osi_days2011_cgroups_understanding_better
Ashish pandey huawei osi_days2011_cgroups_understanding_better
 
Flash tutorials loading external images
Flash tutorials  loading external imagesFlash tutorials  loading external images
Flash tutorials loading external images
 
Hacker tooltalk: Social Engineering Toolkit (SET)
Hacker tooltalk: Social Engineering Toolkit (SET)Hacker tooltalk: Social Engineering Toolkit (SET)
Hacker tooltalk: Social Engineering Toolkit (SET)
 
Mas overview dirks at cni dec11b
Mas overview dirks at cni   dec11bMas overview dirks at cni   dec11b
Mas overview dirks at cni dec11b
 
Mobile Cloud Architectures
Mobile Cloud ArchitecturesMobile Cloud Architectures
Mobile Cloud Architectures
 
Dhs sequence of_learning
Dhs sequence of_learningDhs sequence of_learning
Dhs sequence of_learning
 
Dhs sequence of_learning
Dhs sequence of_learningDhs sequence of_learning
Dhs sequence of_learning
 
Getting Started with DevOps
Getting Started with DevOpsGetting Started with DevOps
Getting Started with DevOps
 
Using Database Constraints Wisely
Using Database Constraints WiselyUsing Database Constraints Wisely
Using Database Constraints Wisely
 
Vineet Choudhry Portfolio
Vineet Choudhry PortfolioVineet Choudhry Portfolio
Vineet Choudhry Portfolio
 
Alt Dvb
Alt DvbAlt Dvb
Alt Dvb
 
Tijdschriften publiceren met onderzoeksdata: Enhanced Journals Made Easy
Tijdschriften publiceren met onderzoeksdata: Enhanced Journals Made EasyTijdschriften publiceren met onderzoeksdata: Enhanced Journals Made Easy
Tijdschriften publiceren met onderzoeksdata: Enhanced Journals Made Easy
 
Sriram simplify os_sdevelopment
Sriram simplify os_sdevelopmentSriram simplify os_sdevelopment
Sriram simplify os_sdevelopment
 

Plus de Nicholas Zakas

Browser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceNicholas Zakas
 
Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!Nicholas Zakas
 
JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)Nicholas Zakas
 
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and PerformanceJavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and PerformanceNicholas Zakas
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012Nicholas Zakas
 
High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)Nicholas Zakas
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011Nicholas Zakas
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011Nicholas Zakas
 
Mobile Web Speed Bumps
Mobile Web Speed BumpsMobile Web Speed Bumps
Mobile Web Speed BumpsNicholas Zakas
 
High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)Nicholas Zakas
 
Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Nicholas Zakas
 
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Nicholas Zakas
 
YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)Nicholas Zakas
 
High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)Nicholas Zakas
 
High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010Nicholas Zakas
 
Nicholas' Performance Talk at Google
Nicholas' Performance Talk at GoogleNicholas' Performance Talk at Google
Nicholas' Performance Talk at GoogleNicholas Zakas
 
High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010Nicholas Zakas
 
Performance on the Yahoo! Homepage
Performance on the Yahoo! HomepagePerformance on the Yahoo! Homepage
Performance on the Yahoo! HomepageNicholas Zakas
 
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010Nicholas Zakas
 

Plus de Nicholas Zakas (20)

Browser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom Menace
 
Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!
 
The Pointerless Web
The Pointerless WebThe Pointerless Web
The Pointerless Web
 
JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)
 
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and PerformanceJavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
 
High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011
 
Mobile Web Speed Bumps
Mobile Web Speed BumpsMobile Web Speed Bumps
Mobile Web Speed Bumps
 
High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)
 
Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)
 
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
 
YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)
 
High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)
 
High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010
 
Nicholas' Performance Talk at Google
Nicholas' Performance Talk at GoogleNicholas' Performance Talk at Google
Nicholas' Performance Talk at Google
 
High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010
 
Performance on the Yahoo! Homepage
Performance on the Yahoo! HomepagePerformance on the Yahoo! Homepage
Performance on the Yahoo! Homepage
 
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
 

Dernier

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 

Dernier (20)

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 

Build Scalable JavaScript Apps with Modular Architecture

  • 1. Scalable JavaScript Application Architecture Nicholas C. Zakas | @slicknet
  • 2. Whos this guy? Ex-tech lead Co-Creator Contributor, Yahoo! csslint.net Creator of YUI TestAuthor Lead Author Contributor Lead Author
  • 5. ModelView Controller
  • 6. Single-page apps &Multi-page apps
  • 8. An application framework is like a playground for your codeProvides structure around otherwise unrelated activities flickr.com/photos/osterwalder/152697503/
  • 9. Isnt that what JavaScript libraries do?
  • 10. flickr.com/photos/skistz/398429879/A JavaScript library is like a toolbox You can build any number of things using the tools
  • 11. Application CoreBase Library
  • 13. 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
  • 14. 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
  • 15.
  • 16.
  • 17. How does this apply to web applications?
  • 18. web application module (n)1 : an independent unit of functionality that is part of the totalstructure of a web application Source: Me
  • 19.
  • 20. Web application modules consist of HTML + CSS + JavaScript
  • 21. Any single module should be ableto live on its own
  • 22. Loose coupling allows you to make changes to one module without affecting the others flickr.com/photos/quinnanya/3575417671/
  • 23. flickr.com/photos/renfield/3414246938/ Each module has its own sandbox An interface with which the module can interact to ensure loose coupling
  • 24. Module Module ModuleModule Sandbox Module Application Core Base Library
  • 26. Module Module ModuleModule Sandbox Module Modules have limited knowledge Each module knows about their sandbox and thats it
  • 27. Core.register("module-name", function(sandbox){ return { init: function(){ //constructor }, destroy: function(){ //destructor } };});
  • 28. Which parts know about the web application being built?
  • 30. 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/
  • 31. What is a modules job?
  • 32. Hello, Im the weather module.Its my job to tell you the weather.
  • 33. Hello, Im the stocks module.Its my job to tell you about thestock market.
  • 34. Each modules job is to create a meaningful user experience
  • 35. flickr.com/photos/eljay/2392332379/ The web application is created as a result of all parts doing their job
  • 36. This doesnt mean modules can do whatever they want to do their job
  • 37. flickr.com/photos/tedsblog/43433812/ Modules are like little kidsThey need a strict set of rules so they dont get into trouble
  • 38. Module Rules• Hands 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 objects• Ask, dont take  Anything else you need, ask the sandbox• Dont leave your toys around  Dont create global objects• Dont talk to strangers  Dont directly reference other modules
  • 39. Modules must stay within their own sandboxes No matter how restrictive or uncomfortable it may seemflickr.com/photos/madaise/3406217980/
  • 41. Module Module ModuleModule Sandbox Module Application Core Base Library
  • 42. SandboxThe sandbox ensures a consistent interface Modules can rely on the methods to always be there
  • 43. Module Module ModuleModule Sandbox Module Application Core Base Library
  • 44. Module Module ModuleModule Sandbox Module Modules only know the sandbox The rest of the architecture doesnt exist to them
  • 45. 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/
  • 46. Core.register("module-name", function(sandbox){ return { init: function(){ //not sure if Im allowed... if (sandbox.iCanHazCheezburger()){ alert("thx u"); } }, destroy: function(){ //destructor } };});
  • 47. Sandbox Jobs• Consistency• Security• Communication
  • 48. Take the time to design the correct sandbox interface It cant change later
  • 50. Module Module ModuleModule Sandbox Module Application Core Base Library
  • 51. Application CoreThe application core manages modules Thats it
  • 52. Application Coreaka Application Controller
  • 53. The application core tells a module whenit should initialize and when it should shutdown flickr.com/photos/bootbearwdc/20817093/ flickr.com/photos/bootbearwdc/20810695/
  • 54. 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; } } }}();
  • 55. 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... };}();
  • 56. //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();
  • 57. The application core managescommunication between modules flickr.com/photos/markhillary/353738538/
  • 58.
  • 59. 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 }};
  • 60. 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});
  • 61. 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; } } };});
  • 62. When modules are loosely coupled, removing a module doesnt break the othersNo direct access to another module = no breaking should the module disappear
  • 63. The application core handles errorsUses available information to determine best course of action flickr.com/photos/brandonschauer/3168761995/
  • 64. 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}();
  • 66. Application Core Jobs• Manage module lifecycle• Enable inter-module communication• General error handling• Be extensible
  • 68. Web applications changeOften in ways that you couldnt possibly anticipate
  • 70. 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
  • 71. Module Module ModuleModule Sandbox Module ApplicationExtension Extension Core Base Library
  • 72. What Extensions?• Error handling• Ajax communication• New module capabilities• General utilities• Anything!
  • 73. Ajax communication comes in different forms Tends to be tied to something available on the server
  • 74. Request format Entrypoint Response formatThree parts must be in sync for Ajax to work Modules shouldnt know anything about any of this
  • 75. Module Module ModuleModule Sandbox Module ApplicationExtension Ajax/XML Core Base Library
  • 76. 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>
  • 77. 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
  • 78. 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
  • 79. 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
  • 80. Request format Entrypoint Response formatAjax extension encapsulates all details Any of these three can change without affecting modules
  • 81. GET ?name=value&name=value /request Request format Entrypoint Response format{ status: "ok|error", data: { results: [ "...", "..." ] }}
  • 82. Module Module ModuleModule Sandbox Module ApplicationExtension Ajax/JSON Core Base Library
  • 83. Ajax Extension Jobs• Hide Ajax communication details• Provide common request interface• Provide common response interface• Manage server failures
  • 85. Module Module ModuleModule Sandbox Module ApplicationExtension Extension Core Base Library
  • 86. The base library provides basic functionality Ironic, huh? Base Library
  • 87.
  • 88. 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
  • 89. High-Performance JavaScript, OSCON 2007 Joseph Smarr, Plaxo, Inc.
  • 91. Ideally, only the application corehas any idea what base library is being used
  • 92. Module Module ModuleModule Sandbox Module Application Core Dojo
  • 93. Module Module ModuleModule Sandbox Module Application Core YUI
  • 94. Base Library Jobs• Browser normalization• General-purpose utilities  Parsers/serializers for XML, JSON, etc.  Object manipulation  DOM manipulation  Ajax communication• Provide low-level extensibility
  • 95. Module Module ModuleModule Sandbox Module ApplicationExtension Extension CoreExtension Base Library Extension
  • 97. Module Module ModuleModule Sandbox Module ApplicationExtension Extension CoreExtension Base Library Extension
  • 98. Only the base library knows which browser is being used No other part of the architecture should need to know Base Library
  • 99. 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
  • 100. Sandbox Application CoreOnly the sandbox knows which application core is being used No other part of the architecture should need to know
  • 101. 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
  • 102. Module Module ModuleModule Sandbox Module ApplicationExtension Extension CoreExtension Base Library ExtensionNo part knows about the web application
  • 104. flickr.com/photos/kgoldendragon613/278240446/Multiple different applications can be created with the same framework Minimize ramp-up time by reusing existing components
  • 105. Each part can be tested separatelyYou just need to verify that each is doing its unique job flickr.com/photos/misocrazy/151021636/
  • 106. A scalable JavaScript architectureallows you to replace any blockwithout fear of toppling the tower flickr.com/photos/aku-ma/2424194422/
  • 108. Etcetera•My blog: www.nczonline.net•Twitter: @slicknet•These Slides: slideshare.net/nzakas