YUI 3 Cookbook
Total Page:16
File Type:pdf, Size:1020Kb
YUI 3 Cookbook Evan Goer Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo YUI 3 Cookbook by Evan Goer Copyright © 2012 Yahoo! Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Editor: Mary Treseler Indexer: BIM Indexing Production Editor: Kristen Borg Cover Designer: Karen Montgomery Copyeditor: Rachel Monaghan Interior Designer: David Futato Proofreader: Kiel Van Horn Illustrator: Robert Romano May 2012: First Edition. Revision History for the First Edition: 2012-05-29 First release See http://oreilly.com/catalog/errata.csp?isbn=9781449304195 for release details. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. YUI 3 Cookbook, the image of a spotted cuscus, and related trade dress are trade- marks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein. ISBN: 978-1-449-30419-5 [LSI] 1337019481 Table of Contents Preface ..................................................................... ix 1. Loading Modules ....................................................... 1 1.1 Loading Rollups and Modules 4 1.2 Loading SimpleYUI 6 1.3 Identifying and Loading Individual Modules 8 1.4 Loading a Different Default Skin 10 1.5 Loading Gallery Modules 11 1.6 Loading a YUI 2 Widget 13 1.7 Loading Locally Hosted Builds 14 1.8 Creating Your Own Modules 17 1.9 Creating a Module with Dependencies 19 1.10 Creating Truly Reusable Modules 22 1.11 Defining Groups of Custom Modules 24 1.12 Reusing a YUI Configuration 27 1.13 Defining Your Own Rollups 30 1.14 Loading jQuery as a YUI Module 31 1.15 Loading Modules Based on Browser Capabilities 34 1.16 Monkeypatching YUI 38 1.17 Loading Modules on Demand 40 1.18 Enabling Predictive Module Loading on User Interaction 42 1.19 Binding a YUI Instance to an iframe 46 1.20 Implementing Static Loading 48 2. DOM Manipulation ..................................................... 51 2.1 Getting Element References 52 2.2 Manipulating CSS Classes 55 2.3 Getting and Setting DOM Properties 57 2.4 Changing an Element’s Inner Content 59 2.5 Working with Element Collections 60 2.6 Creating New Elements 62 iii 2.7 Adding Custom Methods to Nodes 64 2.8 Adding Custom Properties to Nodes 66 3. UI Effects and Interactions ............................................... 69 3.1 Hiding an Element 70 3.2 Fading an Element 71 3.3 Moving an Element 74 3.4 Creating a Series of Transitions 76 3.5 Defining Your Own Canned Transitions 77 3.6 Creating an Infinite Scroll Effect 80 3.7 Dragging an Element 81 3.8 Creating a Resizable Node 84 3.9 Implementing a Reorderable Drag-and-Drop Table 86 4. Events ............................................................... 91 4.1 Responding to Mouseovers, Clicks, and Other User Actions 93 4.2 Responding to Element and Page Lifecycle Events 95 4.3 Controlling Event Propagation and Bubbling 97 4.4 Preventing Default Behavior 99 4.5 Delegating Events 100 4.6 Firing and Capturing Custom Events 102 4.7 Driving Applications with Custom Events 104 4.8 Using Object Methods as Event Handlers 109 4.9 Detaching Event Subscriptions 112 4.10 Controlling the Order of Event Handler Execution 113 4.11 Creating Synthetic DOM Events 116 4.12 Responding to a Method Call with Another Method 118 5. Ajax ................................................................ 121 5.1 Fetching and Displaying XHR Data 122 5.2 Handling Errors During Data Transport 126 5.3 Loading Content Directly into a Node 129 5.4 Submitting Form Data with XHR 132 5.5 Uploading a File with XHR 134 5.6 Getting JSON Data Using Script Nodes (JSONP) 135 5.7 Fetching and Displaying Data with YQL 138 5.8 Scraping HTML with YQL 140 5.9 Querying Data Using DataSource 142 5.10 Normalizing DataSource Responses with a DataSchema 146 6. CSS ................................................................. 149 6.1 Normalizing Browser Style Inconsistencies 150 6.2 Rebuilding Uniform Base Styles 151 iv | Table of Contents 6.3 Applying Consistent Fonts 152 6.4 Laying Out Content with Grids 154 6.5 Using Grids for Responsive Design 157 6.6 Creating Consistent Buttons 159 7. Infrastructure ........................................................ 161 7.1 Managing State with Attributes 163 7.2 Creating Base Components with Y.extend() 167 7.3 Creating Base Components with Y.Base.create() 170 7.4 Creating a Basic Widget 173 7.5 Creating a Widget That Uses Progressive Enhancement 178 7.6 Rendering Remote Data with a Widget 182 7.7 Creating a Simple Plugin 185 7.8 Creating a Plugin That Alters Host Behavior 187 7.9 Bundling CSS with a Widget as a CSS Module 189 7.10 Bundling CSS with a Widget as a Skin 191 7.11 Representing Data with a Model 194 7.12 Persisting Model Data with a Sync Layer 196 7.13 Managing Models with a Syncing ModelList 201 7.14 Rendering HTML with a View 204 7.15 Rendering a Model with a View 207 7.16 Rendering a ModelList with a View 210 7.17 Saving State Changes in the URL 214 7.18 Defining and Executing Routes 217 8. Using Widgets ........................................................ 223 8.1 Instantiating, Rendering, and Configuring Widgets 225 8.2 Creating an Overlay 227 8.3 Aligning and Centering an Overlay 231 8.4 Making an Overlay Draggable 233 8.5 Creating a Simple, Styled Information Panel 234 8.6 Creating a Modal Dialog or Form 236 8.7 Creating a Tooltip from an Overlay 238 8.8 Creating a Lightbox from an Overlay 241 8.9 Creating a Slider 246 8.10 Creating a Tabview 249 8.11 Creating a Basic DataTable 252 8.12 Formatting a DataTable’s Appearance 253 8.13 Displaying a Remote JSON DataSource in a DataTable 256 8.14 Plotting Data in a Chart 257 8.15 Choosing Dates with a Calendar 259 8.16 Defining Calendar Rules 263 8.17 Creating a Basic AutoComplete 265 Table of Contents | v 8.18 Highlighting and Filtering AutoComplete Results 267 8.19 Using AutoComplete with Remote Data 272 8.20 Customizing the AutoComplete Result List 275 9. Utilities ............................................................. 279 9.1 Determining a Variable’s Type 280 9.2 Iterating Over Arrays and Objects 282 9.3 Filtering an Array 285 9.4 Merging Objects 286 9.5 Composing and Inheriting from Other Objects 287 9.6 Automatically Caching Function Call Results 290 9.7 Templating with Simple String Substitution 291 9.8 Formatting Numbers 293 9.9 Formatting Dates 294 9.10 Parsing Arbitrary XML 295 9.11 Converting Color Values 296 9.12 Managing History and the Back Button 297 9.13 Escaping User Input 301 9.14 Assigning Special Behavior to a Checkbox Group 302 9.15 Implementing Easy Keyboard Actions and Navigation 305 9.16 Reliably Detecting Input Field Changes 306 9.17 Managing and Validating Forms 307 10. Server-Side YUI ....................................................... 311 10.1 Installing and Running YUI on the Server 312 10.2 Loading Modules Synchronously on the Server 314 10.3 Using YUI on the Command Line 315 10.4 Calling YQL on the Server 318 10.5 Using the YUI REPL 319 10.6 Constructing and Serving a Page with YUI, YQL, and Handlebars 322 11. Universal Access ...................................................... 325 11.1 Preventing the Flash of Unstyled Content 326 11.2 Adding ARIA to Form Error Messages 329 11.3 Building a Widget with ARIA 331 11.4 Retrofitting a Widget with an ARIA Plugin 334 11.5 Defining Translated Strings 337 11.6 Internationalizing a Widget 339 12. Professional Tools ..................................................... 345 12.1 Enabling Debug Logging 347 12.2 Rendering Debug Log Output in the Page 350 12.3 Writing Unit Tests 354 vi | Table of Contents 12.4 Organizing Unit Tests into Suites 358 12.5 Testing Event Handlers by Simulating Events 361 12.6 Mocking Objects 364 12.7 Testing Asynchronously Using wait() 368 12.8 Collecting and Posting Test Results 372 12.9 Precommit Testing in Multiple Browsers 376 12.10 Testing on Mobile Devices 379 12.11 Testing Server-Side JavaScript 381 12.12 Minifying Your Code 383 12.13 Documenting Your Code 388 Index ..................................................................... 393 Table of Contents | vii CHAPTER 1 Loading Modules Consider the humble <script> element. Introduced in 1995, it is still the gateway for injecting JavaScript into the browser. Unfortunately, if you want to build sophisticated applications, <script> shows its age: • <script> conflates the concepts of loading code and executing code. Programmers need fine-grained control over both phases. • <script> is synchronous, blocking the browser’s flow/paint cycle until the entire script downloads. This is why performance guides currently recommend moving <script> to the bottom of the page. The good news is that HTML now provides the async and defer attributes, so this issue might improve over time. • <script> has a shared global context with no formal namespacing or security built in. This is bad enough when you’re simply trying to protect your own code from your own mistakes, but becomes disastrous when your code must run alongside an unknown number of third-party scripts.