Gardens 13 Rich Internet Applications Are Always Up-to-Date 17 Rich Internet Applications Are OS Killers 19 Rich Internet Applications Are Browser Centric 21 Rich Internet Applications A
Trang 2Professional Rich Internet Applications:
AJAX and Beyond
Dana Moore Raymond Budd Edward Benson
Trang 4Professional Rich Internet Applications:
AJAX and Beyond
Trang 6Professional Rich Internet Applications:
AJAX and Beyond
Dana Moore Raymond Budd Edward Benson
Trang 7Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2007 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-08280-5
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Library of Congress Cataloging-in-Publication Data is available from the publisher.
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by anymeans, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sec-tions 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Pub-lisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600 Requests to the Publisher for permis-sion should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis,
IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NOREPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OFTHE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDINGWITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE NO WARRANTYMAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS THE ADVICE ANDSTRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION THIS WORK ISSOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERINGLEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES IF PROFESSIONAL ASSISTANCE ISREQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT.NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HERE-FROM THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS ACITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THATTHE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION ORWEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE FURTHER, READERS SHOULD BEAWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAP-PEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ
For general information on our other products and services please contact our Customer Care Departmentwithin the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002
Trademarks:Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related tradedress are trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates, in the UnitedStates and other countries, and may not be used without written permission All other trademarks are theproperty of their respective owners Wiley Publishing, Inc., is not associated with any product or vendormentioned in this book
Wiley also publishes its books in a variety of electronic formats Some content that appears in print may not
be available in electronic books
Trang 8About the Authors
Dana Moore is a division scientist with BBN Technologies and is an acknowledged expert in the fields
of peer-to-peer and collaborative computing, software agent frameworks, and assistive environments.Prior to joining BBN, Dana was chief scientist for Roku Technologies, and a Distinguished Member ofTechnical Staff at Bell Laboratories Dana is a popular conference speaker, a university lecturer, and has
published both articles for numerous computing publications, and books, including Peer-to-Peer: Building Secure, Scalable, and Manageable Networks and Jabber Developer Handbook Dana holds a master of science
degree in technology management from the University of Maryland, and a bachelor of science in trial design, also from the University of Maryland
indus-Raymond Budd is a software engineer with BBN Technologies He has designed, developed, and ported a variety of Web applications and other distributed systems in Java, Ruby, and Python He hasbeen published in several conference proceedings, such as the Eighteenth National Conference on
sup-Artificial Intelligence, and journals, including Applied Intelligence Additional areas of interest include
knowledge representations, knowledge engineering, and distributed planning and scheduling
He received a bachelor of science degree in computer science from the University of Pittsburgh
Edward (Ted) Benson is a software engineer with BBN Technologies His experience and interestsinclude distributed programming frameworks, multi-agent systems, Web development, and knowledgerepresentation Ted has developed Web applications for several community groups and companies, and
he has been published in IEEE conference proceedings on the subjects of distributed and multi-agent
systems He gradated summa cum laude from the University of Virginia with a bachelor of science degree
in computer science
Trang 10Quality Control Technicians
John GreenoughJessica KramerBrian H Walls
Project Coordinator
Adrienne Martinez
Media Development Project Supervisor
Laura Carpenter Van Winkle
Media Development Specialists
Angie PennyKit MaloneKate JenkinsSteve Kudirka
Proofreading and Indexing
Aptara
Anniversary Logo Design
Richard Pacifico
Trang 12The authors gratefully acknowledge the contributions of our friend and colleague William Wright,whom we cajoled into acting as the technical editor and all-around technical conscience of this book.Our warmest gratitude also to Maureen Spears, our English editor at Wiley, who put up with our terriblegeek humor during conference calls and worked tirelessly to bring the quality of this book up to whatyou see before you
We also appreciate the Web 2.0 luminaries who agreed to share their expertise and candid opinions with
us, and our readers for the interviews scattered throughout the book These include Dojo Toolkit’sAlex Russell, Ruby on Rails’ David Heinemeier Hansson, 37Signals’ Jason Fried, and Second Life’sWagner James Au We thank our BBN colleagues John Hebeler, for his entertaining sidebar comments,and Jonathan Nilsson, for his helpful comments
Finally, and most important, we thank our friends, families, and significant others for their forbearance.Writing is a solitary activity that tends to exclude others, even those most important to us; and we appre-ciate all their support, and promise somehow to make up for the lost time and opportunities
Trang 13her eyes,” and for Caitlin, who, like the spring breeze, breathes new life to the suffocated hills, and comes as the herald of each new dawn’s
possibilities.
—DM
For Leah, with love I am inspired by your intelligence, strength, and beauty, and am immensely grateful for the support and understanding you gave me as I wrote this Also for my parents with appreciation for everything you’ve taught me throughout my life.
—RB
For Grace, her warm eyes, gentle wisdom, and wonderful laugh
And for my four parents, who taught me all the important things I know in
life.
—EB
Trang 14Rich Internet Applications are “Plastic” 4
Rich Internet Applications: The Web Is Disruptive (Finally) 8 Rich Internet Applications Are Invisible 9
Rich Internet Applications Break Down Walled Gardens 12 Rich Internet Applications Create New (Unwalled?) Gardens 13
Rich Internet Applications Are Always Up-to-Date 17 Rich Internet Applications Are OS Killers 19
Rich Internet Applications Are Browser Centric 21 Rich Internet Applications Are Network Centric 21 Rich Internet Applications Are Mind-Altering 23
Rich Internet Applications Are Software as Service 24 Rich Internet Applications Are User Centered 25 Rich Internet Applications Are Inherently Collaborative 25 Rich Internet Applications: Small and Agile Development 26 Rich Internet Applications Are Bound to Change 26 How Do I Change the Way I Develop Applications? 27 How Am I Going to Make Money from RIAs? 28 Rich Internet Applications Are Seductive 29
Trang 15Chapter 2: RIA Foundations 35
XML: The Lingua Franca of the Internet 36
XHTML: A Language for Documents 42
CSS: A Language for Style 48
JavaScript: A Language for Action 54
A Concluding Example — Angela’s Ristorante 62
What’s a Proxy and Why Do I Need One? 92
The Yahoo and Google Traffic Mashup 97
Trang 16Contents
Two Scenarios: If Restaurants Were Run Like Web Apps 117
AJAX versus the Traditional Approach 120
Advantages of Using AJAX over the Traditional Approach 125
Development Environment Setup 126 Your First RIA: Hello World 126
Trang 17Logging 156
The Model-View-Controller 164
Web Application Frameworks 176
JavaScript Library Basics 186
JavaScript Libraries in Detail 191
Enter the First Contenders 206 The Google Web Toolkit (GWT) 206
Trang 18ideaStax Concept of Operation 222
Getting Started: the Essential Elements 230
ideaStax: the Implementation Detail 234
Implementing the Controllers 239
Using the Ruby JavaScript Construct as a Partial Renderer 240
Incorporating Form Validation into Your System 250
Asynchronous Server-Side Validation of a Single Form Element 251
Capturing User Information 252
Validation in Practice: Client-Side Validation with Dojo 258
Trang 19Using Client-Side Validation Functions 259
Validation in Practice: Server-Side Validation of the Completed Form 272
Enhancing the Helper by Adding Validation of the Other Form Fields 284
Validation in Practice: Server-Side Validation of the Username 288
Approaches to the Usable Form 296
Form Usability in Practice: Populating a Field with Server Data 298
Form Usability in Practice: Using a Server Backed Combo Box 309
Introducing Prototype and script.aculo.us 326
Understanding Prototype and script.aculo.us Capabilities 326
DOM Elements in the Physical World 327
Trang 20Contents
A Client-Only ideaStax Editor 336
Creating Slides Dynamically with script.aculo.us’ Builder 336
A Server-Backed ideaStax Editor 347
Effects Introduction: Hide and Seek 368 The script.aculo.us Effect Class 369
Modal Windows and the ideaStax Previewer 377
Understanding the Tagging Problem 390
Trang 21Setting Up the Data Model 403
Populating the Pictures Data Base 408
Choosing How to Expose Your Service 454
Trang 22Contents
Getting Started: the Essential Elements 468
Defining Your First Widget: a Hello World Exercise 472
A More Useful Example: Incorporating the Stax API 482
Looking Back in Rich Immersion: The World of Magic Cap 498
Getting Started: The Essential Second Life Elements 510
Basic Dojo Validation Functions and Flags 525 Dojo Internet Validation Functions and Flags 529 Locale-Specific Validation Functions in Dojo 531
Trang 24And now for something completely different.
—Monty Python Tagline
This introduction orients you to the rest of the book and takes you for a brief tour of its primary subject,Rich Internet Application (RIA) architecture and how it evolved In looking at how we could best serveour readers, we tried to create a blend of three elements to accomplish the following:
❑ Give you a sense of how RIAs are different from the previous generation of Web applicationsand how this difference is important to you, whether you are a corporate or independent soft-ware developer
❑ Present significant supporting code examples, rich enough to be complete and nontrivial, butsimple enough to present in a page or two of code
❑ Describe and demonstrate important frameworks and APIs
Who Is This Book For?
The authors make no assumptions about the background of the book’s readers other than that you areworking software developers interested in practical solutions to real-world problems This book explainshow to use enabling technologies to create new kinds of distributed systems with features rivaling desk-top systems Whether your skills are in Web development, server architectures, or agile languages, youshould find value in this book
Given the fact that the examples are written in Python, Java, and Ruby on Rails, it is best if you havesome familiarity with one of these languages We do assume you have some experience developing anddeploying Web applications, and can read basic UML diagrams Finally, you should be familiar withbasic database management operations, although any required database administration steps are clearlyoutlined in each chapter
What Is This Book’s Focus?
Because the authors are professional corporate software developers, we know that the quickest road tounderstanding code and APIs is to review working code examples, but often books consist of a stream ofdidactic examples Although this approach may reveal important points of a topic, it ultimately leaves
Trang 25you unfulfilled because the simple examples don’t build anything compelling outside of the context ofthe point the author is trying to make Thus, this book focuses on an interesting and feature-completeapplication that functions as a recurring theme holding the book together and helps you to gain a grow-ing sense of mastery over RIA design, frameworks, and implementation
Accordingly, you have the opportunity to build a capstone application, which we call ideaStax IdeaStax is
an idea capture tool that enables users, either singly or in community, to record, tag, search, organize, andpresent ideas Ideas are the atomic units of ideaCards, and ideaCards are the building blocks of ideaStax.IdeaStax serves multiple other purposes too For one thing, it serves to illustrate the notion of how appli-cations might change in capability and character if they were built from the ground up to reflect RIA con-cepts and capabilities In a sense, you might think of ideaStax as a re-envisioning of what a desktopapplication such as Microsoft’s PowerPoint might be like if it had been designed to conform to the con-cepts of RIAs in the twenty-first century, instead of the rich client platform (RCP) of the twentieth
In addition to getting the code for ideaStax from the Wrox publishing site (www.wrox.com), the authorsare developing a site (ideaStax.com) where you can also contribute ideas and code, show off yourskills, and participate in evolving the application and its capabilities in the best tradition of open-sourcesoftware If your contributions are worthwhile, you can become a committer to the project
The Book’s Topical Approach
For several decades now, developers have believed certain things to be objectively true, perhaps evenindisputable We consider ourselves members of a specific development and deployment “tribe.” Ratherthan consider yourself a developer, you may consider yourself to be a “Java developer,” or “Microsoft.Net developers,” with the limitations and technology constraints implied by membership in the tribe
In the case of Java, this means “one language, many platforms,” and in the case of Microsoft Windows 32APIs, it means “a few languages, one platform.” In any event, writing for a rich client platform tradition-ally means having developers make compromises, having end users manage installation and updates,and having the involvement of corporate IT departments The economics and mechanics of selling andbuying licensed software have created a heavy burden for everyone involved in the process
It’s hardly possible to have been a software developer for any length of time and not have written codeusing a rich client API for Windows, MAC OS/X, or Linux Thus, we’re all familiar with the rich clientplatform (RCP) model Almost every application we’ve written, used, managed, or deployed over thelast three decades on microcomputers adheres to RCP capabilities and limitations When you think like
an RCP developer, you may take for granted that the operating system, data access and storage, and theuser’s experience of the application are tightly bound This accounts for the responsiveness of certaintypes of applications — word processors, for example
Now this status quo is changing, and changing rapidly By the end of 2005, a good deal of “buzz” wasemerging over something called AJAX (asynchronous JavaScript and XML) AJAX, while simply anumbrella term for assembling applications by using several mature technologies already in common use,nevertheless seemed to evoke something more than the sum of its constituent parts There’s now grow-ing recognition that a tectonic shift promises to change the very foundations of how we develop anddeploy applications The Web is undergoing a profound transformation from a collection of news arti-cles, static forms, and bulletin boards to a location-agnostic computing platform in and of itself
Trang 26Introduction
Together, we will explore the elements of this change in browser-based applications — from greaterdynamism and responsiveness to faster development cycles to greater embrace of social networking.The phrase “programming above the platform level” has come to be closely associated with Rich InternetApplications We didn’t invent the phrase, but we will illustrate, in many working examples in multipleprogramming languages, the importance of this concept to Web 2.0 applications and even beyond.Our objective is to prepare both the corporate and independent developer to take advantage of this newemerging landscape As the world of shrink-wrapped boxes of client-side software begins to wane, anew ecology of Rich Internet Applications is emerging to bring both developers and end users new ben-efits that take full advantage of today’s connected world Developers who take advantage of this newecology will prosper and stay at the front of their professional ranks
Learning the technical approaches from this book, and understanding how and why Rich InternetApplications are different, will teach you to look at the world from a completely different point of view.For one thing, you will discover that most of the “action” of your applications actually takes place not onthe user’s desktop but on a server that may exist anywhere, and that what users see and experiencethrough their browser is far more simplistic — mediated by the constraints of the browser
RCP applications have a richness and responsiveness that has been generally impossible on the Web.Traditionally, the simplicity that enabled easy deployment to the Web has also brought with it a gapbetween the experiences you can provide and the experiences users can get from a desktop application.Now, for perhaps the first time since the inception of the Web, that gap may be closing Emerging is anew generation of applications in which the line between rich client and rich Internet applications isblurring; and perhaps in the not too distant future it will disappear altogether
Consider Google Suggest Watch the way the suggested terms update as you type, almost instantly Nowlook at Google Maps Zoom in Use your cursor to grab the map and scroll around a bit Again, every-thing happens almost instantly, with no waiting for pages to reload Google Suggest and Google Maps
are two examples of a new approach to Web applications that use AJAX effectively, and each in its way
represents a fundamental shift in what’s possible on the Web
Consider the various models for creating new applications or redesigning existing ones:
❑ Desktop model— In this model, the rich client platform (RCP) tool still “owns” your ability tomanipulate the data model (i.e., the Word doc, the Excel spreadsheet, etc.) The desktop paradigmcreates a “walled garden” by tightly integrating the operating system, the data format, and filesystem organization, which tends to constrain the user
❑ Web 1.0 or “old school” Web applications— In this model, the user fills out a form, clicks andsubmits, and then waits nervously for a response, hoping that application integrity will not bebroken Developers have dealt with this level of Internet application brokenness for many yearsnow by various improvisational means, including cookies for session robustness and hiddenfields in form-based applications to orchestrate multi-step transaction-oriented applications
❑ RIA (Rich Internet Application) model— In this new model, users walk up to a handy device,start a browser, and access their assets and applications It doesn’t matter what kind of machineit’s on or what kind of browser they use — any modern browser will do In the RIA model, usersneedn’t lug anything from home to work to home again in order to be functional or productive.Often, the data assets the user creates are stored in an industry-standard format (HTML, XML).Users can leave them on the server in the Net, or make a local copy (to a host computer’s harddisk or to a flash drive, for example)
Trang 27What’s key in the new generation of RIAs is the degree to which partial page replacement involves
the server side of the application in maintaining application state and robustness We will makethe point more than once that the key to the liveliness of RIAs is this idea of partial page replace-ment When the user doesn’t have to wait for a server to serve up the entire page after every userinteraction, a browser-based application can hardly help being perceived as delivering a betteruser experience Not coincidentally, the developer experience becomes better as well, involvingfar less ad hoc code
Consider, therefore, the direct consequences of creating new applications using RIAs, for yourself as adeveloper, for your users, and for your potential to leverage the climate for innovation The RIA modeldirectly and immediately threatens the hegemony over the user of such players as Microsoft Currently,whoever owns the OS and the RCP tools controls the user The more users who buy into a given platformand toolset (MS Windows and MS Office, for example), the higher the level of control over users There is a
so-called network effect that creates a value to a potential customer dependent on the number of customers
already owning that tool The RIA model creates a network effect as well, so a viral adoption menaces thestatus quo and creates new opportunity for you as a developer, writing for yourself or for the enterprise
Framewor ks and JavaScript Libraries
A number of incredible frameworks and JavaScript have emerged in the past few years, and we cover anumber of these The general philosophy behind current frameworks is that given current connectionspeeds, page composition and partial page replacement by the server becomes the norm, rather than theexception The wide proliferation of broadband (over 70 million broadband connected computers in theU.S alone) has opened up server interaction to a degree not possible before
Thus, even though the XmlHttpRequest and response (about which we will be saying much more) hasbeen available in modern browsers for several years, only recently have we seen applications such asGoogle Map pioneering its use, and making partial page replacement the rule rather than the exception.Consequently, we have seen a commensurate rise in simple Java, Python, and Ruby servers, and adecrease in complex and formal multi-tiered schemes such as WSDL This book covers a few serverframeworks, including Google Widget Toolkit (Java), TurboGears (Python), and Ruby on Rails (Ruby)
On the client side, dramatic changes are taking place as well JavaScript has always been considered apainful fact of life for developers A quirky language, never a developer favorite, and lacking a strongunifying open-source library layer, it now has a number of libraries, from MochiKit, whose mantra isthat it “makes JavaScript suck less,” to Prototype, the library of choice underlying so many Rails applica-tions You will examine both of these libraries
The Hybrids and the Exotics
In addition to strictly browser-based RIAs, we also cover two other incarnations of networks-centricapplications, the first exemplified by DashboardWidgets on Mac OS/X and Google Desktop Widgets onWindows, and Yahoo Widgets on both platforms Widgets are rather like applications, each hosted in itsown mini-browser environment While such applications often have the same characteristics of nativedesktop applications, they are arguably easier to design and construct, built of HTML, stylesheets, andJavaScript (elements familiar to Web developers) We chose to cover Yahoo Widgets, owing to its pres-
Trang 28Introduction
A second, and even more groundbreaking network-centric, application paradigm is that of immersive3D environments, exemplified in applications such as Second Life Numerous past attempts have beenmade to create immersive environments, but they have all failed for various reasons — network andbandwidth issues or awkward user experiences, but now, perhaps for the first time, immersive environ-ments are suddenly not only possible but also vibrant Second Life gives developers a simple, yet com-plete scripting language and object building environment We will cover this emerging phenomenon,and show you usable code for both “in-world” and network-connected objects
What This Book Covers
This book explores a number of frameworks, in-browser APIs, and server code examples It also presents
a variety of implementation languages and illustrates implementations in code To present the capstone,
we had to choose whether to compose it from disparate frameworks and languages or choose a singleimplementation framework and (by extension) a single language and design for the application Aftermuch experimentation and discussion, we decided to implement ideaStax in a specific framework, Ruby
on Rails (usually referred to simply as “Rails”), primarily for its code compactness, its comprehensive set
of capabilities, and its ability to produce something both useful and reasonably easy for you to stand, even if you have no Rails (or even Ruby) experience
under-This is not to say that the other implementation frameworks we highlight in the book (e.g., TurboGears
or the Google Widget Toolkit — GWT) are in any way inferior to Rails, because they certainly are not;and in fact if you prefer to work in another language (Python for TurboGears, or Java for GWT), thenthese are preferable options We simply had to make a choice, and given the pace of advancement by theRails community, it seemed to be a reasonable choice, but by no means the only one
Although we chose to work in Rails for the capstone application, we didn’t want to play favorites withlanguages or frameworks — after all, this book is about RIA, not Rails We decided on a compromise wehope you will like: We use other languages to demonstrate code for key concepts such as mashups,client-side validation, and auto-completion; and social site concepts such as tagging There should beplenty to hold your interest regardless of your language preference
Many developer books have to decide between greater breadth of coverage versus greater depth.Because of the explosive growth of tools and libraries, we opted for breadth Thus, we cover a significantamount of the RIA and Web 2.0 landscape, and accordingly we won’t exhaustively cover any particularframework We have, however, extracted the important concepts from each Because the details of someframeworks are documented online (although there’s a wide variance in the quality of online documen-tation), we have striven to give you the developer point of view, or the “inside scoop,” for each of theframeworks
Part I: An Introduction to RIAs
In this part, you’re provided with the background you need to develop Rich Internet Applications Youlearn what distinguishes Rich Internet Applications and how they work, you get a refresher on Webapplication concepts, and you get your feet wet by implementing a simple Hello World example RIA.Finally, you learn some tips for enhancing your productivity through an exploration of some commonapproaches and tools for JavaScript debugging
Trang 29❑ Chapter 1 explores several traits of Rich Internet Applications, and investigates what makes trueRIAs so different from traditional Web applications It explores the differences in developmentprocess, marketing, and philosophy used when developing traditional verses Rich InternetApplications.
❑ Chapter 2 provides you with the foundations in Web technologies that you’ll need for theremainder of the book It includes a refresher of the Extensible Markup Language (XML) andthe document object model (DOM) Extensible Hypertext Markup Language (XHTML),
Cascading Style Sheets (CSS), and JavaScript are reviewed next Finally, all the reviewed nologies are brought together in a simple example
tech-❑ In Chapter 3, the mashup phenomenon common in RIAs is explored in detail This chaptershows you what a mashup really is, and walks you through the steps necessary to write yourown mashup It also provides you with a detailed look at the XMLHttpObject and JavaScriptObject Notation (JSON)
❑ Chapter 4 details RIA development with a Hello World example In this chapter, the differencesbetween AJAX applications and traditional Web applications are first explored in detail Thenthe steps required to write a simple Hello World Web application are outlined You also learnthe steps necessary to make and respond to an asynchronous call in both Java and PHP Finally,you learn how to implement and respond to an asynchronous request in a simple example inboth Java and PHP
❑ Issues related to debugging Web applications are explored in Chapter 5 This chapter provides adetailed survey of the language-independent debugging tools, and approaches available to theRIA developer It looks at Firefox as a key test browser, and describes some of the commondebugging plug-ins available for the tool It also shows how to use a variety of debugging tools,including Venkman and FireBug Finally, it examines the utility of logging, and outlines thesteps necessary to develop a simple JavaScript logging tool
Part II: RIAs Explored
Part II expands upon the technologies introduced in Part I and explains some of the higher-level themesand development packages that build on top of them
❑ Chapter 6 discusses the Model-View-Controller (MVC) paradigm of design, possibly the mostimportant concept to learn for developers of any platform The MVC pattern represents a way
to architect and organize modules of code so that concerns are separated between the domaininformation and business logic (Model), visualization of output to the user (View), and manage-ment of user input (Controller) This type of architecture is particularly important to RIA devel-opers because the underlying client-server architecture upon which the Web is built makes RIAs
a near-perfect medium for MVC design Chapter 6 introduces the three server-side developmentpackages highlighted by this book: Java, Ruby on Rails, and TurboGears Each of these frame-works is explained in the common parlance of MVC terminology
❑ Chapter 7 pits various JavaScript frameworks against each other so that you get a chance tolearn which tool is right for which job In traditional Web development, most of the program-ming work is done on the server, and the client-side tasks are primarily design-oriented RIAprogramming can require just as much attention to client-side logic as the server side does, sochoosing the right JavaScript library is an important task This bake-off helps you learn whereeach framework excels and where each falls short
Trang 30Introduction
❑ Chapter 8 enters the relatively new arena of compiled-to-JavaScript frameworks and outlinesthe two different approaches to this technique taken by Google and the Ruby on Rails team.These solutions replace JavaScript programming with higher-level languages that are easier tocode, maintain, and debug At some point before RIA pages are sent to the client, the higher-level code is machine-translated into JavaScript
❑ Chapter 9 presents this book’s capstone application, ideaStax IdeaStax is a simple Web tion that enables users to create and maintain stacks of note cards containing rich text andimages As the chapters of Part III explain various RIA interface techniques, ideaStax is used toframe the examples in a simple and consistent context Chapter 9 outlines the goals and capabil-ities of the Stax concept, of which many are implemented in Part III
applica-When you have finished with this part, you will have a thorough understanding of the underlyingdesign principles behind professional RIA development, and a solid knowledge of the various tools andframeworks that are available to accomplish your design goals
Part III: RIA Development in Depth
In this part, you’re provided with the tools necessary to develop RIAs in the real world In this part, youexplore common issues in Web applications, and how they can be solved or minimized when develop-ing a RIA You’ll also see some new capabilities, such as drag and drop, and autocompletion of formfields with server data that are increasingly used in real-world RIAs Throughout this part, you’ll gainfamiliarity with several powerful JavaScript libraries, such as Dojo, script.aculo.us, and MochiKit.These chapters contain a variety of examples that show you how to develop RIAs in three different lan-guages: Java, Ruby, and Python Regardless of your preferred language, you can always follow alongwith the intent of the example by noting whether the objects or functions appear in the model, view, orcontroller Even if you’re quite familiar with the example language, you may want to explore the capa-bilities of the other candidate languages You can do this with a little work, by porting the example tothe other language, if you pay attention to which objects are in the model, view, or controller Afteryou’ve finished, go to the book’s Web site at www.wrox.com, which contains the examples implemented
in each of the three reference languages Recall from Chapter 6 the three alternative implementationsand how they incorporate the MVC
All of the chapters define capabilities that are incorporated into the capstone Stax application You cansee the full code for the capstone, and a working version, on the book’s Web site Also see Chapter 9 for
an introduction to the application
❑ Chapter 10 explores issues associated with form field validation in a Web application The ter explores the problem of form input data, and common approaches used to validate data
chap-It includes client-side validation with the Dojo JavaScript library, server-side validation in Java,and server-side validation of a single field in Java with AJAX
❑ Chapter 11 builds on the previous chapter, examining other issues in form usability It includes
an exploration of AJAX-based approaches to enhance a user’s form interactions It then builds
on the example from Chapter 10 to incorporate several AJAX-based enhancements
❑ Chapter 12 shows how to greatly increase RIA interactivity by adding drag and drop ties This chapter defines the concept of drag and drop, and briefly explores how it works usingthe script.aculo.us library It shows how to develop a RIA that has drag and drop capabilitieswith script.aculo.us and Ruby on Rails
Trang 31capabili-❑ Chapter 13 examines some of the ways in which subtle JavaScript effects can improve theusability of a RIA It introduces the script.aculo.us Effects library and demonstrates severalways to bind these effects to events and actions on a RIAPage Code examples are provided forseveral scenarios in which special effects are useful, including dynamic user notifications andfull-screen previews
❑ Chapter 14 looks at the concepts of tagging and rating in detail It explains what tagging andrating are and shows why the capabilities are being incorporated in many new RIAs and otherWeb applications, and why they are gaining more and more popularity It includes an examplewritten in Python
❑ Chapter 15 builds on the example introduced in Chapter 14, and explores implementing taggingand searching as one aspect of a larger RIA This chapter shows you how to add tagging andsearching to a more complex application through adding the capability to Stax, the capstoneapplication The Python implementation in Chapter 14 is replaced with an implementation inRuby on Rails
Part IV: Beyond the Web
Part IV examines the spread of Rich Internet Applications outside of the traditional Web browser As RIAdevelopment becomes a more professional and capable process, their reach is slowly extending to allareas of computing, from operating systems to applications to games Through the use of APIs, manyRIAs now have tie-ins to desktop applications so that users can benefit from the best of both worlds.Online applications such as Yahoo’s Flickr, for example, integrate seamlessly into Apple’s iPhoto, enablingusers to manage their photo albums locally but share their favorites with the world The chapters in thispart discuss how these combinations are possible and show examples of how they are being used today
❑ Chapter 16 takes a brief look at the importance of the Application Programming Interface (API).Successful RIAs don’t just present users with a polished Web interface; they also present devel-opers with a capable programmatic interface Access to an API is what makes mashups anddesktop RIA extensions possible This chapter explains how to develop, deploy, and controlthird-party access to your RIA
❑ In Chapter 17, you are introduced to the concept of desktop widgets Widgets are small applicationsthat float on a user’s desktop and provide access to a specific piece of information or functionality.This chapter demonstrates how Yahoo! Widgets are used to provide quick access to frequentlyneeded RIA functions that are exposed through an API The availability of such widgets allowsfor tie-ins to a user’s desktop and relieves the user of the need to open a Web browser and log in
to accomplish simple tasks
❑ Chapter 18 explores the early stages of the migration out of the confines of the browser and into
immersive virtual worlds, in the spirit of Neal Stephenson’s novel Snow Crash Immersive
appli-cations are socially rich environments populated and created by end users around the world.Chapter 18 takes you into a world called Second Life, presenting the technical approach andexamples of how to allow this world to interact with the Web at large Second Life presents itsusers (“residents”) with a full-featured programming language to manipulate the world aroundthem, and it is gaining support to access external services and display Web documents fromwithin its 3D immersive environment Real economies are springing up in this virtual space,and traditional companies are beginning to take note Connecting one’s RIA to virtual worldssuch as Second Life puts your product in a cutting-edge environment that will one day be
Trang 32Introduction
Part V: Appendix
The Appendix extends the discussion in Chapter 10 by discussing Dojo validation functions and flags
What You Need to Run the Examples
Many books focus on a single technology or single language It’s easy to define, right up front, theneeded support software or environment This book covers a wide range of browser-side JavaScriptlibraries, multiple dynamic page generation frameworks, and multiple server-side implementation lan-guages Each chapter outlines its specific support and environmental requirements; just look for theheading “Getting Started.” This will enumerate the support elements for the specific chapter Theauthors’ site, RIABook.ideastax.com, will also maintain links to the latest versions of supporting soft-ware and provide additional comments from the authors and other readers on supporting code Ofcourse, the code will be maintained on both the publisher’s site (www.wrox.com) and the
In code examples we highlight new and important code with a gray background
The gray highlighting is not used for code that’s less important in the presentcontext, or has been shown before
Note that most long blocks of code include listing numbers (for example, Listing 5-1) These listings tain code that have numbered lines so that the authors can more easily refer to specific lines during thediscussions that generally follow the code block
Trang 33Sometimes you will see a mixture of styles For example, when certain sections of changed code arebeing discussed, they’re presented in bold, as shown in Listing 18-1.
Listing 18-1: Default LSL script
Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.
As for styles in the text:
❑ We highlight new terms and important words when we introduce them.
❑ We show filenames, URLs, and code within the text like so: index.html
Source Code
As you work through the examples in this book, you may choose either to type in all the code manually
or to use the source code files that accompany the book All of the source code used in this book is able for download at www.wrox.com Once at the site, simply locate the book’s title (either by using theSearch box or by using one of the title lists) and click the Download Code link on the book’s detail page
avail-to obtain all the source code for the book
Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-0-470-08280-5.
Once you download the code, just decompress it with your favorite compression tool Alternately, youcan go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspxtosee the code available for this book and all other Wrox books
Boxes like this one hold important, not-to-be forgotten information that is directly
relevant to the surrounding text.
Trang 34per-To find the errata page for this book, go to www.wrox.comand locate the title using the Search box orone of the title lists Then, on the book details page, click the Book Errata link On this page you can viewall errata that has been submitted for this book and posted by Wrox editors A complete book list, includ-ing links to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml.
If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtmland complete the form there to send us the error you have found We’ll check the informationand, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions
of the book
p2p.wrox.com
For author and peer discussion, join the P2P forums at p2p.wrox.com The forums are a Web-based tem for you to post messages relating to Wrox books and related technologies and interact with otherreaders and technology users The forums offer a subscription feature to e-mail you topics of interest ofyour choosing when new posts are made to the forums Wrox authors, editors, other industry experts,and your fellow readers are present on these forums
sys-At p2p.wrox.comyou will find a number of different forums that will help you not only as you readthis book, but also as you develop your own applications To join the forums, just follow these steps:
1. Go to p2p.wrox.comand click the Register link
2. Read the terms of use and click Agree
3. Complete the required information to join as well as any optional information you wish to vide and click Submit
pro-4. You will receive an e-mail with information describing how to verify your account and plete the joining process
com-You can read messages in the forums without joining P2P but in order to post your own messages, you must join.
Once you join, you can post new messages and respond to messages other users post You can read sages at any time on the Web If you would like to have new messages from a particular forum e-mailed
mes-to you, click the Subscribe mes-to this Forum icon by the forum name in the forum listing
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to tions about how the forum software works as well as many common questions specific to P2P and Wroxbooks To read the FAQs, click the FAQ link on any P2P page
Trang 35ques-In Our Opinion
This is an “opinionated book.” The authors are all professional software developers who benefit dailyfrom using agile languages and open-source frameworks We think it’s important to point out that ourexamples, our discussions, and our applications use (almost exclusively) frameworks, toolkits, and lan-guages that are open source and available to all developers This affords you, the reader, access to capa-bilities and tools that are within the means of even the smallest enterprise or individual
One of the features of the book is the inclusion of interviews with opinionated figures in the RIA munity In our interview with David Heinemeier Hanson of 37Signals and innovator of Ruby on Rails,you’ll learn why “small is better” in terms of both team structure and application functionality In ourinterview with Alex Russell, innovator of Dojo Toolkit, you’ll get an inside view of one of the most suc-cessful and comprehensive JavaScript libraries In our final chapter, we present a conversation withSecond Life’s Official “Embedded Reporter,” Wagner James Au
com-An Invitation
We hope that after reading this introduction you cannot wait to begin digging into the rest of the book
At this point, we hope that you understand this book is dedicated to providing you with insightfulexamples and a good fundamental understanding of the available APIs You should expect a lot ofexploration of the important features of Rich Internet Applications Finally, you will gain expertise andconfidence from usable sample source code that functions as both interesting application and instructiveexample
We hope — and endeavor — to exceed your expectations Let us know if we succeeded
— Dana Moore (dana.virtual@gmail.com)
— Raymond Budd (ray.budd@gmail.com)
— Edward Benson (edward.benson@gmail.com)
Trang 36Part I
An Introduction to RIAs
Chapter 1: What Characterizes Rich Internet Applications?
Chapter 2: RIA Foundations
Chapter 3: The Programmable Web: The Mashup EcoSystem
Chapter 4: Getting Started: Creating Your First RIA
Trang 38What Characterizes Rich Internet Applications?
“Let me just say just one word to you, young man — plastics!”
— Older male character giving investment advice to Dustin Hoffman’s
character, Benjamin Braddock, in the 1964 film The Graduate
First things first This is a book for software developers by software developers As developers, weare inclined to jump to the technical detail immediately When we learn a new language, for exam-ple, we probably want to understand concepts such as typing, declaration, variable assignment,containment, and control flow structures: iteration, test and branching, modularization, and so on.This chapter is going to be a little different, but no less valuable
This chapter lays a foundation for why learning the RIA design approach is important In thatsense, this chapter is going to be more “philosophical” than any other chapters in this book It hasonly a couple code examples, primarily explaining the software revolution under way, and help-ing you understand the nature of the revolution The rest of the book discusses code and coding;here you discover what’s different and how you can profit from it The discussion tilts towardindependent software writers, by explaining how the competitive landscape is changing; butdevelopers within the enterprise will benefit from understanding how to make their companymore competitive externally, by building more scalable and user-centric public user experiences;and more effective internally, by building better collaboration and coordination tools
In that spirit, read on to find out what makes RIAs (Rich Internet Applications) something worthpaying attention to
Trang 39Rich Internet Applications are “Plastic”
The reference to plastics from The Graduate at the beginning of the chapter suggests the most famous
meaning of the word “plastic,” a commodity material which is often used as a substitute for the real(usually more expensive) material In the film, plastics were being touted to the character as a goodinvestment for the future When we, as developers, look back at the formative days of this period, thenext incarnation of the Internet, we may think “plastic” as well — in the dictionary meaning of the word:
“transforming; growing; changing; dynamic, developing.”
Thus, a first characteristic of RIAs is plasticity The new generation of Internet-platformed applications is
extensible and able to be recomposed into many different “look and feel” models, sometimes with theswipe of a cascading style sheet (CSS) paintbrush Web applications, and Web pages before them, havealways been “skinnable,” and a simple demonstration of applying a cascading style sheet (CSS) in anHTML page shows how plastic (dynamic) an ordinary Web page can become If you are well versed inWeb page plasticity, feel free to skip this section; otherwise, read on
An Example of Plastic (Dynamic) Web Pages
First, a Web page with no formatting: boring and mundane Figure 1-1 shows a Web page with noapplied styles The information is there, but the page is static and lifeless
Figure 1-1
Trang 40The following code creates the trivial Web page shown in Figure 1-1 The few DOM (document objectmodel) elements are placed by default — a couple paragraphs identified by the <p>and </p>tag pairsand a JPEG image declared in the <img/>tag: