Professional Documents
Culture Documents
AboutthisGuide
IntroductiontoAura
Prerequisites
AboutAuraNote
Tutorial#1:CreatingaComponent
Step1:SetupaComponent
Step2:CreateaModel
Step3:GetDatafromtheModel
Step4:IteratethroughtheModel
Tutorial#2:CreatingaNestedComponent
Step1:CreateaComponentforRepeatingData
Step2:CreateaCSSfile
Tutorial#3:MakingtheComponentInteractive
Step1:AddanonclickHTMLEvent
Step2:CreateaClientSideController
Step3:CreateaServerSideController
Step4:RunanInstanceoftheAction
Step5:SpecifytheServersideControllerintheComponent
Tutorial#4:DebuggingandTestingtheComponent
Step1:Usethebrowserdebugger
Step2:UsetheAuraDebugTool
Tutorial#5:BuildingtheApp
Step1:CombinetheComponentstogether
Step2:ExtendaComponent
Step3:CommunicatewithEvents
NextSteps
Foundanissue?
Introduction to Aura
AuraisaUIframeworkfordevelopingdynamicwebappsformobileanddesktopdevices.Aura
providesascalable,longlivedlifecycletosupportbuildingappsengineeredforgrowth.Built
usingJavaScriptontheclientsideandJavaontheserverside,Aurasupportspartitioned,
multitiercomponentdevelopmentthatbridgestheclientandserver.
Auracomeswitharichandextensiblecomponentsettokickstartbuildingapps.Youdon'thave
tospendyourtimeoptimizingyourappsfordifferentdevicesasthecomponentstakecareof
thatforyou.Theframeworkintelligentlyutilizesyourserver,browser,devices,andnetworkso
youcanfocusonthelogicandinteractionsofyourapps.
Prerequisites
Beforeyoubegin,thereareafewprerequisites.
CompletetheAuracommandlineQuickStartsectiontomakesurethatyouhavethe
rightenvironmenttoworkwithAura.
GetthesourceforAuraNoteandbuildit.
AuraNotehasthesemainfeatures:
1.Createanewnote.
2.Displaythenotes.
3.Sortnotesbydateoralphabet.
4.Searchnotesbasedonagiventerm.
5.Editanote.
Wellshowyouhowtocreateacomponent,whichdisplaysthenotesintheapp.
Tell Me More
Whenyourecreatingcomponents,itsimportanttounderstandthedirectorystructure.
noteList.cmpisinadirectorycallednoteList.ThenoteListdirectoryrepresentsthe
componentandthedirectoryiscalledacomponentbundle.
YoucanaddaJavaScriptcontroller,renderer,CSSfileandotherresourcesinthecomponent
bundle.Theparentdirectoryofthebundleiscalledauranoteandrepresentsthenamespace
forthiscomponent.ComponentsaregroupedintonamespacessimilarlytohowJavaclasses
aregroupedinapackage.
Next,welliterateoverdatainthemodel.
2. Reloadthebrowser(http://localhost:8080/auranote/noteList.cmp)and
seethatthetitleandbodyofeachnoteisdisplayed.
Inthenexttutorial,wellshowyouhowtobreakthisdownintoanestedcomponent,use
unescapedHTML,andpassattributestotheparentcomponent.
Tell Me More
Auracomeswithasetofoutoftheboxcomponentsthatareorganizedintodifferent
namespacesforexample,theauraanduinamespaces.Theuinamespacehasallthe
componentsyouwouldexpecttofindinaUIframework,suchastextinput/output,date
input/output,andlayoutcomponents.Theauranamespaceincludesmanycomponentsfor
coreAuraframeworkfunctionality,likeaura:iterationinthistutorial.
{!v.note.title}
</aura:component>
4. Reloadthebrowser(http://localhost:8080/auranote/noteList.cmp)and
youllseeasimilaroutputasinTutorial#1.
Tell Me More
PassinginAttributes
WehaveanoteattributeofJavatype,henceweset
type=java://org.auraframework.demo.notes.Note.Forprimitivetypes,youcan
justusetype="String"ortype="Integer",etc.PrimitivesareconvertedtoJava.For
nonprimitivetypes,usethespecificlanguageandthefullyqualifiednameofthetypethatyou
wouldliketouse,likeweredoinghere.
Werenowusing{!v.note.title}and{!v.note.body},insteadof{!note.title}
and{!note.body}.Whenwewereinsideaniterationearlier,wehaddefinedaprefixcalled
noteforthescopeoftheiteration.Sincewemovedthiscodeoutoftheiterationtoaseparate
component,weareactuallylookingforthenotethatwaspassedinasanattribute.vistheprefix
thatreferstothecollectionofattributesonthiscomponent.Allexpressionsmuststartwitha
prefix.
UnescapingHTML
YoucanuseHTMLinabodyofthecomponent.Bydefault,AurawillescapeallHTML.
noteListRow.cmpuses<aura:unescapedHtmlvalue="{!v.note.body}"/>inthe
componenttomakesureouroutputisunescaped.Otherwise,theoutputissimilartoStep4of
Tutorial#1.
10
YoucandeletenoteList.cssasweareonlyusingitinthistutorial.
Tell Me More
Theformatoftheselectorforacomponentis.namespaceComponentName.Noticethat
.THIS.uiOutputDateTimehasaspacebecauseitisadescendantselectorandnota
toplevelelement.
11
<aura:componentextends="auranote:listRow">
<aura:attributename="note"
type="java://org.auraframework.demo.notes.Note"/>
<aura:setattribute="desc">
<divclass="mask"> </div>
<aura:unescapedHtmlvalue="{!v.note.body}"/>
</aura:set>
<aura:setattribute="onclick"value="{!c.openNote}"/>
{!v.note.title}
</aura:component>
The{!c.openNote}expressiontiestheonclickeventtotheopenNoteactioninthe
component'sclientsidecontroller.Auraalsoallowsyoutocreateyourowncomponentor
applicationevents.Formoreinformation,seetheAuradocsite.
Next,wellseehowtospecifythebehaviorforthiseventinthecontroller.
2. Letsgobacktothebrowser
(http://localhost:8080/auranote/noteList.cmp)andreload.Clickon
somethingandyoushouldgetanalert.
3. Togetsomedata,updatethecodewith
alert(component.get("v.note.title")).Reloadthebrowserandseethatwe
gotsomedatausingtheJavaScriptAPI.
13
noteListRowController.js
({
openNote:function(component,event){
alert(component.get("v.note.title"))
}
})
Tell Me More
SincethisisthecontrollerfornoteListRow,thecomponentthatispassedintothatactionwill
alwaysbeanoteListRow.Thecurlybracesdenotesanobject,andeverythinginsidethe
objectisamapofnamevaluepairs.ThenamehereisopenNote,whichisanactioninthe
controller,andthevalueisafunction.ThefunctionispassedaroundinJavaScriptlikeanyother
object.So,we'recreatingafunctionasavalueoftheopenNotekey.Thatoutsideobjectwe
createdisthecontrollerandtherestofthecodeinsideistheaction.
14
}
Wellusethisinthenextstepwhenwerunaninstanceoftheaction.
Tell Me More
Controllershavea@Controllerannotationbeforetheclassdeclaration.Wecreatedtheecho
methodtotakeinandreturnaString.Themethodmustbestatic.Weregoingtoreturnthe
samestringthatcomesinandaddaprefixtoitsoyouknowitcamefromtheserver.
Wehavetoputthe@AuraEnabledannotationtoexposethemethod.WewanttotakeaString
asanargumentonthisaction.Youcanmakeanysignatureyouwant.Itcanreturnortakeany
typesyouwant,List,Map,andsoon.Youcanevencreatecomponentsinhere,returnthem,and
getanewcomponenttotheclientsidefromtheserver.
WeusetheMaptypecallsandwealwayspassinnamevalues.Soifwehavefourarguments
onthismethod,andifwereonlyinterestedinusingthefourthone,wedonthavetopassinthree
nullslikeinJava.Wejustsaythenameoftheargumentandthevalue.AtJavaruntime,ifyou
donthavecompiledebugflags,youlosethenamingfortheseofarguments.Soweneedtogive
Auraahintonwhatwenamedit.Weaddanotationoneachargumentwiththe@Key
annotation.Inthisexample,thekeyisvalue.
15
2. Queuetheactionsothatitsrunafterthecurrenteventhascompleted.
noteListRowController.js
({
openNote:function(component,event){
varaction=component.get("c.echo")
action.setParams({value:component.get("v.note.title")})
action.setCallback(this,function(a){
alert(a.getReturnValue())
})
$A.enqueueAction(action)
}
})
Inthenexttutorial,wellwireuptheserversidecontrollerwecreatedinStep3inthecomponent.
Tell Me More
component.get("c.echo")returnsaninstanceoftheserversideaction.Itsaonetime
wrapperforthemethodcall.action.setParams()passesinaJSONmapthatsetssome
parametersontheaction,withakeycalledvalue.Thevaluepassesinthetitleofthenoteusing
component.get("v.note.title").
Nowthatwehavesetparamsontheaction,wespecifywhatwewantaftertheserverresponds.
So,wesetacallback.Weuseaction.setCallback()andpassinafunction,whichwillbe
calledwhenthefunctionreturns.Andinthatfunction,wewanttheactionobjectpassedback
in.Justtoillustratethatitstwodifferentpointerstothatobject,wecalledita.Butitwillendup
beingthesameactionobject.
Alltheactioncallsareasynchronousandruninbatches.Aneventcanfiremanyclientside
actions,andeachoneofthemmayrequireserversideprocessing.Youcouldendupwithmany
requeststotheserversowebatchthemupandcancelthingsthatdontmakesenseanymore
beforesendingthemtotheserver.The$A.enqueueAction(action)calladdstheactionto
aqueue.Theactionsinthequeuearerunafteralltheclientsideprocessingrelatedtothisevent
hasbeenprocessed.
16
noteListRow.cmp
<aura:componentextends="auranote:listRow"
controller="java://org.auraframework.demo.notes.controllers.NoteLis
tRowController">
<aura:attributename="note"
type="java://org.auraframework.demo.notes.Note"/>
<aura:setattribute="desc">
<divclass="mask"> </div>
<aura:unescapedHtmlvalue="{!v.note.body}"/>
</aura:set>
<aura:setattribute="onclick"value="{!c.openNote}"/>
<aura:setattribute="right">
<ui:outputDateTimevalue="{!v.note.createdOn}"format="h:mm
a"/></aura:set>
{!v.note.title}
</aura:component>
3. Reloadthebrowser(http://localhost:8080/auranote/noteList.cmp)and
clickanote.YoullgetanalertthatsaysFromserver:SampleNote.
17
2. Refreshthebrowser(http://localhost:8080/auranote/noteList.cmp).
Clickonanyofthenotes,andyouareimmediatelytakenthroughthedebugger.
Youmusthavethedebuggerconsoleopentostepthroughthecode.Youcandothingssuchas
addingexceptionbreakpointshere.Whenanexceptionisraised,itwilltakeyoutothelocation
thatcausedtheproblem.Remembertoremovethedebuggerstatementwhenyouredone
anduncommentthe$A.enqueueAction(action)call.
19
Youcanalsoaddbreakonexceptions(pausesymbolatthebottomleftofthedevconsole).If
youclickthatbuttonandhitanexception,itllbringupthelineofcodethatcausedtheexception.
Tell Me More
20
YoucanputacomponentNameTest.jsfileinyourcomponentbundlejustlikewewrotethe
JSONformatforactions.TheyruninthebrowserandwehaveaUIwithatabforeachtestcase.
TodebugJSONtraffic,usetheNetworktabonGoogleChromeDeveloperTools.Formore
information,seetheAuradocsite.
Forperformancetests,youcanloadacomponentinamodeintheURLwhichrunsJiffyand
returnsagraphofhowyourappisrunning.Append?aura.mode=PTESTtoyourcomponent
output:http://localhost:8080/auranote/noteList.cmp?aura.mode=PTEST
21
22
ItincludesHTMLmarkup,suchas<div>and<header>tags.TheheadertagisanHTML5tag
whichactslikeadiv.Then,weseeaui:block,whichisanAuracomponent.
ui:blockcontainsleft,right,andcenterelements.Thiscomponentappliesfixedwidthtothe
leftandrightelements,andletsthecenterfilluptheavailablespace.Wesetaclassonthe
ui:blockcalledwrapper,whichoutputsastheCSSclass.ui:blockalsotakesina
namespaceattribute,aura:id,soyoucanspecifyanyattributenamespacesyouwant.
aura:idisnotanHTMLID.Itletsusfindthatblockbynameusingcomponent.find
("block")withinthescopeofthisapp,itscontroller,andrenderer.
Intheui:blockcomponent,weresettinganattributewhichpassesinanothercomponent,
sidebar.cmp,whichcontainsthecomponentweworkedon,noteList.cmp.
<aura:setattribute="left">
<auranote:sidebaraura:id="sidebar"/>
</aura:set>
Next,wellextendacomponent.
23
Tell Me More
Anapplicationisaspecialtypeofcomponent.Theycandoeverythingacomponentcando,
excepttheyarealwaysatthetoplevel.Wehavebeenrequestingcomponentsdirectlyinthe
URL.IfyoulookattheURL,anycomponentcanberequestedwith
/namespace/componentName.cmpaslongasyourenotinproductionmode.Inproduction
mode,youcanonlyrequesta.appfileinaURL.
Anapplicationcanalsohaveasecurityprovider,whichisaJavaclassthatcandopermchecks
tomakesurethattheuserwhosloggedincanaccessthisapplication.Ifyouwanttolockdown
whichnamespaceacomponentcanuse,youcandothatwithasecurityprovidertoo.Formore
information,seetheAuradocsite.
PreloadingNamespaces
Theaura:applicationtagincludespreload="auranote",whichdenotesthatwewant
topreloadtheauranotenamespace.Youcanhaveacommaseparatedlistofnamespaces.
Thiscanimproveperformanceconsiderablyasallthemetadataaboutthecomponentsinthat
namespaceareloadedupfront.Bydefault,Aurawillloadthemasneeded.Butsometimesitsa
littleinefficienttoloadalargeamountofmetadatainadatarequest.
UsingtheAppTemplate
Ifyoulookatthesourceinyourbrowser(notthegeneratedsourcebutunderViewpagesource),
youseeaboilerplateHTMLwithsomeinlinescriptsandCSS,linktagstogetmoreCSS,an
errordiv,andacallintoAuratoinitializeit.ThisHTMLisdefinedintheapplicationstemplate,set
inthethetemplateattribute.Thetemplategetstheframework,metadata,andCSSforthe
preloadednamespacesdowntotheclient.Thisboilerplatepageiscacheablebythebrowser
sinceitdoesntcontaindynamiccontent.AllthescripttagsandCSSinthetemplateare
cacheable.
Thetemplateisa.cmpfile.Ifyoudontspecifyyourowntemplate,adefaultisused.Ifyouwant
toloadextralibrarieslikejQuerywithyourapplication,putitinthetemplate.Itwillbeloaded
upfrontwiththeframework.Youcanoverwritethismarkupentirelyoraugmentitbyextendingthe
basecomponent.
InitializingAura
TheonlydynamicelementonthispageisthecalltoinitializeAura($A.initAsync).In
JavaScript,werefertoAuraas$A.$A.initAsyncmeansasynchronouslymakearequestto
theserver,getaninstanceofthisappandrunit.
TheJavaScriptdocsdocumentstheAuraJavaScriptAPI,includingacollectionofAuraservices
fordealingwithrendering,components,instances,events,expressions.
24
Tell Me More
Componentsarefullyobjectoriented.Youcanextendthem,haveabstractcomponents,orhave
interfacesforcomponents.Components,applications,andeventscanallextendothers.That
meanstheyallinherittheattributesfromtheonestheyareextendingsoyoudonthaveto
redefinethem.
aura:setistheequivalentofattributevaluepairsinXML.Iftheresmarkup,theactual
componenttreeyouwanttopassarounddoesnoteasilyfitintoanXMLattribute.Sothisnested
tagisthesameasanXMLattributepassingvalues.Youjustspecifytheattributenameand
valuejustlikeforanXMLtag,oryoucanpassmarkupliketheHTML<script>tag.Forthe
markup,werepassinganinstanceofanHTMLcomponent,whichisawholetreeofHTML
components.
details.cmp
<aura:componentimplements="auranote:noteData">
<aura:handlerevent="auranote:openNote"action="{!c.openNote}"/>
<aura:attributename="note"
type="java://org.auraframework.demo.notes.Note"/>
<aura:attributename="mode"type="String"/>
<divaura:id="notes"/>
</aura:component>
<aura:handlerevent="auranote:openNote"action="{!c.openNote}"/>
indicatesthatthecomponenthandlestheopenNoteeventintheauranotenamespace.
WhenanopenNoteeventisfired,thecontrollerrunsopenNote,whichdisplaysthenotes.
2. ToseewhatanopenNoteeventis,findtheopenNotedirectoryandopenthe
openNote.evtfile.
openNote.evt
<aura:eventtype="APPLICATION">
<aura:attributename="note"
type="java://org.auraframework.demo.notes.Note"/>
<aura:attributename="mode"type="String"/>
<aura:attributename="sort"type="String"/>
</aura:event>
Itlookssimilartootherfiles,exceptitdoesnthaveanymarkupinit,beingashapeonlydefinition.
Itdefinesthetypeofevent,whichisanapplicationeventinthiscase.Theotheroptionis
type="COMPONENT".Formoreinformation,seetheAuradocsite.
Auraeventscancontainattributesofanytype.Thiseventexpecttohaveanote,sowhen
theresanopenNoteeventhandledbyacomponent,thecomponentgetstheeventobject,and
theycanreadanattributecallednotefromit.
3. Letsfiretheeventandpassthenoteeventtoanycomponentsthathandleit.Lookatthe
codeinnoteListRowController.js.
noteListRowController.js
({
openNote:function(component,event,helper){
$A.get("e.auranote:openNote").setParams({
26
note:component.get("v.note")
}).fire()
}
})
Sincethisisanapplicationevent,weuse$A.get("e.auranote:openNote")toretrieve
theevent,whereeistheglobaleventservice.Wesettheparametersandfiretheeventusing
.fire().
5. Gotohttp://localhost:8080/auranote/notes.appandclickonanoteonthesidebartobring
upthenote.
27
Next Steps
Inthisguide,wehavecoveredcomponentcreation,applications,events,controllers,models,
andcomponentstyling.
Atthispoint,youcanlearnmoreaboutAuraat
http://documentation.auraframework.org/auradocstodrilldownintoconcepts,samplecode,and
theJavaScriptandJavaAPIdocs.TheAuradocsitehasmoreinformationonabstract
components,extension,providers,andinterfaces,aswellassomeoftheinnerworkingsof
Aura.
Found an issue?
Ifyoufindanyproblemsinthisguide,pleaseposttheissueintheGitHubRepo.
28