Closure: The Definitive Guide

Book description

If you're ready to use Closure to build rich web applications with JavaScript, this hands-on guide has precisely what you need to learn this suite of tools in depth. Closure makes it easy for experienced JavaScript developers to write and maintain large and complex codebases—as Google has demonstrated by using Closure with Gmail, Google Docs, and Google Maps.

Author and Closure contributor Michael Bolin has included numerous code examples and best practices, as well as valuable information not available publicly until now. You'll learn all about Closure's Library, Compiler, Templates, testing framework, and Inspector—including how to minify JavaScript code with the Compiler, and why the combination of the Compiler and the Library is what sets Closure apart from other JavaScript toolkits.

  • Learn how the Compiler significantly reduces the amount of JavaScript users have to download when visiting your site
  • Discover several ways to use the Compiler as part of your build process
  • Learn about type expressions, primitives, and common utilities
  • Understand how Closure emulates classes and class-based inheritance
  • Use Closure Templates on the server and the client from either JavaScript or Java
  • Test and debug your JavaScript code, even when it's compiled

Publisher resources

View/Submit Errata

Table of contents

  1. Closure: The Definitive Guide
  2. SPECIAL OFFER: Upgrade this ebook with O’Reilly
  3. Foreword
  4. Preface
    1. My Experiences with Closure
    2. Audience
    3. ECMAScript Versus JavaScript
    4. Using This Book
    5. Conventions Used in This Book
    6. Using Code Examples
    7. Safari® Books Online
    8. How to Contact Us
    9. Acknowledgments
  5. 1. Introduction to Closure
    1. Tools Overview
      1. Closure Library
      2. Closure Templates
      3. Closure Compiler
      4. Closure Testing Framework
      5. Closure Inspector
    2. Closure Design Goals and Principles
      1. Reducing Compiled Code Size Is Paramount
      2. All Source Code Is Compiled Together
      3. Managing Memory Matters
      4. Make It Possible to Catch Errors at Compile Time
      5. Code Must Work Without Compilation
      6. Code Must Be Browser-Agnostic
      7. Built-in Types Should Not Be Modified
      8. Code Must Work Across Frames
      9. Tools Should Be Independent
    3. Downloading and Installing the Tools
      1. Closure Library and Closure Testing Framework
      2. Closure Templates
      3. Closure Compiler
      4. Closure Inspector
    4. Example: Hello World
      1. Closure Library
      2. Closure Templates
      3. Closure Compiler
      4. Closure Testing Framework
      5. Closure Inspector
  6. 2. Annotations for Closure JavaScript
    1. JSDoc Tags
    2. Type Expressions
      1. Simple Types and Union Types
      2. Function Types
      3. Record Types
      4. Special @param Types
        1. Specifying optional parameters
        2. Optional parameters
        3. Variable number of parameters
      5. Subtypes and Type Conversion
      6. The ALL Type
    3. JSDoc Tags That Do Not Deal with Types
      1. Constants
      2. Deprecated Members
      3. License and Copyright Information
    4. Is All of This Really Necessary?
  7. 3. Closure Library Primitives
    1. Dependency Management
      1. calcdeps.py
      2. goog.global
        1. Finer details of goog.global
      3. COMPILED
      4. goog.provide(namespace)
        1. Motivation behind goog.provide()
      5. goog.require(namespace)
      6. goog.addDependency(relativePath, provides, requires)
    2. Function Currying
      1. goog.partial(functionToCall, ...)
      2. goog.bind(functionToCall, selfObject, ...)
    3. Exports
      1. goog.getObjectByName(name, opt_object)
      2. goog.exportProperty(object, propertyName, value)
      3. goog.exportSymbol(publicPath, object, opt_objectToExportTo)
    4. Type Assertions
      1. goog.typeOf(value)
      2. goog.isDef(value)
      3. goog.isNull(value)
      4. goog.isDefAndNotNull(value)
      5. goog.isArray(obj)
      6. goog.isArrayLike(obj)
      7. goog.isDateLike(obj)
      8. goog.isString(obj), goog.isBoolean(obj), goog.isNumber(obj)
      9. goog.isFunction(obj)
      10. goog.isObject(obj)
    5. Unique Identifiers
      1. goog.getUid(obj)
      2. goog.removeUid(obj)
    6. Internationalization (i18n)
      1. goog.LOCALE
      2. goog.getMsg(str, opt_values)
    7. Object Orientation
      1. goog.inherits(childConstructorFunction, parentConstructorFunction)
      2. goog.base(self, opt_methodName, var_args)
      3. goog.nullFunction
      4. goog.abstractMethod
      5. goog.addSingletonGetter(constructorFunction)
    8. Additional Utilities
      1. goog.DEBUG
      2. goog.now()
      3. goog.globalEval(script)
      4. goog.getCssName(className, opt_modifier), goog.setCssNameMapping(mapping)
  8. 4. Common Utilities
    1. goog.string
      1. goog.string.htmlEscape(str, opt_isLikelyToContainHtmlChars)
      2. goog.string.regExpEscape(str)
      3. goog.string.whitespaceEscape(str, opt_xml)
      4. goog.string.compareVersions(version1, version2)
      5. goog.string.hashCode(str)
    2. goog.array
      1. goog.array.forEach(arr, func, opt_obj)
      2. Using Iterative goog.array Functions in a Method
    3. goog.object
      1. goog.object.get(obj, key, opt_value)
      2. goog.setIfUndefined(obj, key, value)
      3. goog.object.transpose(obj)
    4. goog.json
      1. goog.json.parse(str)
      2. goog.json.unsafeParse(str)
      3. goog.json.serialize(obj)
    5. goog.dom
      1. goog.dom.getElement(idOrElement)
      2. goog.dom.getElementsByTagNameAndClass(nodeName, className, elementToLookIn)
      3. goog.dom.getAncestorByTagNameAndClass(element, tag, className)
      4. goog.dom.createDom(nodeName, attributes, var_args)
      5. goog.dom.htmlToDocumentFragment(htmlString)
      6. goog.dom.ASSUME_QUIRKS_MODE and goog.dom.ASSUME_STANDARDS_MODE
    6. goog.dom.classes
      1. goog.dom.classes.get(element)
      2. goog.dom.classes.has(element, className)
      3. goog.dom.classes.add(element, var_args) and goog.dom.classes.remove(element, var_args)
      4. goog.dom.classes.toggle(element, className)
      5. goog.dom.classes.swap(element, fromClass, toClass)
      6. goog.dom.classes.enable(element, className, enabled)
    7. goog.userAgent
      1. Rendering Engine Constants
      2. Platform Constants
      3. goog.userAgent.isVersion(version)
    8. goog.userAgent.product
    9. goog.net.cookies
      1. goog.net.cookies.isEnabled()
      2. goog.net.cookies.set(name, value, opt_maxAge, opt_path, opt_domain)
      3. goog.net.cookies.get(name, opt_default)
      4. goog.net.cookies.remove(name, opt_path, opt_domain)
    10. goog.style
      1. goog.style.getPageOffset(element)
      2. goog.style.getSize(element)
      3. goog.style.getBounds(element)
      4. goog.style.setOpacity(element, opacity)
      5. goog.style.setPreWrap(element)
      6. goog.style.setInlineBlock(element)
      7. goog.style.setUnselectable(element, unselectable, opt_noRecurse)
      8. goog.style.installStyles(stylesString, opt_node)
      9. goog.style.scrollIntoContainerView(element, container, opt_center)
    11. goog.functions
      1. goog.functions.TRUE
      2. goog.functions.constant(value)
      3. goog.functions.error(message)
  9. 5. Classes and Inheritance
    1. Example of a Class in Closure
      1. Closure JavaScript Example
      2. Equivalent Example in Java
      3. Static Members
      4. Singleton Pattern
    2. Example of a Subclass in Closure
      1. Closure JavaScript Example
      2. Equivalent Example in Java
      3. Declaring Fields in Subclasses
      4. @override and @inheritDoc
      5. Using goog.base() to Simplify Calls to the Superclass
      6. Abstract Methods
    3. Example of an Interface in Closure
    4. Multiple Inheritance
    5. Enums
    6. goog.Disposable
      1. Overriding disposeInternal()
  10. 6. Event Management
    1. A Brief History of Browser Event Models
    2. Closure Provides a Consistent DOM Level 2 Events API Across Browsers
      1. goog.events.listen()
      2. goog.events.EventTarget
      3. goog.events.Event
      4. goog.events.EventHandler
    3. Handling Keyboard Events
  11. 7. Client-Server Communication
    1. Server Requests
      1. goog.net.XmlHttp
      2. goog.net.XhrIo
        1. Customizing the request
        2. Handling the response
      3. goog.net.XhrManager
      4. goog.Uri and goog.uri.utils
    2. Resource Loading and Monitoring
      1. goog.net.BulkLoader
      2. goog.net.ImageLoader
      3. goog.net.IframeLoadMonitor
      4. goog.net.MultiIframeLoadMonitor
      5. goog.net.NetworkTester
    3. Cross-Domain Communication
      1. goog.net.jsonp
      2. goog.net.xpc
    4. Uploading Files
    5. Comet
  12. 8. User Interface Components
    1. Design Behind the goog.ui Package
    2. goog.ui.Component
      1. Basic Life Cycle
        1. Instantiation
        2. Display
        3. Disposal
      2. Components with Children
        1. Adding a child
        2. Removing a child
        3. Accessor methods
      3. Events
      4. States
      5. Errors
    3. goog.ui.Control
      1. Handling User Input
      2. Managing State
      3. Delegating to the Renderer
        1. Associating presentation logic with a state
        2. goog.ui.registry
        3. goog.ui.decorate
      4. Example: Responding to a Mouseover Event
    4. goog.ui.Container
    5. Using Common Components
      1. Pulling in CSS
      2. goog-inline-block
      3. Example of Rendering a Component: goog.ui.ComboBox
      4. Example of Decorating a Control: goog.ui.Button and goog.ui.CustomButton
        1. goog.ui.Button
        2. goog.ui.CustomButton
    6. Creating Custom Components
      1. example.Checklist and example.ChecklistItem
      2. example.ui.ChecklistItem and example.ui.ChecklistItemRenderer
      3. example.ui.Label
      4. example.ui.Checklist and example.ui.ChecklistRenderer
      5. Rendering Example
      6. Decorating Example
      7. Conclusions
  13. 9. Rich Text Editor
    1. Design Behind the goog.editor Package
      1. Trade-offs: Control, Code Size, and Performance
      2. goog.editor.BrowserFeature
    2. Creating an Editable Region
      1. goog.editor.Field
        1. Instantiation
        2. Making editable
        3. Getting and setting the field’s contents
        4. Change events
        5. Events
        6. State
        7. Common setters and accessors
      2. goog.editor.SeamlessField
        1. Controlling the height of a seamless field
        2. Controlling the styles of a seamless field
    3. Extending the Editor: The Plugin System
      1. Registering Plugins
      2. Interacting with Plugins 
      3. goog.editor.Plugin
        1. Handling key events
        2. Executing commands
        3. Handling selection changes
        4. Transforming field contents
        5. Advanced customization
      4. Built-in Plugins
        1. goog.editor.plugins.BasicTextFormatter
        2. goog.editor.plugins.HeaderFormatter
        3. goog.editor.plugins.RemoveFormatting
        4. goog.editor.plugins.AbstractTabHandler, goog.editor.plugins.ListTabHandler, and goog.editor.plugins.SpacesTabHandler
        5. goog.editor.plugins.EnterHandler, goog.editor.plugins.TagOnEnterHandler, and goog.editor.plugins.Blockquote
        6. goog.editor.plugins.LoremIpsum
        7. goog.editor.plugins.UndoRedo, goog.editor.plugins.UndoRedoManager, and goog.editor.plugins.UndoRedoState
        8. goog.editor.plugins.AbstractDialogPlugin
        9. goog.editor.plugins.LinkDialogPlugin
      5. Custom Plugins
        1. Creating custom plugins
        2. Creating a custom dialog plugin
    4. UI Components
      1. Dialogs
        1. goog.ui.editor.AbstractDialog
        2. Creating a custom dialog
      2. Toolbar
        1. goog.ui.editor.DefaultToolbar
        2. goog.ui.editor.ToolbarFactory
        3. goog.ui.editor.ToolbarController
        4. Creating a custom toolbar button
        5. Styling the toolbar
    5. Selections
      1. goog.dom.Range
      2. goog.dom.AbstractRange
        1. Getting endpoints of a range
        2. Setting endpoints of a range
        3. Extracting data from a range
        4. Changing the DOM
        5. Saving and restoring selections
        6. Iterating
        7. Other goodies
      3. goog.editor.range
        1. Placing the cursor
        2. Visually equivalent positions
        3. goog.editor.range.Point
        4. Normalizing
  14. 10. Debugging and Logging
    1. Creating Logging Information
      1. goog.debug.LogRecord
      2. goog.debug.Logger.Level
      3. goog.debug.Logger
        1. Creating a logger
        2. Logging a message
        3. Logger hierarchy
    2. Displaying Logging Information
      1. goog.debug.Console
      2. goog.debug.DivConsole
      3. goog.debug.DebugWindow
      4. goog.debug.FancyWindow
    3. Profiling JavaScript Code
    4. Reporting JavaScript Errors
  15. 11. Closure Templates
    1. Limitations of Existing Template Systems
      1. Server-Side Templates
      2. Client-Side Templates
    2. Introducing Closure Templates
    3. Creating a Template
      1. Declaring Templates with {namespace} and {template}
      2. Commenting Templates
      3. Overriding Line Joining with {sp} and {nil}
      4. Writing Raw Text with {literal}
      5. Building Soy Expressions
        1. Referencing map and list data
        2. Referencing global variables
      6. Displaying Data with {print}
      7. Managing Control Flow with {if}, {elseif}, and {else}
      8. Advanced Conditional Handling with {switch}, {case}, and {default}
      9. Looping over Lists with {foreach}
      10. Leveraging Other Templates with {call} and {param}
      11. Identifying CSS Classes with {css}
    4. Internationalization (i18n)
    5. Compiling Templates
      1. Compiling a Template for JavaScript
        1. Compilation
        2. Usage
      2. Compiling a Template for Java
        1. Compilation
        2. Usage
    6. Defining a Custom Function
  16. 12. Using the Compiler
    1. Benefits of Using the Compiler
      1. Reducing Code Size
      2. Catching Errors at Compile Time
      3. Protecting Code Through Obfuscation
    2. How the Compiler Works
    3. Compiler Options
      1. Compilation Levels
        1. Whitespace Only
        2. Simple
        3. Advanced
      2. Formatting Options
        1. Pretty print
        2. Print input delimiter
      3. Warning Levels
        1. Quiet
        2. Default
        3. Verbose
    4. Running the Compiler
      1. Closure Compiler Service UI
      2. Closure Compiler Service API
      3. Closure Compiler Application
        1. Fine-grained control over warnings and errors
        2. Compile-time defines
        3. Output wrapper
      4. Programmatic Java API
    5. Integrating the Compiler into a Build Process
    6. Partitioning Compiled Code into Modules
      1. Introducing the Application Code
        1. app.js
        2. settings.js
        3. api.js
      2. Introducing the Module Loading Code
        1. app_init.js
        2. settings_init.js
        3. api_init.js
      3. Partitioning the Input
        1. --module flag
        2. --module_output_path_prefix flag
      4. Loading the Modules
      5. Refining the Partitioning
  17. 13. Advanced Compilation
    1. What Happens During Compilation
      1. Externs and Exports
        1. Using custom externs
        2. Externs and the compilation model
        3. Externs versus exports
        4. Exporting methods for a public API
      2. Property Flattening
      3. Property Renaming
    2. Preparing Code for the Compiler
      1. Input Language
      2. Programmatic Evaluation of Strings of JavaScript Code
      3. Never Use the with Keyword
    3. Checks Provided by the Compiler
      1. Type Checking
        1. Unknown type warnings
      2. Access Controls
        1. Visibility
        2. Deprecated members
    4. Optimizations Performed by the Compiler
      1. Processing Closure Primitives
        1. goog.provide
        2. goog.require
        3. goog.addDependency
      2. Devirtualizing Prototype Methods
      3. Inlining
        1. Constants and folding
        2. Variables
        3. Functions
  18. 14. Inside the Compiler
    1. Tour of the Codebase
      1. Getting and Building the Compiler
      2. Compiler.java
      3. CompilerPass.java
      4. JSSourceFile.java
      5. CompilerOptions.java
      6. CompilationLevel.java
      7. WarningLevel.java
      8. PassFactory.java
      9. DefaultPassConfig.java
      10. CommandLineRunner.java
      11. com.google.common.collect
    2. Hidden Options
      1. Checks
        1. checkEs5Strict
        2. checkMissingReturn
        3. codingConvention
        4. reportUnknownTypes
      2. Renaming
        1. aliasKeywords
        2. aliasAllStrings
        3. aliasExternals
        4. exportTestFunctions
      3. Optimizations
        1. stripTypePrefixes
        2. stripNameSuffixes
        3. setIdGenerators
        4. disambiguateProperties
        5. ambiguateProperties
      4. Output
        1. lineBreak
        2. inputDelimiter
        3. colorizeErrorOutput
        4. externExports
    3. Example: Extending CommandLineRunner
    4. Example: Visualizing the AST Using DOT
      1. What Is DOT?
      2. Converting the AST to DOT
      3. Hooking into MyCommandLineRunner
    5. Example: Creating a Compiler Check
    6. Example: Creating a Compiler Optimization
  19. 15. Testing Framework
    1. Creating Your First Test
      1. Example: Testing an Email Validator
        1. Creating the initial set of tests
        2. Creating the HTML file to run the test
        3. Getting the tests to pass
        4. Creating more tests
      2. Assertions
      3. Life Cycle of a Test Case
      4. Differences from JsUnit
    2. Mock Objects
      1. goog.testing.PropertyReplacer
      2. goog.testing.PseudoRandom
      3. goog.testing.MockClock
    3. Testing to Ensure That an Error Is Thrown
    4. Testing Input Events
    5. Testing Asynchronous Behavior
      1. goog.testing.ContinuationTestCase
        1. waitForTimeout(continuation, duration)
        2. waitForEvent(eventTarget, eventType, continuation)
        3. waitForCondition(condition, continuation, interval, maxTimeout)
      2. goog.testing.AsyncTestCase
    6. Running a Single Test
    7. Running Multiple Tests
    8. Automating Tests
    9. System Testing
  20. 16. Debugging Compiled JavaScript
    1. Verify That the Error Occurs in Uncompiled Mode
    2. Format Compiled Code for Debugging
    3. Compile with --debug=true
    4. Use the Closure Inspector
  21. A. Inheritance Patterns in JavaScript
    1. Example of the Functional Pattern
    2. Example of the Pseudoclassical Pattern
    3. Drawbacks to the Functional Pattern
      1. Instances of Types Take Up More Memory
      2. Methods Cannot Be Inlined
      3. Superclass Methods Cannot Be Renamed (Or Will Be Renamed Incorrectly)
      4. Types Cannot Be Tested Using instanceof
      5. Encourages Adding Properties to Function.prototype and Object.prototype
      6. Makes It Impossible to Update All Instances of a Type
      7. Naming Newly Created Objects Is Awkward
      8. Results in an Extra Level of Indentation
    4. Potential Objections to the Pseudoclassical Pattern
      1. Won’t Horrible Things Happen if I Forget the New Operator?
      2. Didn’t Crockford Also Say I Wouldn’t Have Access to Super Methods?
      3. Won’t All of the Object’s Properties Be Public?
      4. Won’t Declaring SomeClass.prototype for Each Method and Field of SomeClass Waste Bytes?
      5. I Don’t Need Static Checks—My Tests Will Catch All of My Errors!
  22. B. Frequently Misunderstood JavaScript Concepts
    1. JavaScript Objects Are Associative Arrays Whose Keys Are Always Strings
    2. There Are Several Ways to Look Up a Value in an Object
    3. Single-Quoted Strings and Double-Quoted Strings Are Equivalent
    4. There Are Several Ways to Define an Object Literal
    5. The prototype Property Is Not the Prototype You Are Looking For
    6. The Syntax for Defining a Function Is Significant
    7. What this Refers to When a Function Is Called
    8. The var Keyword Is Significant
    9. Block Scope Is Meaningless
  23. C. plovr
    1. Getting Started with plovr
    2. Config Files
    3. Build Command
    4. Serve Command
      1. Displaying Compiler Errors
      2. Auditing Compiled Code Size
    5. Generating Externs from Exports
    6. Generating a Source Map
  24. Index
  25. About the Author
  26. Colophon
  27. SPECIAL OFFER: Upgrade this ebook with O’Reilly
  28. Copyright

Product information

  • Title: Closure: The Definitive Guide
  • Author(s): Michael Bolin
  • Release date: September 2010
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781449396954