Tải bản đầy đủ (.pdf) (527 trang)

Addison wesley flash and XML a developers guide nov 2001 ISBN 0201729202

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.77 MB, 527 trang )





TableofContents

FlashandXML:ADeveloper'sGuide
By
DovJacobson,JesseJacobson

Publisher

:AddisonWesley

PubDate

:November20,2001

ISBN

:0-201-72920-2

Pages

:368

"Thisbookisanexceptionaltrainingmanualtobringawebdeveloperor
flashdesignerwithscriptingskillsintoanentirelynewworldofcoding."ChristopherIanSmith,XMLDeveloper,RespondTV.com
"Thisisa'must-read'foranyFlashdeveloper."-JohnPaulRawlins,Editor
FlashNewz.com
FlashandXMLshowsdesignersanddevelopershowtointegratethese


powerfultechnologiesandcreatedynamicwebsites.Withthisthoroughly
readableguideyoutakeFlashtothenextlevel,interfacingActionScript
withXML.EmpoweryourFlashprojectswithdynamiccontent,backend


databases,server-basedapplications,peer-to-peer,andmore.
FlashandXMLisatutorialthatbringsyouuptospeedonboth
technologies,offeringclearandconciseexplanations.Inaddition,this
bookpresentsanumberofimportantwebtechnologies,includingPHP,
MySQL,andsockets.Itshowshowtoworkwiththesetechnologiesto
createn-tier,interactivesystemsthataccessthefullresourcesofthe
Internet.
Sampleprojects(triviagame,XMLbrowser,simplechat)showcasethe
capabilitiesofFlashandXMLtogetheranddemonstrateimportant
concepts,approaches,andtechniques.








TableofContents

FlashandXML:ADeveloper'sGuide
By
DovJacobson,JesseJacobson

Publisher


:AddisonWesley

PubDate

:November20,2001

ISBN

:0-201-72920-2

Pages

:368

Copyright
Preface
What'sUp?
Don'tStop!
WhoAreYou?
Why?
TypographicConventions
Acknowledgments
Chapter1.
FlashBasics
TheBackgroundofFlash
PracticalFlash
Event-DrivenGraphics



BuildingaButton
ConstructingaRound
MakingKeyframes
ConstructingtheResponses
FinishingFeatures
Conclusion—andBeyond
Chapter2.
FlashActionScript:ObjectsandEvents
ObjectOrientationConcepts
Object-OrientedTheoryvs.ActionScriptReality
FlashObjects
ProgrammableButton
DataEncapsulation
Conclusion
Chapter3.
MoreActionScript:Data-DrivenInterfaces
Data-DrivenDecisions
Data-DrivenEverything
IsolatingtheData
DynamicCreationofGraphics
MultipleQuestions
Conclusion
Chapter4.
XMLFundamentals
XMLBackground
HowXMLWorks
DesigningtheData
Conclusion
Chapter5.
XMLStructure

Element
Name
StartTag
EndTag
Attributes
Text(CharacterData)
EntityReferences
Comments
ProcessorInstructions
Conclusion
Chapter6.
XMLValidation:DTD


PurposeofDTD
ValidXMLandWell-FormedXML
DTDDeclarations
Entities
Namespace
Conclusion
Chapter7.
HTTPConnection
CharacteristicsofHTTP
StructureofHTTP
LoadingDatafromaFile
MakingaSelf-LoadingHighScoreDisplay
Object-OrientedImplementation
DataFile
FlashDownloadSecurity
Conclusion

Chapter8.
XMLConnection
DownloadingXML
XML.load
DebuggingFlash
Event-DrivenFunctionality
Conclusion
Chapter9.
RecursiveApproach
Event-DrivenCode
RecursiveDesign
Recursion
RecursioninPractice
GraphicXMLBrowser
InteractiveNodeViewer
Conclusion
Chapter10.
XMLServer
XMLOnline
DedicatedXMLServer
Middle-TierSolutions
PHPBasics
PHPandXML
XML-DrivenFlashClient
Conclusion


Chapter11.
DatabaseFundamentals
Background

AdvantagesofaDBMS
AdvantagesofSQL
Keys
Conclusion
Chapter12.
SQLSyntax
VarietiesofSQL
Prompt
Tables
GuidelinesforBuildingaTable
TypesofData
AddingDatatoTables
ReadingRecordsfromtheTable
Conclusion
Chapter13.
ServingfromSQL
ConnectingtoaDatabase
InteractionwithaDatabase
ParsingCommands
FetchingaRow
Trial-and-ErrorApproach
ScalableAlternative
Conclusion
Chapter14.
XMLUpload
FlashClient
UploadingtoPHP
Conclusion
Chapter15.
Two-WayXML

Event-DrivenParsing
BuildingthePHPParser
Conclusion
Chapter16.
Cookies
ActionScriptXMLObjects
StatelessPersistence
Conclusion


Chapter17.
ThreeTiers
Database
FlexibleMiddleTier
ClientTier
Conclusion
Chapter18.
FlashtotheWorld
DomainPerimeter
PHPProxy
Client
RSSFile
RSSBrowser
Conclusion
Chapter19.
XMLSockets
AdvancedSocketProgramming
XMLSocket
SimpleSocketSystem
SimpleSocketServer

Conclusion
Chapter20.
MultiplexedXMLSockets
Chat
ClientwithHistory
MulticlientServer
BeyondPHP
Conclusion
Chapter21.
EndNote
AppendixA.
MicrosoftCompatibility
ASPCodewithFlash
IISandPHP
AppendixB.
ScalableVectorGraphics(SVG)
AppendixC.
ToolsandSources
NetworkTool


Servers
XMLTools
PHPTools
MySQLTools
Flash


Copyright
Manyofthedesignationsusedbymanufacturersandsellersto

distinguishtheirproductsareclaimedastrademarks.Wherethose
designationsappearinthisbook,andAddison-Wesleywasawareofa
trademarkclaim,thedesignationshavebeenprintedwithinitialcapital
lettersorinallcapitals.
Theauthorsandpublisherhavetakencareinthepreparationofthis
book,butmakenoexpressedorimpliedwarrantyofanykindand
assumenoresponsibilityforerrorsoromissions.Noliabilityisassumed
forincidentalorconsequentialdamagesinconnectionwithorarisingout
oftheuseoftheinformationorprogramscontainedherein.
Thepublisheroffersdiscountsonthisbookwhenorderedinquantityfor
specialsales.Formoreinformation,pleasecontact:PearsonEducation
CorporateSalesDivision201W.103rdStreet
Indianapolis,IN46290
(800)428-5331

VisitAWontheWeb:www.aw.com/cseng/
LibraryofCongressCataloging-in-PublicationDataJacobson,Dov.
FlashandXML:adeveloper'sguide/DovJacobsonandJesse
Jacobson.
p.cm.
Includesindex.
ISBN0-201-72920-2(alk.paper)1.XML(Documentmarkuplanguage)
2.Websites—Design.3.Flash(Computerfile)I.Jacobson,Jesse.II.
Title.


QA76.76.H94J3342002
005.7'2—dc212001045738
Copyright©2002byDovJacobsonandJesseJacobsonAllrights
reserved.Nopartofthispublicationmaybereproduced,storedina

retrievalsystem,ortransmitted,inanyform,orbyanymeans,electronic,
mechanical,photocopying,recording,orotherwise,withouttheprior
consentofthepublisher.PrintedintheUnitedStatesofAmerica.
PublishedsimultaneouslyinCanada.
Forinformationonobtainingpermissionforuseofmaterialfromthis
work,pleasesubmitawrittenrequestto:PearsonEducation,Inc.
RightsandContractsDepartment75ArlingtonStreet,Suite300
Boston,MA02116
Fax:(617)848-7047
Textprintedonrecycledpaper12345678910—DOC—0504030201
Firstprinting,October2001

Dedication
Tothreewelove—Shez,Judy,andAnnaLeahJacobson


Preface
Flashcanmakefabulousintroductionstofancywebsites.High-grade
wowfactorfillstheopeningscreens.Colorsaredelicious,typefacesare
trendy,andmovementisexquisite.Ravemusicisloopingandattitudeis
everywhere.Eachintroisauniqueworkofart.Buttheyallhaveone
thingincommon.
EachhasabuttonthatsaysSKIPINTRO.
Rarelyisgratuitousglitzsoclearlylabeled.Whenbudgetstighten,
webmasterswillnotskipshoppingcart,orskipcatalog.Buttheymayskip
intro.


What'sUp?
Thewebisoutgrowingitseye-candyphase,andsomustFlash.Aweb

sitemustbeprettytobeviable,butitmustbehighlyfunctionalaswell.
Flashproscan'tgetbyongee-whizanimationorcoolinterfaces.They'd
betterpreparetodosomeoftheheavyliftingontheworkingweb.Flash
screensmustinterfacewithdynamiccontent,withback-enddatabases,
withserver-basedapplications,andevenwithotherliveusers.
XMLprovidesapath.


Don'tStop!
OnceyouconnectyourFlashcodetotheoutsideworld,yourscopeis
unbounded.Andsoisthelistofthingstolearn.
Inthisbookwelearnalot.WebeginwithFlashandXML.Westudy
networkingprotocolsandPHPserverscripting.Welearnsocketsand
SQLandafewfancyXMLdialects.Wegoontoachievecompetencein
manyotherrelatedtechnologiesandputthemtogethertobuildworking
websystems.


WhoAreYou?
Ifyouarecreativeandtechnical,thisbookisforyou.Maybeyouhavea
designbackground.Youlearnwhatevertechnologyyouneedtorealize
yourvision.Thisbookoffersyouskillsthatopenfreshnewworlds.Let's
hopeyourimaginationcankeepup.
Maybeyouhavecomputersciencetraining.You'rehappywithsimple
graybuttons.Yourartisanelegantcodedesign.Youarereadytoput
Flashtoworkwithallthewebtechnologiesyoualreadyknow.
ThisbookwaswrittenbyauthorswhoapproachFlashfrombothangles.
Wewantittospeaktobothengineersandartists,andwestruggled
(oftenwitheachother)tosupportbothperspectives.



Why?
Wewrotethisbookbecauseitwasn'ttherewhenweneededit.


TypographicConventions
Wehaveadheredtoseveralconventionsinthisbook.

CaseConventions
lowerAndUpperCaseisusedtonamevariablesandfunctionsin
ActionScriptUpperAndLowerCaselabelsframesandnames
symbols,objectsandconstructors.
ALL_UPPER_CASEisusedinmanifestconstants,SQLkeywords,
PHPglobals.
Separated_by_underscoresistypicallyusedforPHPnames.

TypesettingConventions
italicsindicatenameswegavevariables,functions,elements,
instances,andsoon.

codefontshowslanguagekeywordsandexpressions.
codefontisalsousedtosetoffthetextoutputofanyprogram.
boldfaceintroducesthefirstuseofanimportantterm.
SMALLCAPSareusedforpull-downmenuoptions.Slashesshow
hierarchy.
"quotes"arereservedforstringliterals.
Theserulesarebreachedoccasionallyinthebook.Sometimesthisisfor
historicreasons,sometimesduetoambiguityandsometimesbecauseit
justdidn'tlookright.



DovandJesseJacobson
BerkeleyLake,Georgia


FlashandXML.com


Acknowledgments
Forhersureguidance,forhersturdybeliefinthisbookandherfaithinits
authors:MaryT.O'Brien,ExecutiveEditoratAddison-Wesley.
Fortheirablesupport:hereditorialassistants,AliciaCareyandMariann
Kourafas.
Forhisimaginative,clearheadedthinkingonmanyaspectsofthisbook,
andespeciallyforitshandsomelooks:KevinSmithofstatelessdesigns.
Forhercareinthetrickytransformationofbytesintoinkandpaper:
JacquelynDoucette.
Fortheirpatienceandprofessionalisminthecompositionprocess:
StratfordPublishingServices.
Forhishelpinunravelingthetoughesttechnicalknotsandhis
aggravatinghabitofimprovingourwork:NigelHead.Hemadehispoints
withsomeveryclevercodesequencesand,well,weincludedsome
verbatim.
Fortheircareful,knowledgeable,andlivelytechnicalreview:Christopher
IanSmith,JohnPaulRawlins,ToddWilliamsen,ScottHamlin,Mike
Callery,JenniferHall,andtheaccomplishedBrendanHall.
Fortheirrapidresponsivenessandforanenjoyableweekofdebugging
Flashpatchestogether:ZlavikLozbenandEricJ.Wittmanof
Macromedia.
ForhiscleandirectionofFlashtechnology:PeterSantangeli.(Wecanall

thankhim.)
ForbuildingMacromediawithhisbarehandsandhisbigmouth:ourold
friendMarcCantor.
Fortheirenthusiasmandtheirinsights:ColinMoockandother
FlashForwardspeakers,Uramiandothermacromedia.flashposters,and


thelivelycommunityatFlashKit.com.
Fortheirsupport—financialandcreative—ofthereal-lifeversionofthe
gamedescribedinthisbook:webmasterGarthMooreandproducerZoë
BurkholderoftheASPCA(animaland.org).
Forpermissiontoreprinthishaiku:WalterVereertbrugghen.
Andfortheircriticalcontributiontothisproject:themakersoffine
caffeinatedbeveragesallovertheworld.


Chapter1.FlashBasics
Inthischapter,welearntobuildsimpleinterfaceelementsandinteractive
structures.Boththeelementarystructureswebuildandthetechniques
welearnareusedanddevelopedfurtherthroughoutthebook.
ThischapterisintendedforreaderswhoarenewtoFlash.Itbringsthem
uptospeedquicklyoneditingconventionsandActionScript
fundamentals.Italsopresentsanoverviewofthedesignofdataand
executioninthetriviagame.


TheBackgroundofFlash
Flashisaninterestingphenomenon.Itbeganwithtechnologyintended
forpencomputing.Thistechnology—whichtranslatedstrokesinto
drawings—wascommercializedasSmartSketch,apersonalcomputer

drawingpackage.SmartSketchmadeiteasyforartiststocreatepictures
thatweredefinedasgeometry,notasascreenofpixels.Theinventorsof
theprogram,suchas,JonathanGay,understoodtheadvantagesofthis
technology—vectordrawing—overthemorefamiliartechniqueofpixel
painting.Geometricdescriptionsscaleperfectlyandtheyareextremely
efficient.Itiseasytomovethesepicturesfromonecomputertoanother.
High-leveldrawingdescriptionsalsomakeiteasytoorganizethe
elementsofadrawing—andtomanipulatethemmathematically.
Easymanipulationmeanspowerfulanimation.SmartSketchevolvedinto
CelAnimator—aprofessionalcartooningtool.Thecartooningworldis
fairlysmall—andwassmallerstillinthe1990s.Thisvectoranimation
programmighthavedisappearedlikeitspredecessorsexceptforthe
emergenceoftheInternet.Deviceindependenceandtinybandwidth
requirementswereagreatfitfortheweb—whichwasstarvedfor
animation.
Macromediawasintroducingitsvenerableanimationsystem,Director,to
theInternetunderthenameShockwave.Butpixel-basedtechnology
suchasDirectorisinflexibleandslowtoload.In1996,Macromedia
acquiredtheproduct,thencalledFutureSplash.Theychangedthename
toFlashandmergeditintotheShockwaveline.
Insucceedingyears,moreinteractivityandmuchmorescriptingwere
addedtoFlash.
Afterafewawkwardattemptstodevelopaproprietarycodingsyntax,
FlashActionScriptwasstabilizedbyadoptingECMA-262asthebasisof
itslanguagedefinition.ECMA-262istheinternationalstandardforweb
scripting.(JavaScriptisanECMA-compliantlanguage.)
Thisdecisionloweredthelearningcurvefordevelopersandreducedalot


ofconfusionandambiguity.ItallowedFlashtodevelopfromasimple

animationsystemtoafairlyrobustenvironmentforthedevelopmentof
interactivewebapplications.
Asecondwisedecisionalsoinvolvedtheadoptionofwebstandards.
MacromediachoseXMLtobeFlash'sdata-communicationtechnology.
SuddenlyFlashdeveloperswereabletoeasilyinteractwithanenormous
numberofwebservices.ThischangedthenatureofFlashoncemore.
Insteadofastand-alonewebapplication,aFlashpresentationcanbe
integratedintoacomplexsystemofweb-enabledsoftware.Flashisno
longerlimitedtoentertainment.Itisnowreadytoprovidehigh-quality
interfacestoallkindsofhardworkingwebapplications.


PracticalFlash
Inthischapter,wedonotattempttoconscientiouslyteachFlashgraphics
creation.Thatisthesubjectofmanyotherbooks.Thechapterisnot
evenanoverviewofthesubject.Infactthischapterismoreofan
underview.Weofferamouse's-eyeviewoftheconstructionofafew
simplebutsophisticatedinterfaceelements.Wedon'tsuggestthatour
methodsarethebestapproachtoeachproblem.Multifacetedsoftware
likeFlashinvitescreativeapproaches.Theapproachweshowhere,
basedonmuchexperienceinteamproductionofcodeandgraphics,is
onegoodapproach.Consideritasyoudevelopyourown.

ProjectDesign
Thetriviaquizgamethatwewillbuildthroughoutthisbookiscomplex
andsophisticated.Itstarts,however,withsomesimpleideasthatare
recognizableineverylaterstepofdevelopment.
Beforewestartanycode,evendemonstrationcode,weneedtothinka
littleaboutthedesign.Ingeneral,adetailedplanningphaseisalwaysa
goodinvestment.Butinthiscase,justasimplelayoutofhierarchywill

suffice.
WeorganizeaGameintoaseriesofQuizzes(Figure1.1).EachQuiz
hasseveralrounds.ARoundisthepresentationofaQuestion,the
player'sresponse,andthescoring.TheQuestionispresentedinQ&A
format:asingleQandmultiple-choiceA's.
Figure1.1.ObjectHierarchyoftheTriviaGame


InthischapterwecreateasinglefunctionalRound.Wepresenta
QuestionandaseriesofAnsweroptionsanddeterminewhetherthe
playerhaschosenthecorrectone.That'sallfornow.
Ourapproachistodevelopthreestates:Startstate,Winstate,andLose
state(Figure1.2).ThelattertwostatescomprisetheResponsetothe
user.TheStartstateencapsulatestheQuestionpresentation.
Figure1.2.LogicatOneRound


Event-DrivenGraphics
AgreatstrengthofActionScriptisthatexecutioniseventdriven.Things
thathappenintheoutsideworldcausethingstohappeninFlash.

FrameEvents
Themostcommoneventisthattimepasses.Ofcourse,timepasses
rathercontinuously,butinFlash(asinvideoorfilm)timeisbrokenintoa
streamofregularintervalscalledframes.InatypicalFlashapplication
thereare12framespersecond.Twelvetimeseverysecond,Flashis
interruptedbyaframeevent(moreprecisely,aframestartevent),which
startsacascadeofcalculations.Anythingthatisintheprocessofmoving
mustdetermineitsnewpositionandpreparetoredisplay.Thisishow
animationhappens.

Eachmoviehasatimeline.Whenaframeeventoccurs,itadvancesa
pointeralongthetimelinetoexecuteanynewscriptoreffectany
changesscheduledforthisframe.

MouseEvents
FrameeventsgiveFlashanimation.Mouseeventsgiveitinteractivity.
Whenauserclicksabutton,thatisanevent.Itisinfactaseriesof
events:Firstthecursorentersthebutton'shotspot(theRollOver
event).Thentheuserdepressesthebutton(thePressevent).Thenthe
userstopspressing(Release)andmovesthecursoraway(RollOut).All
foureventshappenoftenwithinahalfsecond,buteachhasadifferent
meaningintherapidlystabilizinglanguageofuserinterface:
RollOver:
Press:
Release:
RollOut:

Whatisthis?
IthinkIwanttoperformthisaction
Yes,Ido!Iamcommitted.
Oh.Well,nowIambored.


×