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

Enyo up and running, 2nd edition

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 (1.16 MB, 100 trang )

www.it-ebooks.info


Enyo:UpandRunning
RoySutton
Beijing•Cambridge•Farnham•Köln•Sebastopol•Tokyo

www.it-ebooks.info


Preface
HTML5technologiesholdthepromiseofprovidingcompellinguserexperiencesthrough
thewebbrowser.TheWebhasevolvedasaplatformfordeliveringcontenttousers
regardlessoftheoperatingsystemtheircomputers(orsmartphones,tablets,andsmart
TVs)use.AsusersspendmoretimeontheWeb,theynotonlyexpecttoreceivecontent
butalsoperformtheactionsoftheirdailylives.TheWebisevolvingfromstaticpagesto
truewebapplications.
EnyoisaJavaScriptframeworkdesignedtohelpdeveloperscreatecompellinginteractive
webapplications(orapps).WhatmakesEnyospecial?Whyshouldyoubeinterestedinit?
I’lltrytotacklethosequestionsand,alongtheway,helpyougetproductiveinEnyo.

www.it-ebooks.info


WhereDidEnyoComeFrom?
EnyogrewoutoftheneedtocreateapplicationsfortheHPTouchPadtablet.Itwas
designedtobeaneasy-to-learn,high-performanceframeworkthatprovidedapleasingand
consistentuserinterface.AsEnyogrew,HPrealizedthatthetechnologiescouldbeapplied
notonlytotabletsbutalsotothelargerscreensofdesktopsandthesmallerscreensof
smartphones.
OnJanuary25,2012,HPannouncedtheyweregoingtoreleaseEnyoasanopensource


projectundertheApache2.0license.DevelopmentmovedtoGitHubandthebroader
JavaScriptcommunitywasinvitedtoparticipate.Sincethattime,Enyohasmaturedand
nowoffersrobusttoolsfordevelopingwebappsonawidevarietyofplatforms.InMarch
of2013,LGElectronicsacquiredthewebOSgroupfromHPandthecoreEnyoteam
focusedonadaptingtheframeworkforcreatingsmartTVapplications.

www.it-ebooks.info


CoreBeliefs
TheEnyoteambelievesverystronglyinthepoweroftheopenWeb.Tothatend,Enyo
embracesthefollowingconcepts:

Enyoanditscodearefreetouse,always.
Enyoisopensource—developmenttakesplaceintheopenandthecommunityis
encouragedtoparticipate.
Enyoistrulycross-platform—youshouldnothavetochoosebetweenmobileand
desktop,orbetweenChromeandInternetExplorer.
Enyoisextensible.
Enyoisbuilttomanagecomplexity—Enyopromotescodereuseandencapsulation.
Enyoislightweightandfast—Enyoisoptimizedformobileanditscoreissmall.

www.it-ebooks.info


What’sEnyoGoodFor?
Enyoisdesignedforcreatingapps.Whileadiscussionofexactlywhatanappiscould
probablyfillabookthissize,whenIsay“apps”I’mreferringtoaninteractiveapplication
thatrunsinawebbrowser(evenifthebrowseritselfmaybetransparenttotheuser).
ThisistosayEnyoisnotdesignedforcreatingwebpages.Enyoappsruninthebrowser

andnotontheserver.Thisdoesn’tmeanEnyocannotinteractwithdatastoredonservers;
itcertainlycan.Anditdoesn’tmeanthatEnyocan’tbeservedtothebrowserbyaweb
server;itcan.

www.it-ebooks.info


WhoIsThisBookFor?
Thisbookiswrittenforwebdeveloperslookingtolearnnewwaysofdeveloping
applicationsorforprogrammerswhoareinterestedinlearningwebappdesign.Itisnot
intendedasan“introductiontoprogramming”course.WhiledesigningwithEnyoiseasy,
IexpectsomefamiliaritywithHTML,CSS,orJavaScript.

www.it-ebooks.info


MinimumRequirements
Theabsoluteminimumrequirementforworkingthroughthebookisawebbrowserthatis
compatiblewithEnyoandaccesstothejsFiddlewebsite.Togetthemostoutofthebook,
IrecommendaPC(Mac,Windows,orLinux),acodeeditor,andamodernwebbrowser.
Awebserver,suchasalocalinstallationofApacheorahostingaccount,canbehelpful
fortesting.GitandNode.jsroundoutthetoolsneededforthefullexperience.
InformationonsettingupyourenvironmenttodevelopEnyoapplicationscanbefoundin
AppendixA.ThisbookwasbasedoffEnyoversion2.5.1,thoughitshouldapplytolater
versions.

www.it-ebooks.info


TypographicConventions

Thefollowingconventionsareusedinthisbook:
Italic
Italindicatesnewterms,URLs,emailaddresses,filenames,andfileextensions.
Constantwidth
CWisusedforprogramlistings,aswellaswithinparagraphstorefertoprogram

elementssuchasvariableorfunctionnames,databases,datatypes,environment
variables,statements,andkeywords.
Constantwidthbold
CWBshowscommandsorothertextthatshouldbetypedliterallybytheuser.
Constantwidthitalic
CWIshowstextthatshouldbereplacedwithuser-suppliedvaluesorbyvalues

determinedbycontext.
TIP
ThisiconprecedesalinktorunnablecodesamplesonjsFiddle.

TIP
Thisiconprecedesatip,suggestion,ornote.

WARNING
Thisiconprecedesawarningorclarificationofaconfusingpoint.

www.it-ebooks.info


UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,ifthisbookincludescode
examples,youmayusethecodeinthisbookinyourprogramsanddocumentation.Youdo
notneedtocontactusforpermissionunlessyou’rereproducingasignificantportionofthe

code.Forexample,writingaprogramthatusesseveralchunksofcodefromthisbook
doesnotrequirepermission.SellingordistributingaCD-ROMofexamplesfromO’Reilly
booksdoesrequirepermission.Answeringaquestionbycitingthisbookandquoting
examplecodedoesnotrequirepermission.Incorporatingasignificantamountofexample
codefromthisbookintoyourproduct’sdocumentationdoesrequirepermission.
Weappreciate,butdonotrequire,attribution.Anattributionusuallyincludesthetitle,
author,publisher,andISBN.Forexample:“Enyo:UpandRunning,2ndEdition,byRoy
Sutton(O’Reilly).Copyright2015RoySutton,978-1-491-92120-3.”
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseorthepermissiongivenabove,
feelfreetocontactusat

www.it-ebooks.info


Safari®BooksOnline
NOTE
SafariBooksOnlineisanon-demanddigitallibrarythatdeliversexpertcontentinbothbookandvideoformfrom
theworld’sleadingauthorsintechnologyandbusiness.

Technologyprofessionals,softwaredevelopers,webdesigners,andbusinessandcreative
professionalsuseSafariBooksOnlineastheirprimaryresourceforresearch,problem
solving,learning,andcertificationtraining.
SafariBooksOnlineoffersarangeofplansandpricingforenterprise,government,
education,andindividuals.
Membershaveaccesstothousandsofbooks,trainingvideos,andprepublication
manuscriptsinonefullysearchabledatabasefrompublisherslikeO’ReillyMedia,
PrenticeHallProfessional,Addison-WesleyProfessional,MicrosoftPress,Sams,Que,
PeachpitPress,FocalPress,CiscoPress,JohnWiley&Sons,Syngress,Morgan
Kaufmann,IBMRedbooks,Packt,AdobePress,FTPress,Apress,Manning,NewRiders,
McGraw-Hill,Jones&Bartlett,CourseTechnology,andhundredsmore.Formore

informationaboutSafariBooksOnline,pleasevisitusonline.

www.it-ebooks.info


HowtoContactUs
Pleaseaddresscommentsandquestionsconcerningthisbooktothepublisher:
O’ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
800-998-9938(intheUnitedStatesorCanada)
707-829-0515(internationalorlocal)
707-829-0104(fax)

Wehaveawebpageforthisbook,wherewelisterrata,examples,andanyadditional
information.Youcanaccessthispageat />Tocommentorasktechnicalquestionsaboutthisbook,sendemailto

Formoreinformationaboutourbooks,courses,conferences,andnews,seeourwebsiteat
.
FindusonFacebook: />FollowusonTwitter: />WatchusonYouTube: />
www.it-ebooks.info


Acknowledgments
FirstandforemostIwouldliketothankmywifeConnieElliottandsonIanfortheirhelp
andforbearanceasIpreparedthebookyounowhold(evenifonlyvirtually).Next,I
wouldliketothanktheteamatO’Reilly,inparticularSimonSt.LaurentandMegan
Blanchette,whoreallymadetheprocessofgettingthisbookfinishedaspainlessas
possible,KaraEbrahim,whoslewtyposandwrangledwordsintotheirproperplaces,and
KristenBrown,whomadethesecondeditionpainless.V.LElliottplayedaspecialrolein

helpingbringstructuretotheoriginalthoughtsforthisbook.Further,thankstothose
readers(technicalandotherwise)whohelpedreducethenumberoferrorsherein.Special
thankstoBenCombeeandArthurThorntonfortheireffortsinspottingtechnicalerrorsin
thefirstedition.ManythankstoJimTangforkeepingtheofficialEnyodocumentationin
orderandforspottingerrorsinthesecondedition.I’dalsoliketoacknowledgethedozens
ofindividualsatHPandLG(fromSiliconValleytoFrance,Korea,andIndia)whohave
hadahandindeveloping,testing,supportingandevangelizingEnyo,andournumerous
contributorsfromthebroaderEnyocommunity.Therearefartoomanypeopletoname
here,butwithouttheirhardworkandpassion,Enyowouldnotbewhatitistoday.Finally,
specialmentiongoestothecreatorsofEnyo,ScottMilesandSteveOrvell,withoutwhom
thisbookwouldn’texist.

www.it-ebooks.info


ContentUpdates
January8,2015
AlothashappenedwithEnyosincethefirsteditionofthebook.Mostnotablearethe
additionofdatabindingtothecore(BindingsandObservers)andthenewMoonstone
smartTVUIlibrary(MoonstoneControls).Otherchangesincludethedeprecationof
publishedpropertiesandtheintroductionofthenewset()andget()methods
(Properties),theswitchfromg11ntoiLibforinternationalization(GoingGlobal),andthe
newApplicationobject(Application).Ifyoureadthepreviouseditionofthisbook,you
willwanttofocusonthenewchapter(Chapter5)andthencheckindividualchaptersfor
changes.

www.it-ebooks.info


Chapter1.LightItUp

OneofthebestwaystogetfamiliarwithEnyoistogetatasteforwhatanEnyoapplooks
like.We’regoingtodoalittlevirtualtimetravelandfast-forwardtoapointjustafteryou
finishreadingthisbook.We’regoingtoimagineyouworkforasoftwarecompanythat
producesappsforcustomers.

www.it-ebooks.info


ANewProject
YourbossjustcameandtoldyouthatheneedsalightimplementedinJavaScriptright
away.Hetellsyouthatyourcompany’sbestclientneedstobeabletoembedalightapp
ontheirwebpageanditmustworkcross-platform.Fortunately,you’vejustfinished
readingthisbookandareexcitedtouseEnyoonaproject.
Youdecidetomakeaniceyellowcircleanddrawthatonthescreen:
enyo.ready(function(){
enyo.kind({
name:‘Light’,
style:‘width:50px;height:50px;border-radius:50%;’+
‘background:yellow;’
});
newenyo.Application({name:‘app’,view:‘Light’});
});

TIP
Tryitout:jsFiddle.

WithEnyo,youdon’t(usually)havetoworryabouttheHTMLthatmakesupyourapp.
Enyocreatesitallforyou.Inthiscase,you’vecreatedanewkind(Enyo’sbuildingblocks
arecalledkinds,yourecall)calledLightandyouusedalittleCSSmagicyoufoundon
theWebtodrawacirclewithouttheuseofimagesorthecanvas.

WhileusingEnyo’sApplicationcomponent,youplacedthenewkindintothepage’s
bodyelement,causingEnyotocreatetheHTML.Yourecallthattheenyo.ready()
methodexecutescodewhentheframeworkisfullyloaded.YouinspecttheHTMLforthe
circleusingyourfavoritebrowser’sdebuggingtoolandseethatEnyocreatedadiv
elementforyouandappliedthestyleyousupplied.Notbadforafewminutes’work.

www.it-ebooks.info


Improvements
Nowthatyou’refeelinggoodaboutwhatyoudid,youcheckinthefirstversionofthe
codetothecompany’ssourcecodemanagementsystem.Youknowfrompastexperience
thatsaleswillprobablyneedthelightinmorecolorsthanyellow.So,youdecidetouse
Enyo’spropertyfeaturetosetthecolorwhenthekindiscreated:
enyo.kind({
name:‘Light’,
color:‘yellow’,
style:‘width:50px;height:50px;border-radius:50%;’,
create:function(){
this.inherited(arguments);
this.colorChanged();
},
colorChanged:function(oldValue){
this.applyStyle(‘background-color’,this.color);
}
});

TIP
Tryitout:jsFiddle.


TIP
Thiscode(andthefollowingsamples)doesnotincludetheenyo.ready()lineandtheinstantiationofthe
Applicationkind,butyou’llstillneedit.We’llonlyfocusontheareasthatchanged.

Younotethatyou’veaddedadefaultcolorforthelight,incasenoneisdefined,and
you’veaddedafunctionthatEnyowillcallifanyoneupdatesthelightcolorafterthekind
hasbeencreated.Youhadtoaddsomecodetothecreate()functionthatEnyocallson
allcomponentssothatyoucansettheinitialcolor.First,youtestthatyoucansetthecolor
atcreatetimebypassinginaJavaScriptobjectwiththecolorvalueyouwant:
newenyo.Application({name:‘app’,view:{kind:‘Light’,color:‘green’}});

Lookslikethatworksasexpected.Nowyoucantestthatyoucansetthecolorafter
creation:
varapp=newenyo.Application({name:‘app’,view:Light});
app.set(‘view.color’,‘blue’);

TIP
Tryitout:jsFiddle.

Yourememberthatwhenyouuseset(),EnyowillautomaticallycallthecolorChanged()
methodforyouwhenthecolorchanges.Lookslikethatworkswell,too.
Youcheckinthelatestversionofthecodeandshootane-mailofftoyourboss.Your
latestchangeaddedabitmorecodebutyouknowthatyou’llbeabletousethatlight
componentagainandagain,regardlessofwhatcolorsalespromises.

www.it-ebooks.info


Curveball
Notlongafteryousendoffthee-mail,thephonerings.Yourbossexplainsthatsales

finallylethimknowthatthelighttheyneededwasactuallyatrafficlight,withredonthe
top,yellowinthemiddle,andgreenonthebottom.
Fortunately,you’vedonethehardwork.Gettingthetrafficlightdoneshouldbeabreeze
now.YourecallthatEnyosupportscomposition,allowingyoutomakeanewkindby
combiningtogetherotherkinds.Divingbackintothecode,youcreateanew
TrafficLightkind:
enyo.kind({
name:‘TrafficLight’,
components:[
{name:‘stop’,kind:‘Light’,color:‘red’},
{name:‘slow’,kind:‘Light’,color:‘yellow’},
{name:‘go’,kind:‘Light’,color:‘green’}
]
});

TIP
Tryitout:jsFiddle.

Notbad,ifyoudosaysoyourself.YoureusedtheLightkindyoucreatedandyoudidn’t
havetocopyallthatcodeoverandover.Youpushyourchangesup,shootanothere-mail
offtoyourbossandwaitforthephonetoringagain.

www.it-ebooks.info


QAontheLine
Thenextcallisnot,surprisingly,fromyourboss,butfromtheQAdepartment.Theydid
sometestingwiththelightsandfoundthattheydon’tturnoff.Theymentionsomething
aboutthespecsforthelight,sayingthattappingthelightshouldtoggleitonandoff.
Whilewonderinghowtheymanagedtogetaholdofspecsyou’dneverseen,youbegin

thinkingabouthowyou’llimplementthat.Youquicklyhangupafteraskingforacopyof
thespecs.
YourememberthatEnyohasaneventsystemthatallowsyoutorespondtovariousevents
thatoccur.Youcanaddanewpropertyforthepowerstateofthelightandyoucantoggle
itwhenyoureceiveatapevent(aneventyouknowisoptimizedtoperformwellon
mobiledeviceswithtouchevents).Afterthinkingsomemoreabouttheproblem,you
realizeyoudon’treallywanttochangeyourexistinglightkind.YourememberthatEnyo
supportsinheritance,allowingyoutocreateanewlightthathasallthesamebehaviorsas
yourexistinglight,plusthenewbehaviorsyouneed:
enyo.kind({
name:‘PoweredLight’,
kind:‘Light’,
powered:true,
handlers:{
‘ontap’:‘tapped’
},
create:function(){
this.inherited(arguments);
this.poweredChanged();
},
tapped:function(sender,event){
this.set(‘powered’,!this.get(‘powered’));
},
poweredChanged:function(oldValue){
this.applyStyle(‘opacity’,this.powered?‘1’:‘0.2’);
}
});

TIP
Tryitout:jsFiddle.


Youmadeuseofthehandlersblocktoaddtheeventsyouwanttolistenforandspecified
thenameofthemethodyouwantedtocall.YourecallthatinEnyo,youusethenameof
theeventinsteadoftheeventitselfbecauseEnyowillautomaticallybindthemethodsto
eachinstanceofyourkindsoitcanaccessthemethodsanddataofyourkind’sinstance.
Inyourtaphandler,youusedthepartnertotheset()method,get(),toretrievethe
currentvalueofthepoweredpropertyandtoggleit.InthepoweredChanged()function,
youapplyalittleopacitytothelighttogiveitanicelookwhenit’spoweredoff(youcan
readalocalpropertydirectlywithoutget()).YouupdatetheTrafficLightkind,giveita
quicktestinthebrowser,andverifythateverythinglooksgood.

www.it-ebooks.info


TheE-mail
Justafteryoucommitthelatestchanges,youreceiveacopyofthespecsfromQA.Looks
likeyou’vegoteverythingcoveredexceptforaloggingfeature.Thespecscallforalogto
bemaintainedofwhichlightwasactivatedordeactivatedandthetimeoftheevent.
Events,huh?Soundslikeit’stimetorevisitEnyoevents.Yourecallfromyourtraining
thatEnyoallowskindstocreatetheirownevents,towhichotherkindscansubscribe.
YouquicklyaddaneweventtothePoweredLightkindcalledonStateChanged.Youknow
thatEnyoautomaticallycreatesamethodcalleddoStateChanged()thatyoucancallto
sendtheeventtoasubscriber.Youquicklyaddtherelevantcode:
enyo.kind({
name:‘PoweredLight’,
kind:‘Light’,
powered:true,
events:{
‘onStateChanged’:”
},

handlers:{
‘ontap’:‘tapped’
},
create:function(){
this.inherited(arguments);
this.poweredChanged();
},
tapped:function(sender,event){
this.set(‘powered’,!this.get(‘powered’));
},
poweredChanged:function(oldValue){
this.applyStyle(‘opacity’,this.powered?‘1’:‘0.2’);
this.doStateChanged({powered:this.powered});
}
});

NowyoujustneedtosubscribetotheeventintheTrafficLightkind.Youcould,of
course,subscribetoonStateChangedineachLightdefinition,butyourememberthatthe
handlersblockletsyousubscribetoeventsakindreceivesregardlessofwhichchild
originatesthem.Youknowyoucanusethesenderparametertochecktoseewhichlight
senttheeventandyoucanusetheeventparametertoaccesstheobjectsentbythelight:
enyo.kind({
name:‘TrafficLight’,
handlers:{
‘onStateChanged’:‘logStateChanged’
},
components:[
{name:‘stop’,kind:‘PoweredLight’,color:‘red’},
{name:‘slow’,kind:‘PoweredLight’,color:‘yellow’},
{name:‘go’,kind:‘PoweredLight’,color:‘green’}

],
logStateChanged:function(sender,event){
enyo.log(sender.name+‘powered‘+(event.powered?‘on’:‘off’)
+‘at‘+newDate());
}
});

TIP
Tryitout:jsFiddle.

Aquickloggingfunctionandahandlersblocklaterandthingsarestartingtolook
finished.AfterthecodehasbeencheckedinandQAhassignedoff,youcanrelaxand
startplanningthatvacation—asifthatwillhappen.

www.it-ebooks.info


Summary
We’vejustworkedthroughasimpleEnyoapplicationandexploredseveralofthe
conceptsthatmakeusingEnyoproductive.Wesawhoweasyitistoquicklyprototypean
applicationandhowEnyokeptthecodemaintainableandpotentiallyreusable.Withthis
foundation,we’llbeabletoexplorethedeeperconceptsofEnyointhecomingchapters.

www.it-ebooks.info


Chapter2.CoreConcepts

www.it-ebooks.info



Introduction
Inthischapter,we’llcoverthecoreconceptsofEnyothatweonlytouchedoninthelast
chapter.Youwillbeabletowritepowerfulappsafterabsorbingtheinformationinjustthis
chapter.We’llgoovertheconceptsonebyoneandillustrateeachwithcodeyoucanrun
inyourbrowser.
OneofthedrivingideasbehindEnyoisthatyoucancombinesimplepiecestocreate
morecomplexones.Enyointroducesfourconceptstoassistyou:kinds,encapsulation,
components,andlayout.We’llcovercomponentsandlayoutmorethoroughlyinChapter3
andChapter4,respectively.

www.it-ebooks.info


Kinds
Enyoisanobject-orientedframework.ItistruethateveryJavaScriptapplication
regardlessofframework(orlackthereof)containsobjects.However,Enyo’scorefeatures
providealayerontopofJavaScriptthatmakesiteasiertoexpressobject-oriented
conceptssuchasinheritanceandencapsulation.
InEnyo,kindsarethebuildingblocksthatmakeupapps.Thewidgetsthatappearon
screenareinstancesofkinds,asaretheobjectsthatperformAjaxrequests.Kindsarenot
strictlyformakingvisualcomponents.Basically,kindsprovideatemplatefromwhichthe
actualobjectsthatmakeupyourapparegenerated.

BeKind
Oneofthesimplestpossibledeclarationsforakindis:
enyo.kind({name:‘MyKind’});

NAMES
Kindsdon’tevenneednames.Enyowillautomaticallyassignuniquenames,thoughyouwon’tknowwhatthey

are.AnonymouskindsareoftenusedinEnyoapps.YousawoneinChapter1whenthecolorofthelightwasset
togreenintheviewdeclaration.
Top-levelkinds(thosedeclaredoutsideofotherkinds)automaticallygetaglobalobjectcreatedwiththatname
(forexample,Lightinthepreviouschapter).Itispossibletoputkindsintoanamespacebyseparatingnameparts
withperiods.Forexample,usingname:myApp.LightwillresultinamyAppobjectwithaLightmember.
Namespacesprovideagoodmechanismforpreventingnamingconflictswithyourapps,particularlywhenusing
reusablecomponents.
Asaconvention,weuseuppercasenamesforkinddefinitionsandlowercasenamesforinstancesofkinds(those
kindsdeclaredinthecomponentsblock).

enyo.kind()isa“factory”forcreatingnewkinds.Inthiscase,wegetanewobjectthat
inheritsfromtheEnyocontrolkind,enyo.Control.Controlisthebasecomponentfor

objectsthatwillrenderwhenplacedonawebpage.
Whencreatingkinds,youpassinanobjectthatdefinesthestartingstateofthekindas
wellasanymethodsitwillneed.Forexample,controlkindshaveacontentproperty:
enyo.kind({name:‘MyKind’,content:‘HelloWorld!’});

AsyousawinChapter1,whenrenderedontoapagethiscodewillcreateadivtagwith
thecontentplacedinit.Torenderthisintoabodyonawebpage,youspecifyitasthe
viewofanApplication.
Wecanaddbehaviorstoourkindbyaddingmethods(forexample,thetaphandling
methodweaddedtotheLightkind).Asyoumayrecall,wereferencedthemethodname
inthehandlersblockusingastring.WeusestringssoEnyocanbindourmethodsas
kindsarecreated.

www.it-ebooks.info


Encapsulation

Encapsulationisafancycomputersciencetermthatreferstorestrictingoutsideobjects’
accesstoanobject’sinternalfeaturesthroughprovidinganinterfaceforinteractingwith
thedatacontainedintheobject.JavaScriptdoesnothaveverymanywaystoprohibit
accesstoanobject’sdataandmethodsfromoutside,soEnyopromotesencapsulationby
givingprogrammersvarioustoolsandconventions.
Byconvention,Enyokindsshouldhavenodependenciesontheirparentorsiblingkinds
andtheyshouldnotrelyonimplementationdetailsoftheirchildren.Whileitiscertainly
possibletocreateEnyokindsthatviolatetheserules,Enyoprovidesseveralmechanisms
tomakethatunnecessary.Thosemechanismsincludepropertiesandevents.
Bybeingawareofencapsulation,Enyoprogrammerscantapintothebenefitsofcode
reuse,easytesting,anddrop-incomponents.

Properties
Kindscandeclareproperties(forexample,thecolorandpoweredpropertiesfrom
Chapter1).Thepropertysystemallowsforsomeverypowerfulfeatures,suchastwo-way
databindingandnotificationforchangestovalues.We’lldiscussthebasicfeaturesof
propertiesfirstandthendiveintothemoreadvancedfeaturesofbindingsandobservers.
BasicProperties
Propertiesareaccessedusingtheget()andset()methodsdefinedonallkinds.In
addition,thereisamechanismfortrackingchangestoproperties.Propertiesdon’tneedto
evenbedeclaredonakind,thoughyoushouldatleastdocumenttheirpresencesothat
usersofyourkinds(includingyourself)willknow(remember)thattheyexist.
enyo.kind({
name:‘MyKind’,
myValue:3
});

Asyoucansee,youalsospecifyadefaultvalueforaproperty.WithinMyKindyoucan
readthepropertydirectlyusingthis.myValue.WhenyouareaccessingmyValue
externally(e.g.,fromaparentcontrol),youshouldusetheget()orset()methods.

Wheneverthevalueismodifiedusingthesetter,Enyowillautomaticallycalla“changed”
method.Inthiscase,thechangedmethodismyValueChanged().Whencalled,thechanged
methodwillbepassedthepreviousvalueofthepropertyasanargument.
WARNING
Theset()methoddoesnotcallthechangedmethodifthevaluetobesetisthesameasthecurrentvalue.You
can,however,overridethisbehaviorbypassingatruthyvalueasathirdargumenttoset().

Ifyoulookbacktoourearlierdiscussiononkindsyoumayhavenoticedthatwepassedin
somevaluesforpropertieswhenweweredeclaringourkinds.Thosevaluessettheinitial
contentsofthoseproperties.Enyodoesnotcallthechangedmethodduringconstruction.
Ifyouhavespecialprocessingthatneedstooccur,youshouldcallthechangedmethod
directlywithincreate():
enyo.kind({
name:‘MyKind’,
myValue:3,
create:function(){

www.it-ebooks.info


×