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.

26 comments

Comments 1 - 10 of 26 comments previous next Post a comment

  • + guestc73cf40 Jeff Sturgis 1 week ago
    Nicholas, this is a terrific concept and I would like to apply it to an application I am currently working on. Another team already wrote the application in a procedural way. I have a few questions for you regarding re-writing this code using your scalable architecture. I have contacted you via linked in please get back to me if you have time to discuss. Thanks in advance.
  • + anisasliney Anisa Sliney Mark 1 week ago
    Hey

    Thanks for the uploads.. Very Informative I say..

    Regards
    Anisa
    http://phonehut.info
    http://www.jpolls.net
  • + nzakas Nicholas Zakas 3 months ago
    Hi Jacob,

    I’m glad you enjoyed the presentation. I’m afraid there’s no easy answers to your questions, because every system is different based on the requirements that you have. In my world, yes, each module controls a specific part of the page. Within that module, you may have one or more widgets such as tabs. I can’t really give you a general 'this is the way it should be' without understanding the context of the application, but I can say that you need to define the granularity both for 'module' and for 'widget', define that relationship, and use that to guide your design decisions.

    You can pass data to a modules in any number of ways. You may, for instance, output configuration data onto the page that is tied to your module only by a unique ID that the framework can pick up. You also might embed the data inside of the module itself, or have the module request its data from the server once instantiated. It really depends on the overall system architecture. As I said when I gave the talk, I purposely didn’t include a lot of code because it really depends very heavily on your use case.

    I don’t know jQuery very well, but your approach seems logical to me.
  • + guest9722cc1 Jacob Singh 3 months ago
    Hi Nicholas, Great stuff. I’m trying to put some of this into practice. In short, building a media browser (Digital Asset Management interface - think Finder for OSX).

    I am hitting these walls, any feedback would be really appreciated:

    1. Modules control their own markup Your examples kinda assume that modules occupy their own space on the page I think. This is fine on the twitter page, but we have concepts like ’tabs’ or ’right pane’ wherein someone might add a ’youtube’ module, which provides a ’youtube’ tab. We don’t want some tabs to be crazy colors and positioned left:2. So really, is this:

    Sandbox.addTab(title, callbackFunction)?


    2. How should I pass params to modules when I instantiate them? What does application instantiation look like in this case? Are you thinking:

    app = new MediaBrowserApplication(bunch_o_options); app.register(’mod1’, App.modules.mod1, module_specific_options);
    app.startAll();


    3. Interaction w/ DOM. I’m stuck with jQuery on this project. The entire app would be contained inside a single wrapper element. How do the two jive? My gut so far is:

    mb = new MediaBrowser() // this is the Application part of your examples

    mb.register(’browser’, mediaBrowserPlugin);
    mb.register(’folder’, folderPlugin);
    $(’’).mediaBrowser(mb);

    I don’t know how well you know jQuery plugins, but you get this gist. Is this insane?


    I really appreciate you taking the time to write this and read my comments. There is a serious lack of articles on frameworks for JavaScript which emphasize decoupling and extension, this is the best I’ve seen thus far.

    Best, Jacob
  • + nzakas Nicholas Zakas 3 months ago
    @lorewap3 - I don’t know of any books that talk about this specifically (maybe I should write one!), but really, all of the concepts I talk about are in the realm of design patterns. If you pick up some good design pattern books, you’ll get a good base of understanding to start building a more scalable architecture.
  • + ronntx Ni Tancy 3 months ago
    Scalable JavaScript Application Architecture
  • + guest2c3805ec guest2c3805ec 3 months ago



    <b>[Comment posted from</b> http://www.zhuoqun.net/]
  • + lorewap3 lorewap3 4 months 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 4 months ago
    Never mind, found it on YUI theather !. Superb presentation. Would love to hear from you more and more. Keep on
  • + guest787fe3 Gytis Greitai 4 months 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.

Comments 1 - 10 of 26 comments previous next

Login or Signup to post a comment
Edit your comment Cancel

74 Favorites & 2 Groups

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, 6 months ago

 

10777 views, 74 favs, 17 embeds more

About this presentation

© All Rights Reserved

  • Favorites 74
  • Comments 26
  • Downloads 601
  • Total Views 10777
    • 10140 on SlideShare
    • 637 from embeds
Embed views
  • 542 views on http://www.zhuoqun.net
  • 27 views on http://abava.blogspot.com
  • 18 views on http://blog.notsobad.cn
  • 9 views on http://ycao.ctripued.com
  • 9 views on http://static.slidesharecdn.com

more

Embed views
  • 542 views on http://www.zhuoqun.net
  • 27 views on http://abava.blogspot.com
  • 18 views on http://blog.notsobad.cn
  • 9 views on http://ycao.ctripued.com
  • 9 views on http://static.slidesharecdn.com
  • 8 views on http://servletsuite.blogspot.com
  • 7 views on http://www.zhuaxia.com
  • 6 views on http://www.bo-ke-blog.net
  • 2 views on http://xss.yandex.net
  • 2 views on http://zhuaxia.com
  • 1 views on http://feed.zhuoqun.net
  • 1 views on http://translate.googleusercontent.com
  • 1 views on http://feed.feedsky.com
  • 1 views on http://m41.mail.qq.com
  • 1 views on http://xianguo.com
  • 1 views on http://potipotis.blogspot.com
  • 1 views on http://www.slideshare.net

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