Scalable JavaScript Application Architecture

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

19 comments

Comments 1 - 10 of 19 previous next Post a comment

  • + lorewap3 lorewap3 1 week ago
    Hi Nicholas,

    Your presentation is wonderful and I’d really like to adopt this approach, but I would like to learn more before I try to develop my own core/sandbox/modules from scratch.

    I have alot of javascript reference books, and consider myself fairly competent with the syntax. However, none of these references go into the large scale design concepts you talk about.

    Are there any resources that you could direct me to that go deeper into this topic? Maybe there is a small example core/sandbox/module package that would help to illustrate specific functions that would be common inside each layer (besides the ones you touched upon). Maybe a very low level template that would get someone started that is just looking to create modules that do simple ajax calls and table/form manipulation?

    I certainly don’t want to ask for anything proprietary, but any books that you know of, web articles, or sample code that inspired you to design this framework would be invaluable to a small business developer like me.

    Thank you so much, you’ve convinced me of the route my designs need to take!
  • + guest787fe3 Gytis Greitai 2 weeks ago
    Never mind, found it on YUI theather !. Superb presentation. Would love to hear from you more and more. Keep on
  • + guest787fe3 Gytis Greitai 2 weeks ago
    Hi,

    saw your presentation on javascript variables on youtube. Superb. Wonder if any other of your presentations are available somewhere on the internet? Or just these slides? Would love to see them, though neither youtube neither yahoo video gave some more info on that.
  • + nzakas Nicholas Zakas 3 weeks ago
    I’m not sure I completely understand your question, but let me give this a shot. There’s really no concept of security in this architecture, you’re assuming that all modules were written by the application developer and, therefore, don’t need to be protected from one another. For communication and determining whether a module should be allowed to do something or not, that’s up to each extension. You should probably have some meta data associated with each module that the extension can look at to determine what it should or shouldn’t be able to do. But again, the responsibility for checking such meta data falls on the extensions themselves. For instance, the Ajax extension can determine whether or not to allow an Ajax request to go through.
  • + hansbrough hansbrough 3 weeks ago
    Nice presentation. One question - where does security and communication information about each module live? The sandbox is using this info about each module to relay requests to the core, or deny requests, and yet the sandbox wont have the info hardwired for all possible modules I’m assuming. Perhaps modules exist as ’types’ that inherit a ruleset from the sandbox?
  • + arnabc arnabc 4 weeks ago
    after digging through the new Yahoo homepage JS code, I saw exactly similar code where it’s calling 'getService(’yui’)', I think this is the architecture that the new Yahoo home page is built on, it’s really cool :-)
  • + nzakas Nicholas Zakas 1 month ago
    The idea is that you request the wrapper through the sandbox. For example:

    var domUtil = sandbox.getService('domUtil');

    The module still has to request access to the DOM utility, which provides the proper level of abstraction.
  • + agrohe agrohe 1 month ago
    Based on your previous comment, you recommend that the modules can access the base library via a wrapper layer. Doesn’t this violate the idea that modules only know about the sandbox?
  • + arnabc arnabc 1 month ago
    @Nicholas Thanks for replying, now I have understood that this can be done using adapter pattern, thanks again for pointing that, have a nice time.
  • + nzakas Nicholas Zakas 1 month ago
    Hi arnabc -

    The best way to do this is to create a wrapper for the base library DOM methods you want to use and allow the modules to access that. That way, you can change the base library and just create a new wrapper with the same methods.

Comments 1 - 10 of 19 previous next

Post a comment
Embed Video
Edit your comment Cancel

41 Favorites & 1 Group

Scalable JavaScript Application Architecture - Presentation Transcript

  1. Scalable JavaScript Application Architecture Nicholas C. Zakas Principal Front End Engineer, Yahoo! Bayjax – September 2009
  2. Who's this guy? • Principal Front End Engineer, Yahoo! Homepage • YUI Contributor • Author
  3. Building an application framework
  4. An application framework is like a playground for your code Provides structure around otherwise unrelated activities
  5. Isn't that what JavaScript libraries do?
  6. A JavaScript library is like a toolbox You can build any number of things using the tools
  7. Application Core Base Library
  8. Module Theory Everything is a module
  9. module (n) 1 : a standard or unit of measurement 2 : the size of some one part taken as a unit of measure by which the proportions of an architectural composition are regulated 3 a : any in a series of standardized units for use together: as (1) : a unit of furniture or architecture (2) : an educational unit which covers a single subject or topic b : a usually packaged functional assembly of electronic components for use with other such assemblies 4 : an independently operable unit that is a part of the total structure of a space vehicle 5 a : a subset of an additive group that is also a group under addition b : a mathematical set that is a commutative group under addition and that is closed under multiplication which is distributive from the left or right or both by elements of a ring and for which a(bx) = (ab)x or (xb)a = x(ba) or both where a and b are elements of the ring and x belongs to the set Source: Merriam-Webster Dictionary
  10. module (n) 1 : a standard or unit of measurement 2 : the size of some one part taken as a unit of measure by which the proportions of an architectural composition are regulated 3 a : any in a series of standardized units for use together: as (1) : a unit of furniture or architecture (2) : an educational unit which covers a single subject or topic b : a usually packaged functional assembly of electronic components for use with other such assemblies 4 : an independently operable unit that is a part of the total structure of a space vehicle 5 a : a subset of an additive group that is also a group under addition b : a mathematical set that is a commutative group under addition and that is closed under multiplication which is distributive from the left or right or both by elements of a ring and for which a(bx) = (ab)x or (xb)a = x(ba) or both where a and b are elements of the ring and x belongs to the set Source: Merriam-Webster Dictionary
  11. How does this apply to web applications?
  12. web application module (n) 1 : an independent unit of functionality that is part of the total structure of a web application Source: Me
  13. Web application modules consist of HTML + CSS + JavaScript
  14. Any single module should be able to live on its own
  15. Loose coupling allows you to make changes to one module without affecting the others
  16. Each module has its own sandbox An interface with which the module can interact to ensure loose coupling
  17. Module Module Module Module Sandbox Module Application Core Base Library
  18. Application Architecture • Modules • Sandbox • Application Core • Base Library
  19. Module Module Module Module Sandbox Module Modules have limited knowledge Each module knows about their sandbox and that's it
  20. Core.register("module-name", function(sandbox){ return { init: function(){ //constructor }, destroy: function(){ //destructor } }; });
  21. Which parts know about the web application being built?
  22. None of them
  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
  24. What is a module's job?
  25. Hello, I'm the weather module. It's my job to tell you the weather.
  26. Hello, I'm the stocks module. It's my job to tell you about the stock market.
  27. Each module's job is to create a meaningful user experience
  28. The web application is created as a result of all parts doing their job
  29. This doesn't mean modules can do whatever they want to do their job
  30. Modules are like little kids They need a strict set of rules so they don't get into trouble
  31. Module Rules • Hands to yourself – Only call your own methods or those on the sandbox – Don't access DOM elements outside of your box – Don't access non-native global objects • Ask, don't take – Anything else you need, ask the sandbox • Don't leave your toys around – Don't create global objects • Don't talk to strangers – Don't directly reference other modules
  32. Modules must stay within their own sandboxes No matter how restrictive or uncomfortable it may seem
  33. Application Architecture • Modules • Sandbox • Application Core • Base Library
  34. Module Module Module Module Sandbox Module Application Core Base Library
  35. Sandbox The sandbox ensures a consistent interface Modules can rely on the methods to always be there
  36. Module Module Module Module Sandbox Module Application Core Base Library
  37. Module Module Module Module Sandbox Module Modules only know the sandbox The rest of the architecture doesn't exist to them
  38. The sandbox also acts like a security guard Knows what the modules are allowed to access and do on the framework
  39. Core.register("module-name", function(sandbox){ return { init: function(){ //not sure if I'm allowed... if (sandbox.iCanHazCheezburger()){ alert("thx u"); } }, destroy: function(){ //destructor } }; });
  40. Sandbox Jobs • Consistency – Interface must be dependable • Security – Determine which parts of the framework a module can access • Communication – Translate module requests into core actions
  41. Take the time to design the correct sandbox interface It can't change later
  42. Application Architecture • Modules • Sandbox • Application Core • Base Library
  43. Module Module Module Module Sandbox Module Application Core Base Library
  44. Application Core The application core manages modules That's it
  45. The application core tells a module when it should initialize and when it should shutdown
  46. 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; } } } }();
  47. 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... }; }();
  48. //register modules Core.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 modules Core.startAll();
  49. The application core manages communication between modules
  50. TimelineFilter = { changeFilter: function(filter){ Timeline.applyFilter(filter); } }; Tight Coupling StatusPoster = { postStatus: function(status){ Timeline.post(status); } }; Tight Coupling Timeline = { applyFilter: function(filter){ //implementation }, post: function(status){ //implementation } };
  51. 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 });
  52. 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; } } }; });
  53. When modules are loosely coupled, removing a module doesn't break the others No direct access to another module = no breaking should the module disappear
  54. The application core handles errors Uses available information to determine best course of action
  55. 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 }();
  56. Learn more http://www.slideshare.net/nzakas/enterprise-javascript-error-handling-presentation
  57. Application Core Jobs • Manage module lifecycle – Tell modules when to start and stop doing their job • Enable inter-module communication – Allow loose coupling between modules that are related to one another • General error handling – Detect, trap, and report errors in the system • Be extensible – The first three jobs are not enough!
  58. Why not?
  59. Web applications change Often in ways that you couldn't possibly anticipate
  60. Plan for extension
  61. Anything built for extension can never be obsolete Extensions augment the capabilities of the core to keep it relevant and useful
  62. Module Module Module Module Sandbox Module Application Extension Extension Core Base Library
  63. What Extensions? • Error handling • Ajax communication • New module capabilities • General utilities • Anything!
  64. Ajax communication comes in different forms Tends to be tied to something available on the server
  65. Request format Entrypoint Response format Three parts must be in sync for Ajax to work Modules shouldn't know anything about any of this
  66. Module Module Module Module Sandbox Module Application Extension Ajax/XML Core Base Library
  67. 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>
  68. Entrypoint var xhr = new XMLHttpRequest(); xhr.open("get", "/ajax?name=value", true); Request xhr.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
  69. Library reference Entrypoint var 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
  70. 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
  71. Request format Entrypoint Response format Ajax extension encapsulates all details Any of these three can change without affecting modules
  72. GET ?name=value&name=value /request Request format Entrypoint Response format { status: "ok|error", data: { results: [ "...", "..." ] } }
  73. Module Module Module Module Sandbox Module Application Extension Ajax/JSON Core Base Library
  74. Ajax Extension Jobs • Hide Ajax communication details – Modules don't need to know any of it • Provide common request interface – Modules use this interface to specify data to send to the server • Provide common response interface – Modules use this interface to retrieve data from the response • Manage server failures – Modules only care if they got what they wanted or not, don't care why
  75. Application Architecture • Modules • Sandbox • Application Core • Base Library
  76. Module Module Module Module Sandbox Module Application Extension Extension Core Base Library
  77. The base library provides basic functionality Ironic, huh? Base Library
  78. Most applications are too tightly coupled to the base library Developers get upset when they can't touch the base library directly
  79. High-Performance JavaScript, OSCON 2007 Joseph Smarr, Plaxo, Inc.
  80. Learn more http://josephsmarr.com/2007/07/25/high-performance-javascript-oscon-2007/
  81. Ideally, only the application core has any idea what base library is being used
  82. Module Module Module Module Sandbox Module Application Core Dojo
  83. Module Module Module Module Sandbox Module Application Core YUI
  84. Base Library Jobs • Browser normalization – Abstract away differences in browsers with common interface • General-purpose utilities – Parsers/serializers for XML, JSON, etc. – Object manipulation – DOM manipulation – Ajax communication • Provide low-level extensibility
  85. Module Module Module Module Sandbox Module Application Extension Extension Core Extension Base Library Extension
  86. Architecture Knowledge
  87. Module Module Module Module Sandbox Module Application Extension Extension Core Extension Base Library Extension
  88. Only the base library knows which browser is being used No other part of the architecture should need to know Base Library
  89. 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
  90. Sandbox Application Core Only the sandbox knows which application core is being used No other part of the architecture should need to know
  91. Module Module Module Module Sandbox Module The modules know nothing except that the sandbox exists They have no knowledge of one another or the rest of the architecture
  92. Module Module Module Module Sandbox Module Application Extension Extension Core Extension Base Library Extension No part knows about the web application
  93. Advantages
  94. Multiple different applications can be created with the same framework Minimize ramp-up time by reusing existing components
  95. Each part can be tested separately You just need to verify that each is doing it's unique job
  96. A scalable JavaScript architecture allows you to replace any block without fear of toppling the tower
  97. Questions?
  98. Etcetera • My blog: www.nczonline.net • My email: nzakas@yahoo-inc.com • Twitter: @slicknet
  99. Creative Commons Images Used • tonythemisfit/2476732428/ • bootbearwdc/20817093/ • jamesbt/3121318942/ • markhillary/353738538/ • osterwalder/152697503/ • brandonschauer/3168761995/ • renfield/3414246938/ • pointnshoot/1443575327/ • ejchang/2547231236/ • kartik_m/2724121901/ • quinnanya/3575417671/ • goldendragon613/278240446/ • generated/501445202/ • misocrazy/151021636/ • eljay/2392332379/ • aku-ma/2424194422/ • tedsblog/43433812/ • 29505605@N08/3198765320/ • torley/2361164281/ • madaise/3406217980/ • heraklit/169566548/ • bootbearwdc/20810695/ All available at http://www.flickr.com/photos/

+ Nicholas ZakasNicholas Zakas, 2 months ago

custom

4527 views, 41 favs, 6 embeds more stats

Discover how to build a JavaScript application fram more

More info about this document

© All Rights Reserved

Go to text version

  • Total Views 4527
    • 4486 on SlideShare
    • 41 from embeds
  • Comments 19
  • Favorites 41
  • Downloads 267
Most viewed embeds
  • 25 views on http://abava.blogspot.com
  • 7 views on http://servletsuite.blogspot.com
  • 5 views on http://static.slidesharecdn.com
  • 2 views on http://xss.yandex.net
  • 1 views on http://www.slideshare.net

more

All embeds
  • 25 views on http://abava.blogspot.com
  • 7 views on http://servletsuite.blogspot.com
  • 5 views on http://static.slidesharecdn.com
  • 2 views on http://xss.yandex.net
  • 1 views on http://www.slideshare.net
  • 1 views on http://potipotis.blogspot.com

less

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

Cancel
File a copyright complaint
Having problems? Go to our helpdesk?

Categories

Groups / Events