• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Scalable JavaScript Application Architecture
 

Scalable JavaScript Application Architecture

on

  • 156,985 views

Discover how to build a JavaScript application framework that scales for the challenges of today's complex web applications.

Discover how to build a JavaScript application framework that scales for the challenges of today's complex web applications.

Statistics

Views

Total Views
156,985
Views on SlideShare
146,038
Embed Views
10,947

Actions

Likes
514
Downloads
4,474
Comments
46

112 Embeds 10,947

https://tutsplus.com 2090
http://tutsplus.com 1927
http://mobicon.tistory.com 1091
http://www.zhuoqun.net 1073
http://www.scoop.it 818
http://ontwik.com 557
http://caoyue.sinaapp.com 518
http://www.slideshare.net 505
http://lanyrd.com 367
http://dovapour.info 300
http://www.pixelovers.com 264
http://mcloide.wordpress.com 260
http://academy.formosasoft.com 119
https://twitter.com 117
http://www.cnblogs.com 89
http://paper.li 78
http://blog.waleedmohamed.net 77
http://feeds.nexoblogs.com 53
http://localhost 45
http://abava.blogspot.com 45
file:// 32
http://devilalbum.com 31
http://www.wooui.com 28
http://blog.notsobad.cn 27
http://waleedmohamed.net 26
http://tetgo.sinaapp.com 22
http://ycao.ctripued.com 22
http://www.obolog.com 21
http://a0.twimg.com 19
http://tantrieuf31.blogspot.com 18
https://twimg0-a.akamaihd.net 17
http://twitter.com 15
http://us-w1.rockmelt.com 14
http://app1.prvt.nytimes.com 14
http://www.jimzhan.com 14
http://dev.graymound.com 13
https://si0.twimg.com 13
http://www.bo-ke-blog.net 13
http://blog.fasoulas.com 10
http://static.slidesharecdn.com 10
http://www.zhuaxia.com 9
http://fe.com 8
http://zhuaxia.com 8
https://jabbr.net 8
http://servletsuite.blogspot.com 8
http://9a0e.m9.tcp.cc 6
http://bundlr.com 6
http://theoldreader.com 5
http://cache.baidu.com 5
http://cloud-notepad.blogspot.com 5
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

110 of 46 previous next Post a comment

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • How can this be reconciled with AMD, where in each module you import all the other modules you need in a define statement and access them directly as opposed to using a single sandbox?
    Are you sure you want to
    Your message goes here
    Processing…
  • 很有实践指导意义啊
    感谢作者
    Are you sure you want to
    Your message goes here
    Processing…
  • Great presentation! It's not only useful for JavaScript developers, but the idea is also very inspiring for developers using other languages.

    I'm refactoring LIVEditor (New html editor with a Firebug-like UI) and am having an architecture problem, now I got an idea as to how to solve the problem after re-viewing this slide again. Thanks!
    Are you sure you want to
    Your message goes here
    Processing…
  • This is similar to an approach we use based on OpenSocial Gadgets. Your 'module' is a 'gadget' and they communicate over a PageBus in a publish/subscribe manner using Tibco's PageBus.

    Gadgets can be rendered in-line in a div, or inside an iframe for greater 'sandboxing'. Each Gadget contains it's own javascript / html code, their metadata also describes the messages they can send / receive, and we have a gadget repository and a framework for building mash-ups which are custom collections of these gadgets.

    For those of you who like this idea, check out some casts on the Tibco site and also read about OpenSocial Gadgets.
    Are you sure you want to
    Your message goes here
    Processing…
  • A fairly simple implementation that follows this talk fairly closely can be found here:

    https://github.com/aranm/scalable-javascript-architecture
    Are you sure you want to
    Your message goes here
    Processing…

110 of 46 previous next

Post Comment
Edit your comment

    Scalable JavaScript Application Architecture Scalable JavaScript Application Architecture Presentation Transcript

    • 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