Sunteți pe pagina 1din 27

TableofContents

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?

About this Guide


ThisguidegivesyouahighlevelintroductiontoAuraandwalksyouthroughafewtutorialson
creatingasimplenotetakingapp,AuraNote.

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.

About Aura Note


AuraNoteisasamplenotetakingappbuiltwiththeAuraframeworktodemonstratethe
simplicityofbuildingappswithAura.Youcanviewtheappat
http://localhost:8080/auranote/notes.appafteryougetthesourceandbuildit.

AuraNotehasthesemainfeatures:
1.Createanewnote.
2.Displaythenotes.
3.Sortnotesbydateoralphabet.
4.Searchnotesbasedonagiventerm.
5.Editanote.
Wellshowyouhowtocreateacomponent,whichdisplaysthenotesintheapp.

Tutorial #1: Creating a Component


AcomponentisareusableandextensiblepartofaUI.Thebasicmarkupofacomponentis
shownbelow.
<aura:component>
<!Othercomponentsandmarkupgohere>
</aura:component>

Step 1: Set up a Component


TheAuraNoteappiscomposedofmultiplecomponents,andwellshowyouhowtoputthem
togetherlater.Fornow,wellintroduceacomponentinthesidebar,auranote:noteList,
whichdisplaysnotesintheapp.
1. OpenthenoteList.cmpfile.Thisfilecontainsthemarkupforauranote:noteList.
2. Loadthiscomponentonthebrowserbygoingto
http://localhost:8080/auranote/noteList.cmp.

Tell Me More
Whenyourecreatingcomponents,itsimportanttounderstandthedirectorystructure.
noteList.cmpisinadirectorycallednoteList.ThenoteListdirectoryrepresentsthe
componentandthedirectoryiscalledacomponentbundle.

YoucanaddaJavaScriptcontroller,renderer,CSSfileandotherresourcesinthecomponent
bundle.Theparentdirectoryofthebundleiscalledauranoteandrepresentsthenamespace
forthiscomponent.ComponentsaregroupedintonamespacessimilarlytohowJavaclasses
aregroupedinapackage.

Step 2: Create a Model


DatainAuratypicallycomesfromamodel.ThemodelcanbeaJavaclassoraJSONmodel.
WeregoingtouseJavaforthisexample.
1. OpenthenoteList.cmpfile,whichdisplaysdatafromamodel.Youllseethefollowing
code.Themodelattributein<aura:component>wiresthecomponenttoa
NoteListModelclass.Ignoretheaura:attributetagsaswe'lldiscussthemlater.
noteList.cmp
<aura:component
model="java://org.auraframework.demo.notes.models.NoteListModel">
<aura:attributename="sort"type="String"
default="createdOn.desc"/>
<aura:attributename="query"type="String"/>
<aura:iterationitems="{!m.notes}"var="note">
<auranote:noteListRowaura:id="row"note="{!note}"/>
</aura:iteration>
</aura:component>
2. OpentheNoteListModel.javafile.The@Modelannotationprecedingtheclass
denotesthattheclassisamodel.Aurainstantiatesyourmodel,executeseachofthe
gettersontheinstanceofyourmodelclass,andsendsthereturnedvaluestotheclient.
3. Bydefault,Auradoesntcallanygetters.Ifyouwanttoaccessamethod,annotatethe
methodwith@AuraEnabled.The@AuraEnabledannotationenablesyoutoonly
exposedatathatyouexplicitlychoosetoexpose.
NoteListModel.java
@AuraEnabled
publicList<Note>getNotes(){
returnnotes
}

Step 3: Get Data from the Model


Tounderstandhowwereusingthemodeldatainthecomponent,letslookatnoteList.cmp.
1. InnoteList.cmp,replacethe<aura:iteration>...</aura:iteration>code
blockwith{!m.notes[0].title}.Thisexpressionbindstothetitleofthefirstnotein
thelistreturnedfromthegetNotes()methodonourmodel.
noteList.cmp
<aura:component
model="java://org.auraframework.demo.notes.models.NoteListModel">
<aura:attributename="sort"type="String"
default="createdOn.desc"/>
<aura:attributename="query"type="String"/>
{!m.notes[0].title}
</aura:component>
2. Refreshthebrowser(http://localhost:8080/auranote/noteList.cmp)and
youllseethatonlythetitleofthefirstnoteisdisplayed.

Next,welliterateoverdatainthemodel.

Step 4: Iterate through the Model


Thisstepusesanexpressiontobindtodatainthemodel.
1. Replace{!m.notes[0].title}withthe
<aura:iteration>...</aura:iteration>codeblock,asshowninthefollowing
code.<aura:iteration>isacomponentthatiteratesoveragivenlistofitems.
noteList.cmp
<aura:component
model="java://org.auraframework.demo.notes.models.NoteListModel">
<aura:attributename="sort"type="String"
default="createdOn.desc"/>
<aura:attributename="query"type="String"/>
<aura:iterationitems="{!m.notes}"var="note">
{!note.title}<br/>
{!note.body}
</aura:iteration>
</aura:component>

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.

Tutorial #2: Creating a Nested Component


Sincethelogicfordisplayinganoteisstartingtogetcomplicated,letsbreakitoutintoa
separatenoteListRowcomponent.

Step 1: Create a Component for Repeating Data


1. Removethecontentinthe<aura:iteration>codeblockandreplaceitwith
<auranote:noteListRowaura:id="row"note="{!note}"/>.
noteList.cmp
<aura:component
model="java://org.auraframework.demo.notes.models.NoteListModel">
<aura:attributename="sort"type="String"
default="createdOn.desc"/>
<aura:attributename="query"type="String"/>
<aura:iterationitems="{!m.notes}"var="note">
<auranote:noteListRowaura:id="row"note="{!note}"/>
</aura:iteration>
</aura:component>
Now,insteadofpassingsomedatafromthenoteintoHTML,wearepassingthewholenoteinto
anothercomponent.Wehavecreatedthenestedcomponent,auranote:noteListRowfor
you.
2. OpennoteListRow.cmptoseethesource.
3. Tounderstandhowthenestedcomponentworks,letsstripthecodedowntothebare
minimum,asshowninthefollowingcode.{!v.note.title}accessesthenote
attributeandthetitleonit.
noteListRow.cmp
<aura:componentextends="auranote:listRow">
<aura:attributename="note"
type="java://org.auraframework.demo.notes.Note"/>
<aura:setattribute="desc">
<divclass="mask">&nbsp</div>
<aura:unescapedHtmlvalue="{!v.note.body}"/>
</aura:set>

{!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

Step 2: Create a CSS file


Toapplystylestoyourcomponent,adda.cssfileinthecomponentbundle.
1. LetscreateanewfilecallednoteList.cssinthenoteListfolder.
2. Addthefollowingstylesinthefile.
.THIS{
backgroundcolor:#dbebff
}
.THIS.auranoteNoteListRow{
border:1pxsolid#888
}
.THIS.uiOutputDateTime{
fontweight:bold
}
.THISh2{
color:#333
}
Theformatoftheclassnameisthenamespacefollowedbythenameofthecomponent.And
.THISreferstothetoplevelelementthatsrenderedbythiscomponent.
3. Refreshthebrowserandseethatthestyleshavebeenapplied.

YoucandeletenoteList.cssasweareonlyusingitinthistutorial.

Tell Me More
Theformatoftheselectorforacomponentis.namespaceComponentName.Noticethat
.THIS.uiOutputDateTimehasaspacebecauseitisadescendantselectorandnota
toplevelelement.

11

Tutorial #3: Making the Component Interactive


Nowthatweveexploredthebasicsofacomponent,letsmakeourappabitmoreinteractiveby
addinganeventandcommunicatingwiththeserver.

Step 1: Add an onclick HTML Event


ManyHTMLtagsarevalidinAuramarkup.Youcanuseeventsforcommonmouseand
keyboardinteractions,suchasonclick,fortheseHTMLtags.
Forexample,wecanaddanonclickeventforthe<li>tagtotriggeranactioninthe
clientsidecontrollerofthecomponent.noteListRow.cmpextendslistRow.cmp,which
containstheonclickevent.
1. OpenlistRow.cmpandnotethatwesettheonclickeventonthe<li>tag.
listRow.cmp
<aura:componentextensible="true">
<aura:attributename="desc"type="Aura.Component[]"/>
<aura:attributename="onclick"type="Aura.Action"/>
<aura:attributename="left"type="Aura.Component[]"/>
<aura:attributename="right"type="Aura.Component[]"/>
<lionclick="{!v.onclick}">
<ui:block>
<aura:setattribute="left">{!v.left}</aura:set>
<aura:setattribute="right">{!v.right}</aura:set>
<h2class="subjecttruncate">{!v.body}</h2>
</ui:block>
<aura:ifisTrue="{!v.desc!=null}">
<pclass="desctruncate">{!v.desc}</p>
</aura:if>
</li>
</aura:component>
<aura:attributename="onclick"type="Aura.Action"/>describesthatthe
onclickattributeisavailableonthecomponent.Wecanthensetitonthechildcomponent,
noteListRow.cmp.Tutorial#5goesthroughextendingacomponentinmoredetails.
2. InnoteListRow.cmp,settheonclickeventusing<aura:set
attribute="onclick"value="{!c.openNote}"/>.
noteListRow.cmp
12

<aura:componentextends="auranote:listRow">
<aura:attributename="note"
type="java://org.auraframework.demo.notes.Note"/>
<aura:setattribute="desc">
<divclass="mask">&nbsp</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.

Step 2: Create a Client-Side Controller


Aclientsidecontrollerhandleseventsinacomponent.
1. InthenoteListRowdirectory,openthenoteListRowController.jsfile.Replace
thecodewiththeonehere.
noteListRowController.js
({
openNote:function(component,event){
alert("opennote")
}
})

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.

Step 3: Create a Server-Side Controller


Nowthatwehavedemonstratedsomeinteractivityontheclientside,letsaddsomeserver
interactionnext.LetsgotowheretheJavaclassesare.Controllersarefullystatic.Wedont
instantiatethemandyoucantkeepstateonthem.
1. CreateanewNoteListRowController.javaclassin
src/main/java/org/auraframework/demo/notes/controllers.
2. Copyandpastethefollowingcode.
NoteListRowController.java
packageorg.auraframework.demo.notes.controllers
importorg.auraframework.system.Annotations.AuraEnabled
importorg.auraframework.system.Annotations.Controller
importorg.auraframework.system.Annotations.Key
@Controller
publicclassNoteListRowController{
@AuraEnabled
publicstaticStringecho(@Key("value")Stringvalue){
return"Fromserver:"+value
}

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.

Step 4: Run an Instance of the Action


InAura,wetalkaboutdefinitionsandinstances.Almosteverythingisadefinitionand,inthisstep,
weremakinganactioninstancefromtheactiondefinition.
1. Letsgobacktoourclientsidecontroller,noteListRowController.js.Copyand
pastethecodebelow.
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())
})
}
})

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.

Step 5: Specify the Server-side Controller in the Component


Associatetheserversidecontrollerwiththecomponent.
1. InnoteListRow.cmp,add
controller="java://org.auraframework.demo.notes.controllers.Note
ListRowController"totheroottagofthefile.

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">&nbsp</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

Tutorial #4: Debugging and Testing the Component


YoucanusethebrowserdebuggerwiththedebuggerJavaScriptkeyword,ortheAuradebug
toolifcodeisn'tworkingasyou'dexpect.

Step 1: Use the browser debugger


1. InnoteListRowController.js,addadebuggerstatementtothebeginningofthe
controller.Commentout$A.enqueueAction(action).Welldebugwhatwould
happenifthe$A.enqueueAction(action)callismissing.
noteListRowController.js
({
openNote:function(component,event){
debugger
varaction=component.get("c.echo")
action.setParams({value:component.get("v.note.title")})
action.setCallback(this,function(a){
alert(a.getReturnValue())
})
//$A.enqueueAction(action)
}
})

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.

Step 2: Use the Aura Debug Tool


Inthebrowser,append?aura.debugTool=truetoyourcomponentfile.Thedebugging
windowappearswithtabsforerrors,warnings,andsoon.
http://localhost:8080/auranote/noteList.cmp?aura.debugtool=true

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

Tutorial #5: Building the App


Wehavecreatedacomponentthatdisplaysthenotes.Now,letsaddittotheapplication,
notes.app.Themarkupinthe.appfilelooksfamiliar,justlikewhatwesawinthe.cmpfiles,
excepttheroottagisaura:applicationinsteadofaura:component.

Step 1: Combine the Components together


Afteryoucreatecomponents,putthemina.appfile.TheAuraNoteappusesthenotes.app
file.
1. Opennotes.app.
NoticethatweareusingHTMLtagsaswellasAuracomponents,suchasui:block.
AuratreatsHTMLtagslikefirstclassAuracomponentsandyoucanusemanyHTMLtagsina
componentorapplication.
notes.app
<aura:applicationpreload="auranote"template="auranote:template"
useAppCache="true">
<div>
<header>
<h1>aura:note</h1>
</header>
<ui:blockclass="wrapper"aura:id="block">
<aura:setattribute="left">
<auranote:sidebaraura:id="sidebar"/>
</aura:set>
<auranote:detailsaura:id="details"/>
</ui:block>
</div>
</aura:application>
Youllseethatthistoplevelfilecontainstwocomponents.Thecomponentweworkedoninthe
previoustutorialsbelongstothesidebar,denotedbyauranote:sidebar.
2. Opensidebar.cmp.andnotethatitcontainsauranote:noteList,acomponentwe
workedonintheprevioustutorials.
Tosumupnotes.app,wehaveaheaderatthetop,aui:blockcomponentunderneathit.
Thecomponents,auranote:sidebarandauranote:details,correspondstotheleftand
rightsideoftheapp.

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

Step 2: Extend a Component


Ourtemplatecomponentauranote:templatespecifiesextends="aura:template"in
itstopleveltag.aura:templateisthebasetemplateandithasextensionpointswhichyou
cansetusingaura:setinasubcomponent.
1. Opentemplate.cmp.
2. Setanattributeonthecomponentusingaura:set.Here,wehavesetthetitleattribute
using<aura:setattribute="title"value="AuraNotes"/>.
template.cmp
<aura:componentisTemplate="true"extends="aura:template"
theme="templateCss://auranote.template">
<aura:setattribute="title"value="AuraNotes"/>
//Moreaura:settags
<aura:setattribute="auraInitBlock">
<script>
document.addEventListener('touchmove',function(e){
e.preventDefault()},false)
</script>
</aura:component>

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.

Step 3: Communicate with Events


InAura,eventsarestronglytyped,justlikecomponents.Theyhaveattributes,andtheycan
extendeachother.Thisstepshowsyouhowtofireaneventtodisplaythenotesintherightside
oftheapp,whichisthedetailscomponent,details.cmp.
1. Opendetails.cmp.
25

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

S-ar putea să vă placă și