ember-latest.js 607 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800
  1. // Version: v1.0.pre
  2. // Last commit: 7955b85 (2012-08-03 14:50:17 -0700)
  3. (function() {
  4. /*global __fail__*/
  5. if ('undefined' === typeof Ember) {
  6. Ember = {};
  7. if ('undefined' !== typeof window) {
  8. window.Em = window.Ember = Em = Ember;
  9. }
  10. }
  11. Ember.ENV = 'undefined' === typeof ENV ? {} : ENV;
  12. if (!('MANDATORY_SETTER' in Ember.ENV)) {
  13. Ember.ENV.MANDATORY_SETTER = true; // default to true for debug dist
  14. }
  15. /**
  16. Define an assertion that will throw an exception if the condition is not
  17. met. Ember build tools will remove any calls to Ember.assert() when
  18. doing a production build. Example:
  19. // Test for truthiness
  20. Ember.assert('Must pass a valid object', obj);
  21. // Fail unconditionally
  22. Ember.assert('This code path should never be run')
  23. @static
  24. @function
  25. @param {String} desc
  26. A description of the assertion. This will become the text of the Error
  27. thrown if the assertion fails.
  28. @param {Boolean} test
  29. Must be truthy for the assertion to pass. If falsy, an exception will be
  30. thrown.
  31. */
  32. Ember.assert = function(desc, test) {
  33. if (!test) throw new Error("assertion failed: "+desc);
  34. };
  35. /**
  36. Display a warning with the provided message. Ember build tools will
  37. remove any calls to Ember.warn() when doing a production build.
  38. @static
  39. @function
  40. @param {String} message
  41. A warning to display.
  42. @param {Boolean} test
  43. An optional boolean. If falsy, the warning will be displayed.
  44. */
  45. Ember.warn = function(message, test) {
  46. if (!test) {
  47. Ember.Logger.warn("WARNING: "+message);
  48. if ('trace' in Ember.Logger) Ember.Logger.trace();
  49. }
  50. };
  51. /**
  52. Display a deprecation warning with the provided message and a stack trace
  53. (Chrome and Firefox only). Ember build tools will remove any calls to
  54. Ember.deprecate() when doing a production build.
  55. @static
  56. @function
  57. @param {String} message
  58. A description of the deprecation.
  59. @param {Boolean} test
  60. An optional boolean. If falsy, the deprecation will be displayed.
  61. */
  62. Ember.deprecate = function(message, test) {
  63. if (Ember && Ember.TESTING_DEPRECATION) { return; }
  64. if (arguments.length === 1) { test = false; }
  65. if (test) { return; }
  66. if (Ember && Ember.ENV.RAISE_ON_DEPRECATION) { throw new Error(message); }
  67. var error;
  68. // When using new Error, we can't do the arguments check for Chrome. Alternatives are welcome
  69. try { __fail__.fail(); } catch (e) { error = e; }
  70. if (Ember.LOG_STACKTRACE_ON_DEPRECATION && error.stack) {
  71. var stack, stackStr = '';
  72. if (error['arguments']) {
  73. // Chrome
  74. stack = error.stack.replace(/^\s+at\s+/gm, '').
  75. replace(/^([^\(]+?)([\n$])/gm, '{anonymous}($1)$2').
  76. replace(/^Object.<anonymous>\s*\(([^\)]+)\)/gm, '{anonymous}($1)').split('\n');
  77. stack.shift();
  78. } else {
  79. // Firefox
  80. stack = error.stack.replace(/(?:\n@:0)?\s+$/m, '').
  81. replace(/^\(/gm, '{anonymous}(').split('\n');
  82. }
  83. stackStr = "\n " + stack.slice(2).join("\n ");
  84. message = message + stackStr;
  85. }
  86. Ember.Logger.warn("DEPRECATION: "+message);
  87. };
  88. /**
  89. Display a deprecation warning with the provided message and a stack trace
  90. (Chrome and Firefox only) when the wrapped method is called.
  91. Ember build tools will not remove calls to Ember.deprecateFunc(), though
  92. no warnings will be shown in production.
  93. @static
  94. @function
  95. @param {String} message
  96. A description of the deprecation.
  97. @param {Function} func
  98. The function to be deprecated.
  99. */
  100. Ember.deprecateFunc = function(message, func) {
  101. return function() {
  102. Ember.deprecate(message);
  103. return func.apply(this, arguments);
  104. };
  105. };
  106. window.ember_assert = Ember.deprecateFunc("ember_assert is deprecated. Please use Ember.assert instead.", Ember.assert);
  107. window.ember_warn = Ember.deprecateFunc("ember_warn is deprecated. Please use Ember.warn instead.", Ember.warn);
  108. window.ember_deprecate = Ember.deprecateFunc("ember_deprecate is deprecated. Please use Ember.deprecate instead.", Ember.deprecate);
  109. window.ember_deprecateFunc = Ember.deprecateFunc("ember_deprecateFunc is deprecated. Please use Ember.deprecateFunc instead.", Ember.deprecateFunc);
  110. })();
  111. // Version: v1.0.pre
  112. // Last commit: 7955b85 (2012-08-03 14:50:17 -0700)
  113. (function() {
  114. // ==========================================================================
  115. // Project: Ember Metal
  116. // Copyright: ©2011 Strobe Inc. and contributors.
  117. // License: Licensed under MIT license (see license.js)
  118. // ==========================================================================
  119. /*globals Em:true ENV */
  120. if ('undefined' === typeof Ember) {
  121. // Create core object. Make it act like an instance of Ember.Namespace so that
  122. // objects assigned to it are given a sane string representation.
  123. Ember = {};
  124. }
  125. /**
  126. @namespace
  127. @name Ember
  128. @version 1.0.pre
  129. All Ember methods and functions are defined inside of this namespace.
  130. You generally should not add new properties to this namespace as it may be
  131. overwritten by future versions of Ember.
  132. You can also use the shorthand "Em" instead of "Ember".
  133. Ember-Runtime is a framework that provides core functions for
  134. Ember including cross-platform functions, support for property
  135. observing and objects. Its focus is on small size and performance. You can
  136. use this in place of or along-side other cross-platform libraries such as
  137. jQuery.
  138. The core Runtime framework is based on the jQuery API with a number of
  139. performance optimizations.
  140. */
  141. // aliases needed to keep minifiers from removing the global context
  142. if ('undefined' !== typeof window) {
  143. window.Em = window.Ember = Em = Ember;
  144. }
  145. // Make sure these are set whether Ember was already defined or not
  146. Ember.isNamespace = true;
  147. Ember.toString = function() { return "Ember"; };
  148. /**
  149. @static
  150. @type String
  151. @default '1.0.pre'
  152. @constant
  153. */
  154. Ember.VERSION = '1.0.pre';
  155. /**
  156. @static
  157. @type Hash
  158. @constant
  159. Standard environmental variables. You can define these in a global `ENV`
  160. variable before loading Ember to control various configuration
  161. settings.
  162. */
  163. Ember.ENV = Ember.ENV || ('undefined' === typeof ENV ? {} : ENV);
  164. Ember.config = Ember.config || {};
  165. // ..........................................................
  166. // BOOTSTRAP
  167. //
  168. /**
  169. @static
  170. @type Boolean
  171. @default true
  172. @constant
  173. Determines whether Ember should enhances some built-in object
  174. prototypes to provide a more friendly API. If enabled, a few methods
  175. will be added to Function, String, and Array. Object.prototype will not be
  176. enhanced, which is the one that causes most troubles for people.
  177. In general we recommend leaving this option set to true since it rarely
  178. conflicts with other code. If you need to turn it off however, you can
  179. define an ENV.EXTEND_PROTOTYPES config to disable it.
  180. */
  181. Ember.EXTEND_PROTOTYPES = (Ember.ENV.EXTEND_PROTOTYPES !== false);
  182. /**
  183. @static
  184. @type Boolean
  185. @default true
  186. @constant
  187. Determines whether Ember logs a full stack trace during deprecation warnings
  188. */
  189. Ember.LOG_STACKTRACE_ON_DEPRECATION = (Ember.ENV.LOG_STACKTRACE_ON_DEPRECATION !== false);
  190. /**
  191. @static
  192. @type Boolean
  193. @default Ember.EXTEND_PROTOTYPES
  194. @constant
  195. Determines whether Ember should add ECMAScript 5 shims to older browsers.
  196. */
  197. Ember.SHIM_ES5 = (Ember.ENV.SHIM_ES5 === false) ? false : Ember.EXTEND_PROTOTYPES;
  198. /**
  199. @static
  200. @type Boolean
  201. @default true
  202. @constant
  203. Determines whether computed properties are cacheable by default.
  204. This option will be removed for the 1.1 release.
  205. When caching is enabled by default, you can use `volatile()` to disable
  206. caching on individual computed properties.
  207. */
  208. Ember.CP_DEFAULT_CACHEABLE = (Ember.ENV.CP_DEFAULT_CACHEABLE !== false);
  209. /**
  210. @static
  211. @type Boolean
  212. @default true
  213. @constant
  214. Determines whether views render their templates using themselves
  215. as the context, or whether it is inherited from the parent. This option
  216. will be removed in the 1.1 release.
  217. If you need to update your application to use the new context rules, simply
  218. prefix property access with `view.`:
  219. // Before:
  220. {{#each App.photosController}}
  221. Photo Title: {{title}}
  222. {{#view App.InfoView contentBinding="this"}}
  223. {{content.date}}
  224. {{content.cameraType}}
  225. {{otherViewProperty}}
  226. {{/view}}
  227. {{/each}}
  228. // After:
  229. {{#each App.photosController}}
  230. Photo Title: {{title}}
  231. {{#view App.InfoView}}
  232. {{date}}
  233. {{cameraType}}
  234. {{view.otherViewProperty}}
  235. {{/view}}
  236. {{/each}}
  237. */
  238. Ember.VIEW_PRESERVES_CONTEXT = (Ember.ENV.VIEW_PRESERVES_CONTEXT !== false);
  239. /**
  240. Empty function. Useful for some operations.
  241. @returns {Object}
  242. @private
  243. */
  244. Ember.K = function() { return this; };
  245. /**
  246. @namespace
  247. @name window
  248. @description The global window object
  249. */
  250. // Stub out the methods defined by the ember-debug package in case it's not loaded
  251. if ('undefined' === typeof Ember.assert) { Ember.assert = Ember.K; }
  252. if ('undefined' === typeof Ember.warn) { Ember.warn = Ember.K; }
  253. if ('undefined' === typeof Ember.deprecate) { Ember.deprecate = Ember.K; }
  254. if ('undefined' === typeof Ember.deprecateFunc) {
  255. Ember.deprecateFunc = function(_, func) { return func; };
  256. }
  257. // These are deprecated but still supported
  258. if ('undefined' === typeof ember_assert) { window.ember_assert = Ember.K; }
  259. if ('undefined' === typeof ember_warn) { window.ember_warn = Ember.K; }
  260. if ('undefined' === typeof ember_deprecate) { window.ember_deprecate = Ember.K; }
  261. if ('undefined' === typeof ember_deprecateFunc) {
  262. /** @private */
  263. window.ember_deprecateFunc = function(_, func) { return func; };
  264. }
  265. // ..........................................................
  266. // LOGGER
  267. //
  268. /**
  269. @class
  270. Inside Ember-Metal, simply uses the window.console object.
  271. Override this to provide more robust logging functionality.
  272. */
  273. Ember.Logger = window.console || { log: Ember.K, warn: Ember.K, error: Ember.K, info: Ember.K, debug: Ember.K };
  274. })();
  275. (function() {
  276. /*jshint newcap:false*/
  277. // NOTE: There is a bug in jshint that doesn't recognize `Object()` without `new`
  278. // as being ok unless both `newcap:false` and not `use strict`.
  279. // https://github.com/jshint/jshint/issues/392
  280. // Testing this is not ideal, but we want to use native functions
  281. // if available, but not to use versions created by libraries like Prototype
  282. /** @private */
  283. var isNativeFunc = function(func) {
  284. // This should probably work in all browsers likely to have ES5 array methods
  285. return func && Function.prototype.toString.call(func).indexOf('[native code]') > -1;
  286. };
  287. // From: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/map
  288. /** @private */
  289. var arrayMap = isNativeFunc(Array.prototype.map) ? Array.prototype.map : function(fun /*, thisp */) {
  290. //"use strict";
  291. if (this === void 0 || this === null) {
  292. throw new TypeError();
  293. }
  294. var t = Object(this);
  295. var len = t.length >>> 0;
  296. if (typeof fun !== "function") {
  297. throw new TypeError();
  298. }
  299. var res = new Array(len);
  300. var thisp = arguments[1];
  301. for (var i = 0; i < len; i++) {
  302. if (i in t) {
  303. res[i] = fun.call(thisp, t[i], i, t);
  304. }
  305. }
  306. return res;
  307. };
  308. // From: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/foreach
  309. /** @private */
  310. var arrayForEach = isNativeFunc(Array.prototype.forEach) ? Array.prototype.forEach : function(fun /*, thisp */) {
  311. //"use strict";
  312. if (this === void 0 || this === null) {
  313. throw new TypeError();
  314. }
  315. var t = Object(this);
  316. var len = t.length >>> 0;
  317. if (typeof fun !== "function") {
  318. throw new TypeError();
  319. }
  320. var thisp = arguments[1];
  321. for (var i = 0; i < len; i++) {
  322. if (i in t) {
  323. fun.call(thisp, t[i], i, t);
  324. }
  325. }
  326. };
  327. /** @private */
  328. var arrayIndexOf = isNativeFunc(Array.prototype.indexOf) ? Array.prototype.indexOf : function (obj, fromIndex) {
  329. if (fromIndex === null || fromIndex === undefined) { fromIndex = 0; }
  330. else if (fromIndex < 0) { fromIndex = Math.max(0, this.length + fromIndex); }
  331. for (var i = fromIndex, j = this.length; i < j; i++) {
  332. if (this[i] === obj) { return i; }
  333. }
  334. return -1;
  335. };
  336. Ember.ArrayPolyfills = {
  337. map: arrayMap,
  338. forEach: arrayForEach,
  339. indexOf: arrayIndexOf
  340. };
  341. var utils = Ember.EnumerableUtils = {
  342. map: function(obj, callback, thisArg) {
  343. return obj.map ? obj.map.call(obj, callback, thisArg) : arrayMap.call(obj, callback, thisArg);
  344. },
  345. forEach: function(obj, callback, thisArg) {
  346. return obj.forEach ? obj.forEach.call(obj, callback, thisArg) : arrayForEach.call(obj, callback, thisArg);
  347. },
  348. indexOf: function(obj, element, index) {
  349. return obj.indexOf ? obj.indexOf.call(obj, element, index) : arrayIndexOf.call(obj, element, index);
  350. },
  351. indexesOf: function(obj, elements) {
  352. return elements === undefined ? [] : utils.map(elements, function(item) {
  353. return utils.indexOf(obj, item);
  354. });
  355. },
  356. removeObject: function(array, item) {
  357. var index = utils.indexOf(array, item);
  358. if (index !== -1) { array.splice(index, 1); }
  359. }
  360. };
  361. if (Ember.SHIM_ES5) {
  362. if (!Array.prototype.map) {
  363. /** @private */
  364. Array.prototype.map = arrayMap;
  365. }
  366. if (!Array.prototype.forEach) {
  367. /** @private */
  368. Array.prototype.forEach = arrayForEach;
  369. }
  370. if (!Array.prototype.indexOf) {
  371. /** @private */
  372. Array.prototype.indexOf = arrayIndexOf;
  373. }
  374. }
  375. })();
  376. (function() {
  377. // ==========================================================================
  378. // Project: Ember Metal
  379. // Copyright: ©2011 Strobe Inc. and contributors.
  380. // License: Licensed under MIT license (see license.js)
  381. // ==========================================================================
  382. /*globals Node */
  383. /**
  384. @class
  385. Platform specific methods and feature detectors needed by the framework.
  386. @name Ember.platform
  387. */
  388. var platform = Ember.platform = {};
  389. /**
  390. Identical to Object.create(). Implements if not available natively.
  391. @memberOf Ember.platform
  392. @name create
  393. */
  394. Ember.create = Object.create;
  395. if (!Ember.create) {
  396. /** @private */
  397. var K = function() {};
  398. Ember.create = function(obj, props) {
  399. K.prototype = obj;
  400. obj = new K();
  401. if (props) {
  402. K.prototype = obj;
  403. for (var prop in props) {
  404. K.prototype[prop] = props[prop].value;
  405. }
  406. obj = new K();
  407. }
  408. K.prototype = null;
  409. return obj;
  410. };
  411. Ember.create.isSimulated = true;
  412. }
  413. /** @private */
  414. var defineProperty = Object.defineProperty;
  415. var canRedefineProperties, canDefinePropertyOnDOM;
  416. // Catch IE8 where Object.defineProperty exists but only works on DOM elements
  417. if (defineProperty) {
  418. try {
  419. defineProperty({}, 'a',{get:function(){}});
  420. } catch (e) {
  421. /** @private */
  422. defineProperty = null;
  423. }
  424. }
  425. if (defineProperty) {
  426. // Detects a bug in Android <3.2 where you cannot redefine a property using
  427. // Object.defineProperty once accessors have already been set.
  428. /** @private */
  429. canRedefineProperties = (function() {
  430. var obj = {};
  431. defineProperty(obj, 'a', {
  432. configurable: true,
  433. enumerable: true,
  434. get: function() { },
  435. set: function() { }
  436. });
  437. defineProperty(obj, 'a', {
  438. configurable: true,
  439. enumerable: true,
  440. writable: true,
  441. value: true
  442. });
  443. return obj.a === true;
  444. })();
  445. // This is for Safari 5.0, which supports Object.defineProperty, but not
  446. // on DOM nodes.
  447. /** @private */
  448. canDefinePropertyOnDOM = (function(){
  449. try {
  450. defineProperty(document.createElement('div'), 'definePropertyOnDOM', {});
  451. return true;
  452. } catch(e) { }
  453. return false;
  454. })();
  455. if (!canRedefineProperties) {
  456. /** @private */
  457. defineProperty = null;
  458. } else if (!canDefinePropertyOnDOM) {
  459. /** @private */
  460. defineProperty = function(obj, keyName, desc){
  461. var isNode;
  462. if (typeof Node === "object") {
  463. isNode = obj instanceof Node;
  464. } else {
  465. isNode = typeof obj === "object" && typeof obj.nodeType === "number" && typeof obj.nodeName === "string";
  466. }
  467. if (isNode) {
  468. // TODO: Should we have a warning here?
  469. return (obj[keyName] = desc.value);
  470. } else {
  471. return Object.defineProperty(obj, keyName, desc);
  472. }
  473. };
  474. }
  475. }
  476. /**
  477. Identical to Object.defineProperty(). Implements as much functionality
  478. as possible if not available natively.
  479. @memberOf Ember.platform
  480. @name defineProperty
  481. @param {Object} obj The object to modify
  482. @param {String} keyName property name to modify
  483. @param {Object} desc descriptor hash
  484. @returns {void}
  485. */
  486. platform.defineProperty = defineProperty;
  487. /**
  488. Set to true if the platform supports native getters and setters.
  489. @memberOf Ember.platform
  490. @name hasPropertyAccessors
  491. */
  492. platform.hasPropertyAccessors = true;
  493. if (!platform.defineProperty) {
  494. platform.hasPropertyAccessors = false;
  495. platform.defineProperty = function(obj, keyName, desc) {
  496. if (!desc.get) { obj[keyName] = desc.value; }
  497. };
  498. platform.defineProperty.isSimulated = true;
  499. }
  500. if (Ember.ENV.MANDATORY_SETTER && !platform.hasPropertyAccessors) {
  501. Ember.ENV.MANDATORY_SETTER = false;
  502. }
  503. })();
  504. (function() {
  505. // ==========================================================================
  506. // Project: Ember Metal
  507. // Copyright: ©2011 Strobe Inc. and contributors.
  508. // License: Licensed under MIT license (see license.js)
  509. // ==========================================================================
  510. var o_defineProperty = Ember.platform.defineProperty,
  511. o_create = Ember.create,
  512. // Used for guid generation...
  513. GUID_KEY = '__ember'+ (+ new Date()),
  514. uuid = 0,
  515. numberCache = [],
  516. stringCache = {};
  517. var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER;
  518. /**
  519. @private
  520. @static
  521. @type String
  522. @constant
  523. A unique key used to assign guids and other private metadata to objects.
  524. If you inspect an object in your browser debugger you will often see these.
  525. They can be safely ignored.
  526. On browsers that support it, these properties are added with enumeration
  527. disabled so they won't show up when you iterate over your properties.
  528. */
  529. Ember.GUID_KEY = GUID_KEY;
  530. var GUID_DESC = {
  531. writable: false,
  532. configurable: false,
  533. enumerable: false,
  534. value: null
  535. };
  536. /**
  537. @private
  538. Generates a new guid, optionally saving the guid to the object that you
  539. pass in. You will rarely need to use this method. Instead you should
  540. call Ember.guidFor(obj), which return an existing guid if available.
  541. @param {Object} obj
  542. Optional object the guid will be used for. If passed in, the guid will
  543. be saved on the object and reused whenever you pass the same object
  544. again.
  545. If no object is passed, just generate a new guid.
  546. @param {String} prefix
  547. Optional prefix to place in front of the guid. Useful when you want to
  548. separate the guid into separate namespaces.
  549. @returns {String} the guid
  550. */
  551. Ember.generateGuid = function generateGuid(obj, prefix) {
  552. if (!prefix) prefix = 'ember';
  553. var ret = (prefix + (uuid++));
  554. if (obj) {
  555. GUID_DESC.value = ret;
  556. o_defineProperty(obj, GUID_KEY, GUID_DESC);
  557. }
  558. return ret ;
  559. };
  560. /**
  561. @private
  562. Returns a unique id for the object. If the object does not yet have
  563. a guid, one will be assigned to it. You can call this on any object,
  564. Ember.Object-based or not, but be aware that it will add a _guid property.
  565. You can also use this method on DOM Element objects.
  566. @method
  567. @param obj {Object} any object, string, number, Element, or primitive
  568. @returns {String} the unique guid for this instance.
  569. */
  570. Ember.guidFor = function guidFor(obj) {
  571. // special cases where we don't want to add a key to object
  572. if (obj === undefined) return "(undefined)";
  573. if (obj === null) return "(null)";
  574. var cache, ret;
  575. var type = typeof obj;
  576. // Don't allow prototype changes to String etc. to change the guidFor
  577. switch(type) {
  578. case 'number':
  579. ret = numberCache[obj];
  580. if (!ret) ret = numberCache[obj] = 'nu'+obj;
  581. return ret;
  582. case 'string':
  583. ret = stringCache[obj];
  584. if (!ret) ret = stringCache[obj] = 'st'+(uuid++);
  585. return ret;
  586. case 'boolean':
  587. return obj ? '(true)' : '(false)';
  588. default:
  589. if (obj[GUID_KEY]) return obj[GUID_KEY];
  590. if (obj === Object) return '(Object)';
  591. if (obj === Array) return '(Array)';
  592. ret = 'ember'+(uuid++);
  593. GUID_DESC.value = ret;
  594. o_defineProperty(obj, GUID_KEY, GUID_DESC);
  595. return ret;
  596. }
  597. };
  598. // ..........................................................
  599. // META
  600. //
  601. var META_DESC = {
  602. writable: true,
  603. configurable: false,
  604. enumerable: false,
  605. value: null
  606. };
  607. var META_KEY = Ember.GUID_KEY+'_meta';
  608. /**
  609. The key used to store meta information on object for property observing.
  610. @static
  611. @type String
  612. */
  613. Ember.META_KEY = META_KEY;
  614. // Placeholder for non-writable metas.
  615. var EMPTY_META = {
  616. descs: {},
  617. watching: {}
  618. };
  619. if (MANDATORY_SETTER) { EMPTY_META.values = {}; }
  620. Ember.EMPTY_META = EMPTY_META;
  621. if (Object.freeze) Object.freeze(EMPTY_META);
  622. var isDefinePropertySimulated = Ember.platform.defineProperty.isSimulated;
  623. function Meta(obj) {
  624. this.descs = {};
  625. this.watching = {};
  626. this.cache = {};
  627. this.source = obj;
  628. }
  629. if (isDefinePropertySimulated) {
  630. // on platforms that don't support enumerable false
  631. // make meta fail jQuery.isPlainObject() to hide from
  632. // jQuery.extend() by having a property that fails
  633. // hasOwnProperty check.
  634. Meta.prototype.__preventPlainObject__ = true;
  635. }
  636. /**
  637. @private
  638. @function
  639. Retrieves the meta hash for an object. If 'writable' is true ensures the
  640. hash is writable for this object as well.
  641. The meta object contains information about computed property descriptors as
  642. well as any watched properties and other information. You generally will
  643. not access this information directly but instead work with higher level
  644. methods that manipulate this hash indirectly.
  645. @param {Object} obj
  646. The object to retrieve meta for
  647. @param {Boolean} writable
  648. Pass false if you do not intend to modify the meta hash, allowing the
  649. method to avoid making an unnecessary copy.
  650. @returns {Hash}
  651. */
  652. Ember.meta = function meta(obj, writable) {
  653. var ret = obj[META_KEY];
  654. if (writable===false) return ret || EMPTY_META;
  655. if (!ret) {
  656. if (!isDefinePropertySimulated) o_defineProperty(obj, META_KEY, META_DESC);
  657. ret = new Meta(obj);
  658. if (MANDATORY_SETTER) { ret.values = {}; }
  659. obj[META_KEY] = ret;
  660. // make sure we don't accidentally try to create constructor like desc
  661. ret.descs.constructor = null;
  662. } else if (ret.source !== obj) {
  663. if (!isDefinePropertySimulated) o_defineProperty(obj, META_KEY, META_DESC);
  664. ret = o_create(ret);
  665. ret.descs = o_create(ret.descs);
  666. ret.watching = o_create(ret.watching);
  667. ret.cache = {};
  668. ret.source = obj;
  669. if (MANDATORY_SETTER) { ret.values = o_create(ret.values); }
  670. obj[META_KEY] = ret;
  671. }
  672. return ret;
  673. };
  674. Ember.getMeta = function getMeta(obj, property) {
  675. var meta = Ember.meta(obj, false);
  676. return meta[property];
  677. };
  678. Ember.setMeta = function setMeta(obj, property, value) {
  679. var meta = Ember.meta(obj, true);
  680. meta[property] = value;
  681. return value;
  682. };
  683. /**
  684. @private
  685. In order to store defaults for a class, a prototype may need to create
  686. a default meta object, which will be inherited by any objects instantiated
  687. from the class's constructor.
  688. However, the properties of that meta object are only shallow-cloned,
  689. so if a property is a hash (like the event system's `listeners` hash),
  690. it will by default be shared across all instances of that class.
  691. This method allows extensions to deeply clone a series of nested hashes or
  692. other complex objects. For instance, the event system might pass
  693. ['listeners', 'foo:change', 'ember157'] to `prepareMetaPath`, which will
  694. walk down the keys provided.
  695. For each key, if the key does not exist, it is created. If it already
  696. exists and it was inherited from its constructor, the constructor's
  697. key is cloned.
  698. You can also pass false for `writable`, which will simply return
  699. undefined if `prepareMetaPath` discovers any part of the path that
  700. shared or undefined.
  701. @param {Object} obj The object whose meta we are examining
  702. @param {Array} path An array of keys to walk down
  703. @param {Boolean} writable whether or not to create a new meta
  704. (or meta property) if one does not already exist or if it's
  705. shared with its constructor
  706. */
  707. Ember.metaPath = function metaPath(obj, path, writable) {
  708. var meta = Ember.meta(obj, writable), keyName, value;
  709. for (var i=0, l=path.length; i<l; i++) {
  710. keyName = path[i];
  711. value = meta[keyName];
  712. if (!value) {
  713. if (!writable) { return undefined; }
  714. value = meta[keyName] = { __ember_source__: obj };
  715. } else if (value.__ember_source__ !== obj) {
  716. if (!writable) { return undefined; }
  717. value = meta[keyName] = o_create(value);
  718. value.__ember_source__ = obj;
  719. }
  720. meta = value;
  721. }
  722. return value;
  723. };
  724. /**
  725. @private
  726. Wraps the passed function so that `this._super` will point to the superFunc
  727. when the function is invoked. This is the primitive we use to implement
  728. calls to super.
  729. @param {Function} func
  730. The function to call
  731. @param {Function} superFunc
  732. The super function.
  733. @returns {Function} wrapped function.
  734. */
  735. Ember.wrap = function(func, superFunc) {
  736. function K() {}
  737. var newFunc = function() {
  738. var ret, sup = this._super;
  739. this._super = superFunc || K;
  740. ret = func.apply(this, arguments);
  741. this._super = sup;
  742. return ret;
  743. };
  744. newFunc.base = func;
  745. return newFunc;
  746. };
  747. /**
  748. Returns true if the passed object is an array or Array-like.
  749. Ember Array Protocol:
  750. - the object has an objectAt property
  751. - the object is a native Array
  752. - the object is an Object, and has a length property
  753. Unlike Ember.typeOf this method returns true even if the passed object is
  754. not formally array but appears to be array-like (i.e. implements Ember.Array)
  755. Ember.isArray(); // false
  756. Ember.isArray([]); // true
  757. Ember.isArray( Ember.ArrayProxy.create({ content: [] }) ); // true
  758. @param {Object} obj The object to test
  759. @returns {Boolean}
  760. */
  761. Ember.isArray = function(obj) {
  762. if (!obj || obj.setInterval) { return false; }
  763. if (Array.isArray && Array.isArray(obj)) { return true; }
  764. if (Ember.Array && Ember.Array.detect(obj)) { return true; }
  765. if ((obj.length !== undefined) && 'object'===typeof obj) { return true; }
  766. return false;
  767. };
  768. /**
  769. Forces the passed object to be part of an array. If the object is already
  770. an array or array-like, returns the object. Otherwise adds the object to
  771. an array. If obj is null or undefined, returns an empty array.
  772. Ember.makeArray(); => []
  773. Ember.makeArray(null); => []
  774. Ember.makeArray(undefined); => []
  775. Ember.makeArray('lindsay'); => ['lindsay']
  776. Ember.makeArray([1,2,42]); => [1,2,42]
  777. var controller = Ember.ArrayProxy.create({ content: [] });
  778. Ember.makeArray(controller) === controller; => true
  779. @param {Object} obj the object
  780. @returns {Array}
  781. */
  782. Ember.makeArray = function(obj) {
  783. if (obj === null || obj === undefined) { return []; }
  784. return Ember.isArray(obj) ? obj : [obj];
  785. };
  786. function canInvoke(obj, methodName) {
  787. return !!(obj && typeof obj[methodName] === 'function');
  788. }
  789. /**
  790. Checks to see if the `methodName` exists on the `obj`.
  791. @function
  792. @param {Object} obj The object to check for the method
  793. @param {String} methodName The method name to check for
  794. */
  795. Ember.canInvoke = canInvoke;
  796. /**
  797. Checks to see if the `methodName` exists on the `obj`,
  798. and if it does, invokes it with the arguments passed.
  799. @function
  800. @param {Object} obj The object to check for the method
  801. @param {String} methodName The method name to check for
  802. @param {Array} args The arguments to pass to the method
  803. @returns {Boolean} true if the method does not return false
  804. @returns {Boolean} false otherwise
  805. */
  806. Ember.tryInvoke = function(obj, methodName, args) {
  807. if (canInvoke(obj, methodName)) {
  808. return obj[methodName].apply(obj, args);
  809. }
  810. };
  811. })();
  812. (function() {
  813. /**
  814. JavaScript (before ES6) does not have a Map implementation. Objects,
  815. which are often used as dictionaries, may only have Strings as keys.
  816. Because Ember has a way to get a unique identifier for every object
  817. via `Ember.guidFor`, we can implement a performant Map with arbitrary
  818. keys. Because it is commonly used in low-level bookkeeping, Map is
  819. implemented as a pure JavaScript object for performance.
  820. This implementation follows the current iteration of the ES6 proposal
  821. for maps (http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets),
  822. with two exceptions. First, because we need our implementation to be
  823. pleasant on older browsers, we do not use the `delete` name (using
  824. `remove` instead). Second, as we do not have the luxury of in-VM
  825. iteration, we implement a forEach method for iteration.
  826. Map is mocked out to look like an Ember object, so you can do
  827. `Ember.Map.create()` for symmetry with other Ember classes.
  828. */
  829. /** @private */
  830. var guidFor = Ember.guidFor,
  831. indexOf = Ember.ArrayPolyfills.indexOf;
  832. var copy = function(obj) {
  833. var output = {};
  834. for (var prop in obj) {
  835. if (obj.hasOwnProperty(prop)) { output[prop] = obj[prop]; }
  836. }
  837. return output;
  838. };
  839. var copyMap = function(original, newObject) {
  840. var keys = original.keys.copy(),
  841. values = copy(original.values);
  842. newObject.keys = keys;
  843. newObject.values = values;
  844. return newObject;
  845. };
  846. // This class is used internally by Ember.js and Ember Data.
  847. // Please do not use it at this time. We plan to clean it up
  848. // and add many tests soon.
  849. var OrderedSet = Ember.OrderedSet = function() {
  850. this.clear();
  851. };
  852. OrderedSet.create = function() {
  853. return new OrderedSet();
  854. };
  855. OrderedSet.prototype = {
  856. clear: function() {
  857. this.presenceSet = {};
  858. this.list = [];
  859. },
  860. add: function(obj) {
  861. var guid = guidFor(obj),
  862. presenceSet = this.presenceSet,
  863. list = this.list;
  864. if (guid in presenceSet) { return; }
  865. presenceSet[guid] = true;
  866. list.push(obj);
  867. },
  868. remove: function(obj) {
  869. var guid = guidFor(obj),
  870. presenceSet = this.presenceSet,
  871. list = this.list;
  872. delete presenceSet[guid];
  873. var index = indexOf.call(list, obj);
  874. if (index > -1) {
  875. list.splice(index, 1);
  876. }
  877. },
  878. isEmpty: function() {
  879. return this.list.length === 0;
  880. },
  881. forEach: function(fn, self) {
  882. // allow mutation during iteration
  883. var list = this.list.slice();
  884. for (var i = 0, j = list.length; i < j; i++) {
  885. fn.call(self, list[i]);
  886. }
  887. },
  888. toArray: function() {
  889. return this.list.slice();
  890. },
  891. copy: function() {
  892. var set = new OrderedSet();
  893. set.presenceSet = copy(this.presenceSet);
  894. set.list = this.list.slice();
  895. return set;
  896. }
  897. };
  898. /**
  899. A Map stores values indexed by keys. Unlike JavaScript's
  900. default Objects, the keys of a Map can be any JavaScript
  901. object.
  902. Internally, a Map has two data structures:
  903. `keys`: an OrderedSet of all of the existing keys
  904. `values`: a JavaScript Object indexed by the
  905. Ember.guidFor(key)
  906. When a key/value pair is added for the first time, we
  907. add the key to the `keys` OrderedSet, and create or
  908. replace an entry in `values`. When an entry is deleted,
  909. we delete its entry in `keys` and `values`.
  910. */
  911. /** @private */
  912. var Map = Ember.Map = function() {
  913. this.keys = Ember.OrderedSet.create();
  914. this.values = {};
  915. };
  916. Map.create = function() {
  917. return new Map();
  918. };
  919. Map.prototype = {
  920. /**
  921. Retrieve the value associated with a given key.
  922. @param {anything} key
  923. @return {anything} the value associated with the key, or undefined
  924. */
  925. get: function(key) {
  926. var values = this.values,
  927. guid = guidFor(key);
  928. return values[guid];
  929. },
  930. /**
  931. Adds a value to the map. If a value for the given key has already been
  932. provided, the new value will replace the old value.
  933. @param {anything} key
  934. @param {anything} value
  935. */
  936. set: function(key, value) {
  937. var keys = this.keys,
  938. values = this.values,
  939. guid = guidFor(key);
  940. keys.add(key);
  941. values[guid] = value;
  942. },
  943. /**
  944. Removes a value from the map for an associated key.
  945. @param {anything} key
  946. @returns {Boolean} true if an item was removed, false otherwise
  947. */
  948. remove: function(key) {
  949. // don't use ES6 "delete" because it will be annoying
  950. // to use in browsers that are not ES6 friendly;
  951. var keys = this.keys,
  952. values = this.values,
  953. guid = guidFor(key),
  954. value;
  955. if (values.hasOwnProperty(guid)) {
  956. keys.remove(key);
  957. value = values[guid];
  958. delete values[guid];
  959. return true;
  960. } else {
  961. return false;
  962. }
  963. },
  964. /**
  965. Check whether a key is present.
  966. @param {anything} key
  967. @returns {Boolean} true if the item was present, false otherwise
  968. */
  969. has: function(key) {
  970. var values = this.values,
  971. guid = guidFor(key);
  972. return values.hasOwnProperty(guid);
  973. },
  974. /**
  975. Iterate over all the keys and values. Calls the function once
  976. for each key, passing in the key and value, in that order.
  977. The keys are guaranteed to be iterated over in insertion order.
  978. @param {Function} callback
  979. @param {anything} self if passed, the `this` value inside the
  980. callback. By default, `this` is the map.
  981. */
  982. forEach: function(callback, self) {
  983. var keys = this.keys,
  984. values = this.values;
  985. keys.forEach(function(key) {
  986. var guid = guidFor(key);
  987. callback.call(self, key, values[guid]);
  988. });
  989. },
  990. copy: function() {
  991. return copyMap(this, new Map());
  992. }
  993. };
  994. var MapWithDefault = Ember.MapWithDefault = function(options) {
  995. Map.call(this);
  996. this.defaultValue = options.defaultValue;
  997. };
  998. MapWithDefault.create = function(options) {
  999. if (options) {
  1000. return new MapWithDefault(options);
  1001. } else {
  1002. return new Map();
  1003. }
  1004. };
  1005. MapWithDefault.prototype = Ember.create(Map.prototype);
  1006. MapWithDefault.prototype.get = function(key) {
  1007. var hasValue = this.has(key);
  1008. if (hasValue) {
  1009. return Map.prototype.get.call(this, key);
  1010. } else {
  1011. var defaultValue = this.defaultValue(key);
  1012. this.set(key, defaultValue);
  1013. return defaultValue;
  1014. }
  1015. };
  1016. MapWithDefault.prototype.copy = function() {
  1017. return copyMap(this, new MapWithDefault({
  1018. defaultValue: this.defaultValue
  1019. }));
  1020. };
  1021. })();
  1022. (function() {
  1023. // ==========================================================================
  1024. // Project: Ember Metal
  1025. // Copyright: ©2011 Strobe Inc. and contributors.
  1026. // License: Licensed under MIT license (see license.js)
  1027. // ==========================================================================
  1028. var META_KEY = Ember.META_KEY, get, set;
  1029. var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER;
  1030. /** @private */
  1031. var IS_GLOBAL = /^([A-Z$]|([0-9][A-Z$]))/;
  1032. var IS_GLOBAL_PATH = /^([A-Z$]|([0-9][A-Z$])).*[\.\*]/;
  1033. var HAS_THIS = /^this[\.\*]/;
  1034. var FIRST_KEY = /^([^\.\*]+)/;
  1035. // ..........................................................
  1036. // GET AND SET
  1037. //
  1038. // If we are on a platform that supports accessors we can get use those.
  1039. // Otherwise simulate accessors by looking up the property directly on the
  1040. // object.
  1041. /** @private */
  1042. get = function get(obj, keyName) {
  1043. // Helpers that operate with 'this' within an #each
  1044. if (keyName === '') {
  1045. return obj;
  1046. }
  1047. if (!keyName && 'string'===typeof obj) {
  1048. keyName = obj;
  1049. obj = null;
  1050. }
  1051. if (!obj || keyName.indexOf('.') !== -1) {
  1052. return getPath(obj, keyName);
  1053. }
  1054. Ember.assert("You need to provide an object and key to `get`.", !!obj && keyName);
  1055. var meta = obj[META_KEY], desc = meta && meta.descs[keyName], ret;
  1056. if (desc) {
  1057. return desc.get(obj, keyName);
  1058. } else {
  1059. if (MANDATORY_SETTER && meta && meta.watching[keyName] > 0) {
  1060. ret = meta.values[keyName];
  1061. } else {
  1062. ret = obj[keyName];
  1063. }
  1064. if (ret === undefined &&
  1065. 'object' === typeof obj && !(keyName in obj) && 'function' === typeof obj.unknownProperty) {
  1066. return obj.unknownProperty(keyName);
  1067. }
  1068. return ret;
  1069. }
  1070. };
  1071. /** @private */
  1072. set = function set(obj, keyName, value, tolerant) {
  1073. if (typeof obj === 'string') {
  1074. Ember.assert("Path '" + obj + "' must be global if no obj is given.", IS_GLOBAL.test(obj));
  1075. value = keyName;
  1076. keyName = obj;
  1077. obj = null;
  1078. }
  1079. if (!obj || keyName.indexOf('.') !== -1) {
  1080. return setPath(obj, keyName, value, tolerant);
  1081. }
  1082. Ember.assert("You need to provide an object and key to `set`.", !!obj && keyName !== undefined);
  1083. Ember.assert('calling set on destroyed object', !obj.isDestroyed);
  1084. var meta = obj[META_KEY], desc = meta && meta.descs[keyName],
  1085. isUnknown, currentValue;
  1086. if (desc) {
  1087. desc.set(obj, keyName, value);
  1088. }
  1089. else {
  1090. isUnknown = 'object' === typeof obj && !(keyName in obj);
  1091. // setUnknownProperty is called if `obj` is an object,
  1092. // the property does not already exist, and the
  1093. // `setUnknownProperty` method exists on the object
  1094. if (isUnknown && 'function' === typeof obj.setUnknownProperty) {
  1095. obj.setUnknownProperty(keyName, value);
  1096. } else if (meta && meta.watching[keyName] > 0) {
  1097. if (MANDATORY_SETTER) {
  1098. currentValue = meta.values[keyName];
  1099. } else {
  1100. currentValue = obj[keyName];
  1101. }
  1102. // only trigger a change if the value has changed
  1103. if (value !== currentValue) {
  1104. Ember.propertyWillChange(obj, keyName);
  1105. if (MANDATORY_SETTER) {
  1106. if (currentValue === undefined && !(keyName in obj)) {
  1107. Ember.defineProperty(obj, keyName, null, value); // setup mandatory setter
  1108. } else {
  1109. meta.values[keyName] = value;
  1110. }
  1111. } else {
  1112. obj[keyName] = value;
  1113. }
  1114. Ember.propertyDidChange(obj, keyName);
  1115. }
  1116. } else {
  1117. obj[keyName] = value;
  1118. }
  1119. }
  1120. return value;
  1121. };
  1122. /** @private */
  1123. function firstKey(path) {
  1124. return path.match(FIRST_KEY)[0];
  1125. }
  1126. // assumes path is already normalized
  1127. /** @private */
  1128. function normalizeTuple(target, path) {
  1129. var hasThis = HAS_THIS.test(path),
  1130. isGlobal = !hasThis && IS_GLOBAL_PATH.test(path),
  1131. key;
  1132. if (!target || isGlobal) target = window;
  1133. if (hasThis) path = path.slice(5);
  1134. if (target === window) {
  1135. key = firstKey(path);
  1136. target = get(target, key);
  1137. path = path.slice(key.length+1);
  1138. }
  1139. // must return some kind of path to be valid else other things will break.
  1140. if (!path || path.length===0) throw new Error('Invalid Path');
  1141. return [ target, path ];
  1142. }
  1143. /** @private */
  1144. function getPath(root, path) {
  1145. var hasThis, parts, tuple, idx, len;
  1146. // If there is no root and path is a key name, return that
  1147. // property from the global object.
  1148. // E.g. get('Ember') -> Ember
  1149. if (root === null && path.indexOf('.') === -1) { return get(window, path); }
  1150. // detect complicated paths and normalize them
  1151. hasThis = HAS_THIS.test(path);
  1152. if (!root || hasThis) {
  1153. tuple = normalizeTuple(root, path);
  1154. root = tuple[0];
  1155. path = tuple[1];
  1156. tuple.length = 0;
  1157. }
  1158. parts = path.split(".");
  1159. len = parts.length;
  1160. for (idx=0; root && idx<len; idx++) {
  1161. root = get(root, parts[idx], true);
  1162. if (root && root.isDestroyed) { return undefined; }
  1163. }
  1164. return root;
  1165. }
  1166. /** @private */
  1167. function setPath(root, path, value, tolerant) {
  1168. var keyName;
  1169. // get the last part of the path
  1170. keyName = path.slice(path.lastIndexOf('.') + 1);
  1171. // get the first part of the part
  1172. path = path.slice(0, path.length-(keyName.length+1));
  1173. // unless the path is this, look up the first part to
  1174. // get the root
  1175. if (path !== 'this') {
  1176. root = getPath(root, path);
  1177. }
  1178. if (!keyName || keyName.length === 0) {
  1179. throw new Error('You passed an empty path');
  1180. }
  1181. if (!root) {
  1182. if (tolerant) { return; }
  1183. else { throw new Error('Object in path '+path+' could not be found or was destroyed.'); }
  1184. }
  1185. return set(root, keyName, value);
  1186. }
  1187. /**
  1188. @private
  1189. Normalizes a target/path pair to reflect that actual target/path that should
  1190. be observed, etc. This takes into account passing in global property
  1191. paths (i.e. a path beginning with a captial letter not defined on the
  1192. target) and * separators.
  1193. @param {Object} target
  1194. The current target. May be null.
  1195. @param {String} path
  1196. A path on the target or a global property path.
  1197. @returns {Array} a temporary array with the normalized target/path pair.
  1198. */
  1199. Ember.normalizeTuple = function(target, path) {
  1200. return normalizeTuple(target, path);
  1201. };
  1202. Ember.getWithDefault = function(root, key, defaultValue) {
  1203. var value = get(root, key);
  1204. if (value === undefined) { return defaultValue; }
  1205. return value;
  1206. };
  1207. /**
  1208. @function
  1209. Gets the value of a property on an object. If the property is computed,
  1210. the function will be invoked. If the property is not defined but the
  1211. object implements the unknownProperty() method then that will be invoked.
  1212. If you plan to run on IE8 and older browsers then you should use this
  1213. method anytime you want to retrieve a property on an object that you don't
  1214. know for sure is private. (My convention only properties beginning with
  1215. an underscore '_' are considered private.)
  1216. On all newer browsers, you only need to use this method to retrieve
  1217. properties if the property might not be defined on the object and you want
  1218. to respect the unknownProperty() handler. Otherwise you can ignore this
  1219. method.
  1220. Note that if the obj itself is null, this method will simply return
  1221. undefined.
  1222. @param {Object} obj
  1223. The object to retrieve from.
  1224. @param {String} keyName
  1225. The property key to retrieve
  1226. @returns {Object} the property value or null.
  1227. */
  1228. Ember.get = get;
  1229. Ember.getPath = Ember.deprecateFunc('getPath is deprecated since get now supports paths', Ember.get);
  1230. /**
  1231. @function
  1232. Sets the value of a property on an object, respecting computed properties
  1233. and notifying observers and other listeners of the change. If the
  1234. property is not defined but the object implements the unknownProperty()
  1235. method then that will be invoked as well.
  1236. If you plan to run on IE8 and older browsers then you should use this
  1237. method anytime you want to set a property on an object that you don't
  1238. know for sure is private. (My convention only properties beginning with
  1239. an underscore '_' are considered private.)
  1240. On all newer browsers, you only need to use this method to set
  1241. properties if the property might not be defined on the object and you want
  1242. to respect the unknownProperty() handler. Otherwise you can ignore this
  1243. method.
  1244. @param {Object} obj
  1245. The object to modify.
  1246. @param {String} keyName
  1247. The property key to set
  1248. @param {Object} value
  1249. The value to set
  1250. @returns {Object} the passed value.
  1251. */
  1252. Ember.set = set;
  1253. Ember.setPath = Ember.deprecateFunc('setPath is deprecated since set now supports paths', Ember.set);
  1254. /**
  1255. Error-tolerant form of Ember.set. Will not blow up if any part of the
  1256. chain is undefined, null, or destroyed.
  1257. This is primarily used when syncing bindings, which may try to update after
  1258. an object has been destroyed.
  1259. */
  1260. Ember.trySet = function(root, path, value) {
  1261. return set(root, path, value, true);
  1262. };
  1263. Ember.trySetPath = Ember.deprecateFunc('trySetPath has been renamed to trySet', Ember.trySet);
  1264. /**
  1265. Returns true if the provided path is global (e.g., "MyApp.fooController.bar")
  1266. instead of local ("foo.bar.baz").
  1267. @param {String} path
  1268. @returns Boolean
  1269. */
  1270. Ember.isGlobalPath = function(path) {
  1271. return IS_GLOBAL.test(path);
  1272. };
  1273. if (Ember.config.overrideAccessors) {
  1274. Ember.config.overrideAccessors();
  1275. get = Ember.get;
  1276. set = Ember.set;
  1277. }
  1278. })();
  1279. (function() {
  1280. // ==========================================================================
  1281. // Project: Ember Metal
  1282. // Copyright: ©2011 Strobe Inc. and contributors.
  1283. // License: Licensed under MIT license (see license.js)
  1284. // ==========================================================================
  1285. var GUID_KEY = Ember.GUID_KEY,
  1286. META_KEY = Ember.META_KEY,
  1287. EMPTY_META = Ember.EMPTY_META,
  1288. metaFor = Ember.meta,
  1289. o_create = Ember.create,
  1290. objectDefineProperty = Ember.platform.defineProperty;
  1291. var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER;
  1292. // ..........................................................
  1293. // DESCRIPTOR
  1294. //
  1295. /**
  1296. @private
  1297. @constructor
  1298. Objects of this type can implement an interface to responds requests to
  1299. get and set. The default implementation handles simple properties.
  1300. You generally won't need to create or subclass this directly.
  1301. */
  1302. var Descriptor = Ember.Descriptor = function() {};
  1303. // ..........................................................
  1304. // DEFINING PROPERTIES API
  1305. //
  1306. /**
  1307. @private
  1308. NOTE: This is a low-level method used by other parts of the API. You almost
  1309. never want to call this method directly. Instead you should use Ember.mixin()
  1310. to define new properties.
  1311. Defines a property on an object. This method works much like the ES5
  1312. Object.defineProperty() method except that it can also accept computed
  1313. properties and other special descriptors.
  1314. Normally this method takes only three parameters. However if you pass an
  1315. instance of Ember.Descriptor as the third param then you can pass an optional
  1316. value as the fourth parameter. This is often more efficient than creating
  1317. new descriptor hashes for each property.
  1318. ## Examples
  1319. // ES5 compatible mode
  1320. Ember.defineProperty(contact, 'firstName', {
  1321. writable: true,
  1322. configurable: false,
  1323. enumerable: true,
  1324. value: 'Charles'
  1325. });
  1326. // define a simple property
  1327. Ember.defineProperty(contact, 'lastName', undefined, 'Jolley');
  1328. // define a computed property
  1329. Ember.defineProperty(contact, 'fullName', Ember.computed(function() {
  1330. return this.firstName+' '+this.lastName;
  1331. }).property('firstName', 'lastName').cacheable());
  1332. */
  1333. Ember.defineProperty = function(obj, keyName, desc, data, meta) {
  1334. // The first two parameters to defineProperty are mandatory:
  1335. //
  1336. // * obj: the object to define this property on. This may be
  1337. // a prototype.
  1338. // * keyName: the name of the property
  1339. //
  1340. // One and only one of the following two parameters must be
  1341. // provided:
  1342. //
  1343. // * desc: an instance of Ember.Descriptor (typically a
  1344. // computed property) or an ES5 descriptor.
  1345. // * data: something other than a descriptor, that will
  1346. // become the explicit value of this property.
  1347. var descs, existingDesc, watching, value;
  1348. if (!meta) meta = metaFor(obj);
  1349. descs = meta.descs;
  1350. existingDesc = meta.descs[keyName];
  1351. watching = meta.watching[keyName] > 0;
  1352. if (existingDesc instanceof Ember.Descriptor) {
  1353. existingDesc.teardown(obj, keyName);
  1354. }
  1355. if (desc instanceof Ember.Descriptor) {
  1356. value = desc;
  1357. descs[keyName] = desc;
  1358. if (MANDATORY_SETTER && watching) {
  1359. objectDefineProperty(obj, keyName, {
  1360. configurable: true,
  1361. enumerable: true,
  1362. writable: true,
  1363. value: undefined // make enumerable
  1364. });
  1365. } else {
  1366. obj[keyName] = undefined; // make enumerable
  1367. }
  1368. desc.setup(obj, keyName);
  1369. } else {
  1370. descs[keyName] = undefined; // shadow descriptor in proto
  1371. if (desc == null) {
  1372. value = data;
  1373. if (MANDATORY_SETTER && watching) {
  1374. meta.values[keyName] = data;
  1375. objectDefineProperty(obj, keyName, {
  1376. configurable: true,
  1377. enumerable: true,
  1378. set: function() {
  1379. Ember.assert('Must use Ember.set() to access this property', false);
  1380. },
  1381. get: function() {
  1382. var meta = this[META_KEY];
  1383. return meta && meta.values[keyName];
  1384. }
  1385. });
  1386. } else {
  1387. obj[keyName] = data;
  1388. }
  1389. } else {
  1390. value = desc;
  1391. // compatibility with ES5
  1392. objectDefineProperty(obj, keyName, desc);
  1393. }
  1394. }
  1395. // if key is being watched, override chains that
  1396. // were initialized with the prototype
  1397. if (watching) { Ember.overrideChains(obj, keyName, meta); }
  1398. // The `value` passed to the `didDefineProperty` hook is
  1399. // either the descriptor or data, whichever was passed.
  1400. if (obj.didDefineProperty) { obj.didDefineProperty(obj, keyName, value); }
  1401. return this;
  1402. };
  1403. })();
  1404. (function() {
  1405. // ==========================================================================
  1406. // Project: Ember Metal
  1407. // Copyright: ©2011 Strobe Inc. and contributors.
  1408. // License: Licensed under MIT license (see license.js)
  1409. // ==========================================================================
  1410. var AFTER_OBSERVERS = ':change';
  1411. var BEFORE_OBSERVERS = ':before';
  1412. var guidFor = Ember.guidFor;
  1413. var deferred = 0;
  1414. var array_Slice = [].slice;
  1415. /** @private */
  1416. var ObserverSet = function () {
  1417. this.targetSet = {};
  1418. };
  1419. ObserverSet.prototype.add = function (target, path) {
  1420. var targetSet = this.targetSet,
  1421. targetGuid = Ember.guidFor(target),
  1422. pathSet = targetSet[targetGuid];
  1423. if (!pathSet) {
  1424. targetSet[targetGuid] = pathSet = {};
  1425. }
  1426. if (pathSet[path]) {
  1427. return false;
  1428. } else {
  1429. return pathSet[path] = true;
  1430. }
  1431. };
  1432. ObserverSet.prototype.clear = function () {
  1433. this.targetSet = {};
  1434. };
  1435. /** @private */
  1436. var DeferredEventQueue = function() {
  1437. this.targetSet = {};
  1438. this.queue = [];
  1439. };
  1440. DeferredEventQueue.prototype.push = function(target, eventName, keyName) {
  1441. var targetSet = this.targetSet,
  1442. queue = this.queue,
  1443. targetGuid = Ember.guidFor(target),
  1444. eventNameSet = targetSet[targetGuid],
  1445. index;
  1446. if (!eventNameSet) {
  1447. targetSet[targetGuid] = eventNameSet = {};
  1448. }
  1449. index = eventNameSet[eventName];
  1450. if (index === undefined) {
  1451. eventNameSet[eventName] = queue.push(Ember.deferEvent(target, eventName, [target, keyName])) - 1;
  1452. } else {
  1453. queue[index] = Ember.deferEvent(target, eventName, [target, keyName]);
  1454. }
  1455. };
  1456. DeferredEventQueue.prototype.flush = function() {
  1457. var queue = this.queue;
  1458. this.queue = [];
  1459. this.targetSet = {};
  1460. for (var i=0, len=queue.length; i < len; ++i) {
  1461. queue[i]();
  1462. }
  1463. };
  1464. var queue = new DeferredEventQueue(), beforeObserverSet = new ObserverSet();
  1465. /** @private */
  1466. function notifyObservers(obj, eventName, keyName, forceNotification) {
  1467. if (deferred && !forceNotification) {
  1468. queue.push(obj, eventName, keyName);
  1469. } else {
  1470. Ember.sendEvent(obj, eventName, [obj, keyName]);
  1471. }
  1472. }
  1473. /** @private */
  1474. function flushObserverQueue() {
  1475. beforeObserverSet.clear();
  1476. queue.flush();
  1477. }
  1478. Ember.beginPropertyChanges = function() {
  1479. deferred++;
  1480. return this;
  1481. };
  1482. Ember.endPropertyChanges = function() {
  1483. deferred--;
  1484. if (deferred<=0) flushObserverQueue();
  1485. };
  1486. /**
  1487. Make a series of property changes together in an
  1488. exception-safe way.
  1489. Ember.changeProperties(function() {
  1490. obj1.set('foo', mayBlowUpWhenSet);
  1491. obj2.set('bar', baz);
  1492. });
  1493. */
  1494. Ember.changeProperties = function(cb, binding){
  1495. Ember.beginPropertyChanges();
  1496. try {
  1497. cb.call(binding);
  1498. } finally {
  1499. Ember.endPropertyChanges();
  1500. }
  1501. };
  1502. /**
  1503. Set a list of properties on an object. These properties are set inside
  1504. a single `beginPropertyChanges` and `endPropertyChanges` batch, so
  1505. observers will be buffered.
  1506. */
  1507. Ember.setProperties = function(self, hash) {
  1508. Ember.changeProperties(function(){
  1509. for(var prop in hash) {
  1510. if (hash.hasOwnProperty(prop)) Ember.set(self, prop, hash[prop]);
  1511. }
  1512. });
  1513. return self;
  1514. };
  1515. /** @private */
  1516. function changeEvent(keyName) {
  1517. return keyName+AFTER_OBSERVERS;
  1518. }
  1519. /** @private */
  1520. function beforeEvent(keyName) {
  1521. return keyName+BEFORE_OBSERVERS;
  1522. }
  1523. Ember.addObserver = function(obj, path, target, method) {
  1524. Ember.addListener(obj, changeEvent(path), target, method);
  1525. Ember.watch(obj, path);
  1526. return this;
  1527. };
  1528. /** @private */
  1529. Ember.observersFor = function(obj, path) {
  1530. return Ember.listenersFor(obj, changeEvent(path));
  1531. };
  1532. Ember.removeObserver = function(obj, path, target, method) {
  1533. Ember.unwatch(obj, path);
  1534. Ember.removeListener(obj, changeEvent(path), target, method);
  1535. return this;
  1536. };
  1537. Ember.addBeforeObserver = function(obj, path, target, method) {
  1538. Ember.addListener(obj, beforeEvent(path), target, method);
  1539. Ember.watch(obj, path);
  1540. return this;
  1541. };
  1542. // Suspend observer during callback.
  1543. //
  1544. // This should only be used by the target of the observer
  1545. // while it is setting the observed path.
  1546. /** @private */
  1547. Ember._suspendBeforeObserver = function(obj, path, target, method, callback) {
  1548. return Ember._suspendListener(obj, beforeEvent(path), target, method, callback);
  1549. };
  1550. Ember._suspendObserver = function(obj, path, target, method, callback) {
  1551. return Ember._suspendListener(obj, changeEvent(path), target, method, callback);
  1552. };
  1553. /** @private */
  1554. Ember.beforeObserversFor = function(obj, path) {
  1555. return Ember.listenersFor(obj, beforeEvent(path));
  1556. };
  1557. Ember.removeBeforeObserver = function(obj, path, target, method) {
  1558. Ember.unwatch(obj, path);
  1559. Ember.removeListener(obj, beforeEvent(path), target, method);
  1560. return this;
  1561. };
  1562. /** @private */
  1563. Ember.notifyObservers = function(obj, keyName) {
  1564. if (obj.isDestroying) { return; }
  1565. notifyObservers(obj, changeEvent(keyName), keyName);
  1566. };
  1567. /** @private */
  1568. Ember.notifyBeforeObservers = function(obj, keyName) {
  1569. if (obj.isDestroying) { return; }
  1570. var guid, set, forceNotification = false;
  1571. if (deferred) {
  1572. if (beforeObserverSet.add(obj, keyName)) {
  1573. forceNotification = true;
  1574. } else {
  1575. return;
  1576. }
  1577. }
  1578. notifyObservers(obj, beforeEvent(keyName), keyName, forceNotification);
  1579. };
  1580. })();
  1581. (function() {
  1582. // ==========================================================================
  1583. // Project: Ember Metal
  1584. // Copyright: ©2011 Strobe Inc. and contributors.
  1585. // License: Licensed under MIT license (see license.js)
  1586. // ==========================================================================
  1587. var guidFor = Ember.guidFor, // utils.js
  1588. metaFor = Ember.meta, // utils.js
  1589. get = Ember.get, // accessors.js
  1590. set = Ember.set, // accessors.js
  1591. normalizeTuple = Ember.normalizeTuple, // accessors.js
  1592. GUID_KEY = Ember.GUID_KEY, // utils.js
  1593. META_KEY = Ember.META_KEY, // utils.js
  1594. // circular reference observer depends on Ember.watch
  1595. // we should move change events to this file or its own property_events.js
  1596. notifyObservers = Ember.notifyObservers, // observer.js
  1597. forEach = Ember.ArrayPolyfills.forEach, // array.js
  1598. FIRST_KEY = /^([^\.\*]+)/,
  1599. IS_PATH = /[\.\*]/;
  1600. var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER,
  1601. o_defineProperty = Ember.platform.defineProperty;
  1602. /** @private */
  1603. function firstKey(path) {
  1604. return path.match(FIRST_KEY)[0];
  1605. }
  1606. // returns true if the passed path is just a keyName
  1607. /** @private */
  1608. function isKeyName(path) {
  1609. return path==='*' || !IS_PATH.test(path);
  1610. }
  1611. // ..........................................................
  1612. // DEPENDENT KEYS
  1613. //
  1614. var DEP_SKIP = { __emberproto__: true }; // skip some keys and toString
  1615. /** @private */
  1616. function iterDeps(method, obj, depKey, seen, meta) {
  1617. var guid = guidFor(obj);
  1618. if (!seen[guid]) seen[guid] = {};
  1619. if (seen[guid][depKey]) return;
  1620. seen[guid][depKey] = true;
  1621. var deps = meta.deps;
  1622. deps = deps && deps[depKey];
  1623. if (deps) {
  1624. for(var key in deps) {
  1625. if (DEP_SKIP[key]) continue;
  1626. method(obj, key);
  1627. }
  1628. }
  1629. }
  1630. var WILL_SEEN, DID_SEEN;
  1631. // called whenever a property is about to change to clear the cache of any dependent keys (and notify those properties of changes, etc...)
  1632. /** @private */
  1633. function dependentKeysWillChange(obj, depKey, meta) {
  1634. if (obj.isDestroying) { return; }
  1635. var seen = WILL_SEEN, top = !seen;
  1636. if (top) { seen = WILL_SEEN = {}; }
  1637. iterDeps(propertyWillChange, obj, depKey, seen, meta);
  1638. if (top) { WILL_SEEN = null; }
  1639. }
  1640. // called whenever a property has just changed to update dependent keys
  1641. /** @private */
  1642. function dependentKeysDidChange(obj, depKey, meta) {
  1643. if (obj.isDestroying) { return; }
  1644. var seen = DID_SEEN, top = !seen;
  1645. if (top) { seen = DID_SEEN = {}; }
  1646. iterDeps(propertyDidChange, obj, depKey, seen, meta);
  1647. if (top) { DID_SEEN = null; }
  1648. }
  1649. // ..........................................................
  1650. // CHAIN
  1651. //
  1652. /** @private */
  1653. function addChainWatcher(obj, keyName, node) {
  1654. if (!obj || ('object' !== typeof obj)) return; // nothing to do
  1655. var m = metaFor(obj);
  1656. var nodes = m.chainWatchers;
  1657. if (!nodes || nodes.__emberproto__ !== obj) {
  1658. nodes = m.chainWatchers = { __emberproto__: obj };
  1659. }
  1660. if (!nodes[keyName]) { nodes[keyName] = {}; }
  1661. nodes[keyName][guidFor(node)] = node;
  1662. Ember.watch(obj, keyName);
  1663. }
  1664. /** @private */
  1665. function removeChainWatcher(obj, keyName, node) {
  1666. if (!obj || 'object' !== typeof obj) { return; } // nothing to do
  1667. var m = metaFor(obj, false),
  1668. nodes = m.chainWatchers;
  1669. if (!nodes || nodes.__emberproto__ !== obj) { return; } //nothing to do
  1670. if (nodes[keyName]) { delete nodes[keyName][guidFor(node)]; }
  1671. Ember.unwatch(obj, keyName);
  1672. }
  1673. var pendingQueue = [];
  1674. // attempts to add the pendingQueue chains again. If some of them end up
  1675. // back in the queue and reschedule is true, schedules a timeout to try
  1676. // again.
  1677. /** @private */
  1678. function flushPendingChains() {
  1679. if (pendingQueue.length === 0) { return; } // nothing to do
  1680. var queue = pendingQueue;
  1681. pendingQueue = [];
  1682. forEach.call(queue, function(q) { q[0].add(q[1]); });
  1683. Ember.warn('Watching an undefined global, Ember expects watched globals to be setup by the time the run loop is flushed, check for typos', pendingQueue.length === 0);
  1684. }
  1685. /** @private */
  1686. function isProto(pvalue) {
  1687. return metaFor(pvalue, false).proto === pvalue;
  1688. }
  1689. // A ChainNode watches a single key on an object. If you provide a starting
  1690. // value for the key then the node won't actually watch it. For a root node
  1691. // pass null for parent and key and object for value.
  1692. /** @private */
  1693. var ChainNode = function(parent, key, value, separator) {
  1694. var obj;
  1695. this._parent = parent;
  1696. this._key = key;
  1697. // _watching is true when calling get(this._parent, this._key) will
  1698. // return the value of this node.
  1699. //
  1700. // It is false for the root of a chain (because we have no parent)
  1701. // and for global paths (because the parent node is the object with
  1702. // the observer on it)
  1703. this._watching = value===undefined;
  1704. this._value = value;
  1705. this._separator = separator || '.';
  1706. this._paths = {};
  1707. if (this._watching) {
  1708. this._object = parent.value();
  1709. if (this._object) { addChainWatcher(this._object, this._key, this); }
  1710. }
  1711. // Special-case: the EachProxy relies on immediate evaluation to
  1712. // establish its observers.
  1713. //
  1714. // TODO: Replace this with an efficient callback that the EachProxy
  1715. // can implement.
  1716. if (this._parent && this._parent._key === '@each') {
  1717. this.value();
  1718. }
  1719. };
  1720. var ChainNodePrototype = ChainNode.prototype;
  1721. ChainNodePrototype.value = function() {
  1722. if (this._value === undefined && this._watching) {
  1723. var obj = this._parent.value();
  1724. this._value = (obj && !isProto(obj)) ? get(obj, this._key) : undefined;
  1725. }
  1726. return this._value;
  1727. };
  1728. ChainNodePrototype.destroy = function() {
  1729. if (this._watching) {
  1730. var obj = this._object;
  1731. if (obj) { removeChainWatcher(obj, this._key, this); }
  1732. this._watching = false; // so future calls do nothing
  1733. }
  1734. };
  1735. // copies a top level object only
  1736. ChainNodePrototype.copy = function(obj) {
  1737. var ret = new ChainNode(null, null, obj, this._separator),
  1738. paths = this._paths, path;
  1739. for (path in paths) {
  1740. if (paths[path] <= 0) { continue; } // this check will also catch non-number vals.
  1741. ret.add(path);
  1742. }
  1743. return ret;
  1744. };
  1745. // called on the root node of a chain to setup watchers on the specified
  1746. // path.
  1747. ChainNodePrototype.add = function(path) {
  1748. var obj, tuple, key, src, separator, paths;
  1749. paths = this._paths;
  1750. paths[path] = (paths[path] || 0) + 1;
  1751. obj = this.value();
  1752. tuple = normalizeTuple(obj, path);
  1753. // the path was a local path
  1754. if (tuple[0] && tuple[0] === obj) {
  1755. path = tuple[1];
  1756. key = firstKey(path);
  1757. path = path.slice(key.length+1);
  1758. // global path, but object does not exist yet.
  1759. // put into a queue and try to connect later.
  1760. } else if (!tuple[0]) {
  1761. pendingQueue.push([this, path]);
  1762. tuple.length = 0;
  1763. return;
  1764. // global path, and object already exists
  1765. } else {
  1766. src = tuple[0];
  1767. key = path.slice(0, 0-(tuple[1].length+1));
  1768. separator = path.slice(key.length, key.length+1);
  1769. path = tuple[1];
  1770. }
  1771. tuple.length = 0;
  1772. this.chain(key, path, src, separator);
  1773. };
  1774. // called on the root node of a chain to teardown watcher on the specified
  1775. // path
  1776. ChainNodePrototype.remove = function(path) {
  1777. var obj, tuple, key, src, paths;
  1778. paths = this._paths;
  1779. if (paths[path] > 0) { paths[path]--; }
  1780. obj = this.value();
  1781. tuple = normalizeTuple(obj, path);
  1782. if (tuple[0] === obj) {
  1783. path = tuple[1];
  1784. key = firstKey(path);
  1785. path = path.slice(key.length+1);
  1786. } else {
  1787. src = tuple[0];
  1788. key = path.slice(0, 0-(tuple[1].length+1));
  1789. path = tuple[1];
  1790. }
  1791. tuple.length = 0;
  1792. this.unchain(key, path);
  1793. };
  1794. ChainNodePrototype.count = 0;
  1795. ChainNodePrototype.chain = function(key, path, src, separator) {
  1796. var chains = this._chains, node;
  1797. if (!chains) { chains = this._chains = {}; }
  1798. node = chains[key];
  1799. if (!node) { node = chains[key] = new ChainNode(this, key, src, separator); }
  1800. node.count++; // count chains...
  1801. // chain rest of path if there is one
  1802. if (path && path.length>0) {
  1803. key = firstKey(path);
  1804. path = path.slice(key.length+1);
  1805. node.chain(key, path); // NOTE: no src means it will observe changes...
  1806. }
  1807. };
  1808. ChainNodePrototype.unchain = function(key, path) {
  1809. var chains = this._chains, node = chains[key];
  1810. // unchain rest of path first...
  1811. if (path && path.length>1) {
  1812. key = firstKey(path);
  1813. path = path.slice(key.length+1);
  1814. node.unchain(key, path);
  1815. }
  1816. // delete node if needed.
  1817. node.count--;
  1818. if (node.count<=0) {
  1819. delete chains[node._key];
  1820. node.destroy();
  1821. }
  1822. };
  1823. ChainNodePrototype.willChange = function() {
  1824. var chains = this._chains;
  1825. if (chains) {
  1826. for(var key in chains) {
  1827. if (!chains.hasOwnProperty(key)) { continue; }
  1828. chains[key].willChange();
  1829. }
  1830. }
  1831. if (this._parent) { this._parent.chainWillChange(this, this._key, 1); }
  1832. };
  1833. ChainNodePrototype.chainWillChange = function(chain, path, depth) {
  1834. if (this._key) { path = this._key + this._separator + path; }
  1835. if (this._parent) {
  1836. this._parent.chainWillChange(this, path, depth+1);
  1837. } else {
  1838. if (depth > 1) { Ember.propertyWillChange(this.value(), path); }
  1839. path = 'this.' + path;
  1840. if (this._paths[path] > 0) { Ember.propertyWillChange(this.value(), path); }
  1841. }
  1842. };
  1843. ChainNodePrototype.chainDidChange = function(chain, path, depth) {
  1844. if (this._key) { path = this._key + this._separator + path; }
  1845. if (this._parent) {
  1846. this._parent.chainDidChange(this, path, depth+1);
  1847. } else {
  1848. if (depth > 1) { Ember.propertyDidChange(this.value(), path); }
  1849. path = 'this.' + path;
  1850. if (this._paths[path] > 0) { Ember.propertyDidChange(this.value(), path); }
  1851. }
  1852. };
  1853. ChainNodePrototype.didChange = function(suppressEvent) {
  1854. // invalidate my own value first.
  1855. if (this._watching) {
  1856. var obj = this._parent.value();
  1857. if (obj !== this._object) {
  1858. removeChainWatcher(this._object, this._key, this);
  1859. this._object = obj;
  1860. addChainWatcher(obj, this._key, this);
  1861. }
  1862. this._value = undefined;
  1863. // Special-case: the EachProxy relies on immediate evaluation to
  1864. // establish its observers.
  1865. if (this._parent && this._parent._key === '@each')
  1866. this.value();
  1867. }
  1868. // then notify chains...
  1869. var chains = this._chains;
  1870. if (chains) {
  1871. for(var key in chains) {
  1872. if (!chains.hasOwnProperty(key)) { continue; }
  1873. chains[key].didChange(suppressEvent);
  1874. }
  1875. }
  1876. if (suppressEvent) { return; }
  1877. // and finally tell parent about my path changing...
  1878. if (this._parent) { this._parent.chainDidChange(this, this._key, 1); }
  1879. };
  1880. // get the chains for the current object. If the current object has
  1881. // chains inherited from the proto they will be cloned and reconfigured for
  1882. // the current object.
  1883. /** @private */
  1884. function chainsFor(obj) {
  1885. var m = metaFor(obj), ret = m.chains;
  1886. if (!ret) {
  1887. ret = m.chains = new ChainNode(null, null, obj);
  1888. } else if (ret.value() !== obj) {
  1889. ret = m.chains = ret.copy(obj);
  1890. }
  1891. return ret;
  1892. }
  1893. /** @private */
  1894. function notifyChains(obj, m, keyName, methodName, arg) {
  1895. var nodes = m.chainWatchers;
  1896. if (!nodes || nodes.__emberproto__ !== obj) { return; } // nothing to do
  1897. nodes = nodes[keyName];
  1898. if (!nodes) { return; }
  1899. for(var key in nodes) {
  1900. if (!nodes.hasOwnProperty(key)) { continue; }
  1901. nodes[key][methodName](arg);
  1902. }
  1903. }
  1904. Ember.overrideChains = function(obj, keyName, m) {
  1905. notifyChains(obj, m, keyName, 'didChange', true);
  1906. };
  1907. /** @private */
  1908. function chainsWillChange(obj, keyName, m) {
  1909. notifyChains(obj, m, keyName, 'willChange');
  1910. }
  1911. /** @private */
  1912. function chainsDidChange(obj, keyName, m) {
  1913. notifyChains(obj, m, keyName, 'didChange');
  1914. }
  1915. // ..........................................................
  1916. // WATCH
  1917. //
  1918. /**
  1919. @private
  1920. Starts watching a property on an object. Whenever the property changes,
  1921. invokes Ember.propertyWillChange and Ember.propertyDidChange. This is the
  1922. primitive used by observers and dependent keys; usually you will never call
  1923. this method directly but instead use higher level methods like
  1924. Ember.addObserver().
  1925. */
  1926. Ember.watch = function(obj, keyName) {
  1927. // can't watch length on Array - it is special...
  1928. if (keyName === 'length' && Ember.typeOf(obj) === 'array') { return this; }
  1929. var m = metaFor(obj), watching = m.watching, desc;
  1930. // activate watching first time
  1931. if (!watching[keyName]) {
  1932. watching[keyName] = 1;
  1933. if (isKeyName(keyName)) {
  1934. desc = m.descs[keyName];
  1935. if (desc && desc.willWatch) { desc.willWatch(obj, keyName); }
  1936. if ('function' === typeof obj.willWatchProperty) {
  1937. obj.willWatchProperty(keyName);
  1938. }
  1939. if (MANDATORY_SETTER && keyName in obj) {
  1940. m.values[keyName] = obj[keyName];
  1941. o_defineProperty(obj, keyName, {
  1942. configurable: true,
  1943. enumerable: true,
  1944. set: function() {
  1945. Ember.assert('Must use Ember.set() to access this property', false);
  1946. },
  1947. get: function() {
  1948. var meta = this[META_KEY];
  1949. return meta && meta.values[keyName];
  1950. }
  1951. });
  1952. }
  1953. } else {
  1954. chainsFor(obj).add(keyName);
  1955. }
  1956. } else {
  1957. watching[keyName] = (watching[keyName] || 0) + 1;
  1958. }
  1959. return this;
  1960. };
  1961. Ember.isWatching = function isWatching(obj, key) {
  1962. var meta = obj[META_KEY];
  1963. return (meta && meta.watching[key]) > 0;
  1964. };
  1965. Ember.watch.flushPending = flushPendingChains;
  1966. /** @private */
  1967. Ember.unwatch = function(obj, keyName) {
  1968. // can't watch length on Array - it is special...
  1969. if (keyName === 'length' && Ember.typeOf(obj) === 'array') { return this; }
  1970. var m = metaFor(obj), watching = m.watching, desc;
  1971. if (watching[keyName] === 1) {
  1972. watching[keyName] = 0;
  1973. if (isKeyName(keyName)) {
  1974. desc = m.descs[keyName];
  1975. if (desc && desc.didUnwatch) { desc.didUnwatch(obj, keyName); }
  1976. if ('function' === typeof obj.didUnwatchProperty) {
  1977. obj.didUnwatchProperty(keyName);
  1978. }
  1979. if (MANDATORY_SETTER && keyName in obj) {
  1980. o_defineProperty(obj, keyName, {
  1981. configurable: true,
  1982. enumerable: true,
  1983. writable: true,
  1984. value: m.values[keyName]
  1985. });
  1986. delete m.values[keyName];
  1987. }
  1988. } else {
  1989. chainsFor(obj).remove(keyName);
  1990. }
  1991. } else if (watching[keyName]>1) {
  1992. watching[keyName]--;
  1993. }
  1994. return this;
  1995. };
  1996. /**
  1997. @private
  1998. Call on an object when you first beget it from another object. This will
  1999. setup any chained watchers on the object instance as needed. This method is
  2000. safe to call multiple times.
  2001. */
  2002. Ember.rewatch = function(obj) {
  2003. var m = metaFor(obj, false), chains = m.chains;
  2004. // make sure the object has its own guid.
  2005. if (GUID_KEY in obj && !obj.hasOwnProperty(GUID_KEY)) {
  2006. Ember.generateGuid(obj, 'ember');
  2007. }
  2008. // make sure any chained watchers update.
  2009. if (chains && chains.value() !== obj) {
  2010. m.chains = chains.copy(obj);
  2011. }
  2012. return this;
  2013. };
  2014. Ember.finishChains = function(obj) {
  2015. var m = metaFor(obj, false), chains = m.chains;
  2016. if (chains) {
  2017. if (chains.value() !== obj) {
  2018. m.chains = chains = chains.copy(obj);
  2019. }
  2020. chains.didChange(true);
  2021. }
  2022. };
  2023. // ..........................................................
  2024. // PROPERTY CHANGES
  2025. //
  2026. /**
  2027. This function is called just before an object property is about to change.
  2028. It will notify any before observers and prepare caches among other things.
  2029. Normally you will not need to call this method directly but if for some
  2030. reason you can't directly watch a property you can invoke this method
  2031. manually along with `Ember.propertyDidChange()` which you should call just
  2032. after the property value changes.
  2033. @memberOf Ember
  2034. @param {Object} obj
  2035. The object with the property that will change
  2036. @param {String} keyName
  2037. The property key (or path) that will change.
  2038. @returns {void}
  2039. */
  2040. function propertyWillChange(obj, keyName, value) {
  2041. var m = metaFor(obj, false),
  2042. watching = m.watching[keyName] > 0 || keyName === 'length',
  2043. proto = m.proto,
  2044. desc = m.descs[keyName];
  2045. if (!watching) { return; }
  2046. if (proto === obj) { return; }
  2047. if (desc && desc.willChange) { desc.willChange(obj, keyName); }
  2048. dependentKeysWillChange(obj, keyName, m);
  2049. chainsWillChange(obj, keyName, m);
  2050. Ember.notifyBeforeObservers(obj, keyName);
  2051. }
  2052. Ember.propertyWillChange = propertyWillChange;
  2053. /**
  2054. This function is called just after an object property has changed.
  2055. It will notify any observers and clear caches among other things.
  2056. Normally you will not need to call this method directly but if for some
  2057. reason you can't directly watch a property you can invoke this method
  2058. manually along with `Ember.propertyWilLChange()` which you should call just
  2059. before the property value changes.
  2060. @memberOf Ember
  2061. @param {Object} obj
  2062. The object with the property that will change
  2063. @param {String} keyName
  2064. The property key (or path) that will change.
  2065. @returns {void}
  2066. */
  2067. function propertyDidChange(obj, keyName) {
  2068. var m = metaFor(obj, false),
  2069. watching = m.watching[keyName] > 0 || keyName === 'length',
  2070. proto = m.proto,
  2071. desc = m.descs[keyName];
  2072. if (proto === obj) { return; }
  2073. // shouldn't this mean that we're watching this key?
  2074. if (desc && desc.didChange) { desc.didChange(obj, keyName); }
  2075. if (!watching && keyName !== 'length') { return; }
  2076. dependentKeysDidChange(obj, keyName, m);
  2077. chainsDidChange(obj, keyName, m);
  2078. Ember.notifyObservers(obj, keyName);
  2079. }
  2080. Ember.propertyDidChange = propertyDidChange;
  2081. var NODE_STACK = [];
  2082. /**
  2083. Tears down the meta on an object so that it can be garbage collected.
  2084. Multiple calls will have no effect.
  2085. @param {Object} obj the object to destroy
  2086. @returns {void}
  2087. */
  2088. Ember.destroy = function (obj) {
  2089. var meta = obj[META_KEY], node, nodes, key, nodeObject;
  2090. if (meta) {
  2091. obj[META_KEY] = null;
  2092. // remove chainWatchers to remove circular references that would prevent GC
  2093. node = meta.chains;
  2094. if (node) {
  2095. NODE_STACK.push(node);
  2096. // process tree
  2097. while (NODE_STACK.length > 0) {
  2098. node = NODE_STACK.pop();
  2099. // push children
  2100. nodes = node._chains;
  2101. if (nodes) {
  2102. for (key in nodes) {
  2103. if (nodes.hasOwnProperty(key)) {
  2104. NODE_STACK.push(nodes[key]);
  2105. }
  2106. }
  2107. }
  2108. // remove chainWatcher in node object
  2109. if (node._watching) {
  2110. nodeObject = node._object;
  2111. if (nodeObject) {
  2112. removeChainWatcher(nodeObject, node._key, node);
  2113. }
  2114. }
  2115. }
  2116. }
  2117. }
  2118. };
  2119. })();
  2120. (function() {
  2121. // ==========================================================================
  2122. // Project: Ember Metal
  2123. // Copyright: ©2011 Strobe Inc. and contributors.
  2124. // License: Licensed under MIT license (see license.js)
  2125. // ==========================================================================
  2126. Ember.warn("Computed properties will soon be cacheable by default. To enable this in your app, set `ENV.CP_DEFAULT_CACHEABLE = true`.", Ember.CP_DEFAULT_CACHEABLE);
  2127. var get = Ember.get,
  2128. metaFor = Ember.meta,
  2129. guidFor = Ember.guidFor,
  2130. a_slice = [].slice,
  2131. o_create = Ember.create,
  2132. META_KEY = Ember.META_KEY,
  2133. watch = Ember.watch,
  2134. unwatch = Ember.unwatch;
  2135. // ..........................................................
  2136. // DEPENDENT KEYS
  2137. //
  2138. // data structure:
  2139. // meta.deps = {
  2140. // 'depKey': {
  2141. // 'keyName': count,
  2142. // __emberproto__: SRC_OBJ [to detect clones]
  2143. // },
  2144. // __emberproto__: SRC_OBJ
  2145. // }
  2146. /**
  2147. @private
  2148. This function returns a map of unique dependencies for a
  2149. given object and key.
  2150. */
  2151. function keysForDep(obj, depsMeta, depKey) {
  2152. var keys = depsMeta[depKey];
  2153. if (!keys) {
  2154. // if there are no dependencies yet for a the given key
  2155. // create a new empty list of dependencies for the key
  2156. keys = depsMeta[depKey] = { __emberproto__: obj };
  2157. } else if (keys.__emberproto__ !== obj) {
  2158. // otherwise if the dependency list is inherited from
  2159. // a superclass, clone the hash
  2160. keys = depsMeta[depKey] = o_create(keys);
  2161. keys.__emberproto__ = obj;
  2162. }
  2163. return keys;
  2164. }
  2165. /**
  2166. @private
  2167. return obj[META_KEY].deps
  2168. */
  2169. function metaForDeps(obj, meta) {
  2170. var deps = meta.deps;
  2171. // If the current object has no dependencies...
  2172. if (!deps) {
  2173. // initialize the dependencies with a pointer back to
  2174. // the current object
  2175. deps = meta.deps = { __emberproto__: obj };
  2176. } else if (deps.__emberproto__ !== obj) {
  2177. // otherwise if the dependencies are inherited from the
  2178. // object's superclass, clone the deps
  2179. deps = meta.deps = o_create(deps);
  2180. deps.__emberproto__ = obj;
  2181. }
  2182. return deps;
  2183. }
  2184. /** @private */
  2185. function addDependentKeys(desc, obj, keyName, meta) {
  2186. // the descriptor has a list of dependent keys, so
  2187. // add all of its dependent keys.
  2188. var depKeys = desc._dependentKeys, depsMeta, idx, len, depKey, keys;
  2189. if (!depKeys) return;
  2190. depsMeta = metaForDeps(obj, meta);
  2191. for(idx = 0, len = depKeys.length; idx < len; idx++) {
  2192. depKey = depKeys[idx];
  2193. // Lookup keys meta for depKey
  2194. keys = keysForDep(obj, depsMeta, depKey);
  2195. // Increment the number of times depKey depends on keyName.
  2196. keys[keyName] = (keys[keyName] || 0) + 1;
  2197. // Watch the depKey
  2198. watch(obj, depKey);
  2199. }
  2200. }
  2201. /** @private */
  2202. function removeDependentKeys(desc, obj, keyName, meta) {
  2203. // the descriptor has a list of dependent keys, so
  2204. // add all of its dependent keys.
  2205. var depKeys = desc._dependentKeys, depsMeta, idx, len, depKey, keys;
  2206. if (!depKeys) return;
  2207. depsMeta = metaForDeps(obj, meta);
  2208. for(idx = 0, len = depKeys.length; idx < len; idx++) {
  2209. depKey = depKeys[idx];
  2210. // Lookup keys meta for depKey
  2211. keys = keysForDep(obj, depsMeta, depKey);
  2212. // Increment the number of times depKey depends on keyName.
  2213. keys[keyName] = (keys[keyName] || 0) - 1;
  2214. // Watch the depKey
  2215. unwatch(obj, depKey);
  2216. }
  2217. }
  2218. // ..........................................................
  2219. // COMPUTED PROPERTY
  2220. //
  2221. /** @private */
  2222. function ComputedProperty(func, opts) {
  2223. this.func = func;
  2224. this._cacheable = (opts && opts.cacheable !== undefined) ? opts.cacheable : Ember.CP_DEFAULT_CACHEABLE;
  2225. this._dependentKeys = opts && opts.dependentKeys;
  2226. }
  2227. /**
  2228. @constructor
  2229. */
  2230. Ember.ComputedProperty = ComputedProperty;
  2231. ComputedProperty.prototype = new Ember.Descriptor();
  2232. /**
  2233. @extends Ember.ComputedProperty
  2234. @private
  2235. */
  2236. var ComputedPropertyPrototype = ComputedProperty.prototype;
  2237. /**
  2238. Call on a computed property to set it into cacheable mode. When in this
  2239. mode the computed property will automatically cache the return value of
  2240. your function until one of the dependent keys changes.
  2241. MyApp.president = Ember.Object.create({
  2242. fullName: function() {
  2243. return this.get('firstName') + ' ' + this.get('lastName');
  2244. // After calculating the value of this function, Ember.js will
  2245. // return that value without re-executing this function until
  2246. // one of the dependent properties change.
  2247. }.property('firstName', 'lastName').cacheable()
  2248. });
  2249. Properties are cacheable by default.
  2250. @memberOf Ember.ComputedProperty.prototype
  2251. @name cacheable
  2252. @function
  2253. @param {Boolean} aFlag optional set to false to disable caching
  2254. @returns {Ember.ComputedProperty} receiver
  2255. */
  2256. ComputedPropertyPrototype.cacheable = function(aFlag) {
  2257. this._cacheable = aFlag !== false;
  2258. return this;
  2259. };
  2260. /**
  2261. Call on a computed property to set it into non-cached mode. When in this
  2262. mode the computed property will not automatically cache the return value.
  2263. MyApp.outsideService = Ember.Object.create({
  2264. value: function() {
  2265. return OutsideService.getValue();
  2266. }.property().volatile()
  2267. });
  2268. @memberOf Ember.ComputedProperty.prototype
  2269. @name volatile
  2270. @function
  2271. @returns {Ember.ComputedProperty} receiver
  2272. */
  2273. ComputedPropertyPrototype.volatile = function() {
  2274. return this.cacheable(false);
  2275. };
  2276. /**
  2277. Sets the dependent keys on this computed property. Pass any number of
  2278. arguments containing key paths that this computed property depends on.
  2279. MyApp.president = Ember.Object.create({
  2280. fullName: Ember.computed(function() {
  2281. return this.get('firstName') + ' ' + this.get('lastName');
  2282. // Tell Ember.js that this computed property depends on firstName
  2283. // and lastName
  2284. }).property('firstName', 'lastName')
  2285. });
  2286. @memberOf Ember.ComputedProperty.prototype
  2287. @name property
  2288. @function
  2289. @param {String} path... zero or more property paths
  2290. @returns {Ember.ComputedProperty} receiver
  2291. */
  2292. ComputedPropertyPrototype.property = function() {
  2293. var args = [];
  2294. for (var i = 0, l = arguments.length; i < l; i++) {
  2295. args.push(arguments[i]);
  2296. }
  2297. this._dependentKeys = args;
  2298. return this;
  2299. };
  2300. /**
  2301. In some cases, you may want to annotate computed properties with additional
  2302. metadata about how they function or what values they operate on. For example,
  2303. computed property functions may close over variables that are then no longer
  2304. available for introspection.
  2305. You can pass a hash of these values to a computed property like this:
  2306. person: function() {
  2307. var personId = this.get('personId');
  2308. return App.Person.create({ id: personId });
  2309. }.property().meta({ type: App.Person })
  2310. The hash that you pass to the `meta()` function will be saved on the
  2311. computed property descriptor under the `_meta` key. Ember runtime
  2312. exposes a public API for retrieving these values from classes,
  2313. via the `metaForProperty()` function.
  2314. @memberOf Ember.ComputedProperty.prototype
  2315. @name meta
  2316. @function
  2317. @param {Hash} meta
  2318. @returns {Ember.ComputedProperty} property descriptor instance
  2319. */
  2320. ComputedPropertyPrototype.meta = function(meta) {
  2321. if (arguments.length === 0) {
  2322. return this._meta || {};
  2323. } else {
  2324. this._meta = meta;
  2325. return this;
  2326. }
  2327. };
  2328. /** @private - impl descriptor API */
  2329. ComputedPropertyPrototype.willWatch = function(obj, keyName) {
  2330. // watch already creates meta for this instance
  2331. var meta = obj[META_KEY];
  2332. Ember.assert('watch should have setup meta to be writable', meta.source === obj);
  2333. if (!(keyName in meta.cache)) {
  2334. addDependentKeys(this, obj, keyName, meta);
  2335. }
  2336. };
  2337. ComputedPropertyPrototype.didUnwatch = function(obj, keyName) {
  2338. var meta = obj[META_KEY];
  2339. Ember.assert('unwatch should have setup meta to be writable', meta.source === obj);
  2340. if (!(keyName in meta.cache)) {
  2341. // unwatch already creates meta for this instance
  2342. removeDependentKeys(this, obj, keyName, meta);
  2343. }
  2344. };
  2345. /** @private - impl descriptor API */
  2346. ComputedPropertyPrototype.didChange = function(obj, keyName) {
  2347. // _suspended is set via a CP.set to ensure we don't clear
  2348. // the cached value set by the setter
  2349. if (this._cacheable && this._suspended !== obj) {
  2350. var meta = metaFor(obj);
  2351. if (keyName in meta.cache) {
  2352. delete meta.cache[keyName];
  2353. if (!meta.watching[keyName]) {
  2354. removeDependentKeys(this, obj, keyName, meta);
  2355. }
  2356. }
  2357. }
  2358. };
  2359. /** @private - impl descriptor API */
  2360. ComputedPropertyPrototype.get = function(obj, keyName) {
  2361. var ret, cache, meta;
  2362. if (this._cacheable) {
  2363. meta = metaFor(obj);
  2364. cache = meta.cache;
  2365. if (keyName in cache) { return cache[keyName]; }
  2366. ret = cache[keyName] = this.func.call(obj, keyName);
  2367. if (!meta.watching[keyName]) {
  2368. addDependentKeys(this, obj, keyName, meta);
  2369. }
  2370. } else {
  2371. ret = this.func.call(obj, keyName);
  2372. }
  2373. return ret;
  2374. };
  2375. /** @private - impl descriptor API */
  2376. ComputedPropertyPrototype.set = function(obj, keyName, value) {
  2377. var cacheable = this._cacheable,
  2378. meta = metaFor(obj, cacheable),
  2379. watched = meta.watching[keyName],
  2380. oldSuspended = this._suspended,
  2381. hadCachedValue,
  2382. ret;
  2383. this._suspended = obj;
  2384. if (watched) { Ember.propertyWillChange(obj, keyName); }
  2385. if (cacheable) {
  2386. if (keyName in meta.cache) {
  2387. delete meta.cache[keyName];
  2388. hadCachedValue = true;
  2389. }
  2390. }
  2391. ret = this.func.call(obj, keyName, value);
  2392. if (cacheable) {
  2393. if (!watched && !hadCachedValue) {
  2394. addDependentKeys(this, obj, keyName, meta);
  2395. }
  2396. meta.cache[keyName] = ret;
  2397. }
  2398. if (watched) { Ember.propertyDidChange(obj, keyName); }
  2399. this._suspended = oldSuspended;
  2400. return ret;
  2401. };
  2402. /** @private - called when property is defined */
  2403. ComputedPropertyPrototype.setup = function(obj, keyName) {
  2404. var meta = obj[META_KEY];
  2405. if (meta && meta.watching[keyName]) {
  2406. addDependentKeys(this, obj, keyName, metaFor(obj));
  2407. }
  2408. };
  2409. /** @private - called before property is overridden */
  2410. ComputedPropertyPrototype.teardown = function(obj, keyName) {
  2411. var meta = metaFor(obj);
  2412. if (meta.watching[keyName] || keyName in meta.cache) {
  2413. removeDependentKeys(this, obj, keyName, meta);
  2414. }
  2415. if (this._cacheable) { delete meta.cache[keyName]; }
  2416. return null; // no value to restore
  2417. };
  2418. /**
  2419. This helper returns a new property descriptor that wraps the passed
  2420. computed property function. You can use this helper to define properties
  2421. with mixins or via Ember.defineProperty().
  2422. The function you pass will be used to both get and set property values.
  2423. The function should accept two parameters, key and value. If value is not
  2424. undefined you should set the value first. In either case return the
  2425. current value of the property.
  2426. @param {Function} func
  2427. The computed property function.
  2428. @returns {Ember.ComputedProperty} property descriptor instance
  2429. */
  2430. Ember.computed = function(func) {
  2431. var args;
  2432. if (arguments.length > 1) {
  2433. args = a_slice.call(arguments, 0, -1);
  2434. func = a_slice.call(arguments, -1)[0];
  2435. }
  2436. var cp = new ComputedProperty(func);
  2437. if (args) {
  2438. cp.property.apply(cp, args);
  2439. }
  2440. return cp;
  2441. };
  2442. /**
  2443. Returns the cached value for a property, if one exists.
  2444. This can be useful for peeking at the value of a computed
  2445. property that is generated lazily, without accidentally causing
  2446. it to be created.
  2447. @param {Object} obj the object whose property you want to check
  2448. @param {String} key the name of the property whose cached value you want
  2449. to return
  2450. */
  2451. Ember.cacheFor = function cacheFor(obj, key) {
  2452. var cache = metaFor(obj, false).cache;
  2453. if (cache && key in cache) {
  2454. return cache[key];
  2455. }
  2456. };
  2457. Ember.computed.not = function(dependentKey) {
  2458. return Ember.computed(dependentKey, function(key) {
  2459. return !get(this, dependentKey);
  2460. }).cacheable();
  2461. };
  2462. Ember.computed.empty = function(dependentKey) {
  2463. return Ember.computed(dependentKey, function(key) {
  2464. var val = get(this, dependentKey);
  2465. return val === undefined || val === null || val === '' || (Ember.isArray(val) && get(val, 'length') === 0);
  2466. }).cacheable();
  2467. };
  2468. Ember.computed.bool = function(dependentKey) {
  2469. return Ember.computed(dependentKey, function(key) {
  2470. return !!get(this, dependentKey);
  2471. }).cacheable();
  2472. };
  2473. })();
  2474. (function() {
  2475. // ==========================================================================
  2476. // Project: Ember Metal
  2477. // Copyright: ©2011 Strobe Inc. and contributors.
  2478. // License: Licensed under MIT license (see license.js)
  2479. // ==========================================================================
  2480. var o_create = Ember.create,
  2481. meta = Ember.meta,
  2482. metaPath = Ember.metaPath,
  2483. guidFor = Ember.guidFor,
  2484. a_slice = [].slice;
  2485. /**
  2486. The event system uses a series of nested hashes to store listeners on an
  2487. object. When a listener is registered, or when an event arrives, these
  2488. hashes are consulted to determine which target and action pair to invoke.
  2489. The hashes are stored in the object's meta hash, and look like this:
  2490. // Object's meta hash
  2491. {
  2492. listeners: { // variable name: `listenerSet`
  2493. "foo:changed": { // variable name: `targetSet`
  2494. [targetGuid]: { // variable name: `actionSet`
  2495. [methodGuid]: { // variable name: `action`
  2496. target: [Object object],
  2497. method: [Function function]
  2498. }
  2499. }
  2500. }
  2501. }
  2502. }
  2503. */
  2504. // Gets the set of all actions, keyed on the guid of each action's
  2505. // method property.
  2506. /** @private */
  2507. function actionSetFor(obj, eventName, target, writable) {
  2508. return metaPath(obj, ['listeners', eventName, guidFor(target)], writable);
  2509. }
  2510. // Gets the set of all targets, keyed on the guid of each action's
  2511. // target property.
  2512. /** @private */
  2513. function targetSetFor(obj, eventName) {
  2514. var listenerSet = meta(obj, false).listeners;
  2515. if (!listenerSet) { return false; }
  2516. return listenerSet[eventName] || false;
  2517. }
  2518. // TODO: This knowledge should really be a part of the
  2519. // meta system.
  2520. var SKIP_PROPERTIES = { __ember_source__: true };
  2521. /** @private */
  2522. function iterateSet(obj, eventName, callback, params) {
  2523. var targetSet = targetSetFor(obj, eventName);
  2524. if (!targetSet) { return false; }
  2525. // Iterate through all elements of the target set
  2526. for(var targetGuid in targetSet) {
  2527. if (SKIP_PROPERTIES[targetGuid]) { continue; }
  2528. var actionSet = targetSet[targetGuid];
  2529. if (actionSet) {
  2530. // Iterate through the elements of the action set
  2531. for(var methodGuid in actionSet) {
  2532. if (SKIP_PROPERTIES[methodGuid]) { continue; }
  2533. var action = actionSet[methodGuid];
  2534. if (action) {
  2535. if (callback(action, params, obj) === true) {
  2536. return true;
  2537. }
  2538. }
  2539. }
  2540. }
  2541. }
  2542. return false;
  2543. }
  2544. /** @private */
  2545. function invokeAction(action, params, sender) {
  2546. var method = action.method, target = action.target;
  2547. // If there is no target, the target is the object
  2548. // on which the event was fired.
  2549. if (!target) { target = sender; }
  2550. if ('string' === typeof method) { method = target[method]; }
  2551. if (params) {
  2552. method.apply(target, params);
  2553. } else {
  2554. method.apply(target);
  2555. }
  2556. }
  2557. /**
  2558. The sendEvent arguments > 2 are passed to an event listener.
  2559. @memberOf Ember
  2560. */
  2561. function addListener(obj, eventName, target, method) {
  2562. Ember.assert("You must pass at least an object and event name to Ember.addListener", !!obj && !!eventName);
  2563. if (!method && 'function' === typeof target) {
  2564. method = target;
  2565. target = null;
  2566. }
  2567. var actionSet = actionSetFor(obj, eventName, target, true),
  2568. methodGuid = guidFor(method);
  2569. if (!actionSet[methodGuid]) {
  2570. actionSet[methodGuid] = { target: target, method: method };
  2571. }
  2572. if ('function' === typeof obj.didAddListener) {
  2573. obj.didAddListener(eventName, target, method);
  2574. }
  2575. }
  2576. /** @memberOf Ember */
  2577. function removeListener(obj, eventName, target, method) {
  2578. Ember.assert("You must pass at least an object and event name to Ember.removeListener", !!obj && !!eventName);
  2579. if (!method && 'function' === typeof target) {
  2580. method = target;
  2581. target = null;
  2582. }
  2583. var actionSet = actionSetFor(obj, eventName, target, true),
  2584. methodGuid = guidFor(method);
  2585. // we can't simply delete this parameter, because if we do, we might
  2586. // re-expose the property from the prototype chain.
  2587. if (actionSet && actionSet[methodGuid]) { actionSet[methodGuid] = null; }
  2588. if ('function' === typeof obj.didRemoveListener) {
  2589. obj.didRemoveListener(eventName, target, method);
  2590. }
  2591. }
  2592. // Suspend listener during callback.
  2593. //
  2594. // This should only be used by the target of the event listener
  2595. // when it is taking an action that would cause the event, e.g.
  2596. // an object might suspend its property change listener while it is
  2597. // setting that property.
  2598. /** @private */
  2599. function suspendListener(obj, eventName, target, method, callback) {
  2600. if (!method && 'function' === typeof target) {
  2601. method = target;
  2602. target = null;
  2603. }
  2604. var actionSet = actionSetFor(obj, eventName, target, true),
  2605. methodGuid = guidFor(method),
  2606. action = actionSet && actionSet[methodGuid];
  2607. actionSet[methodGuid] = null;
  2608. try {
  2609. return callback.call(target);
  2610. } finally {
  2611. actionSet[methodGuid] = action;
  2612. }
  2613. }
  2614. // returns a list of currently watched events
  2615. /** @memberOf Ember */
  2616. function watchedEvents(obj) {
  2617. var listeners = meta(obj, false).listeners, ret = [];
  2618. if (listeners) {
  2619. for(var eventName in listeners) {
  2620. if (!SKIP_PROPERTIES[eventName] && listeners[eventName]) {
  2621. ret.push(eventName);
  2622. }
  2623. }
  2624. }
  2625. return ret;
  2626. }
  2627. /** @memberOf Ember */
  2628. function sendEvent(obj, eventName, params) {
  2629. // first give object a chance to handle it
  2630. if (obj !== Ember && 'function' === typeof obj.sendEvent) {
  2631. obj.sendEvent(eventName, params);
  2632. }
  2633. iterateSet(obj, eventName, invokeAction, params);
  2634. return true;
  2635. }
  2636. /** @memberOf Ember */
  2637. function deferEvent(obj, eventName, params) {
  2638. var actions = [];
  2639. iterateSet(obj, eventName, function (action) {
  2640. actions.push(action);
  2641. });
  2642. return function() {
  2643. if (obj.isDestroyed) { return; }
  2644. if (obj !== Ember && 'function' === typeof obj.sendEvent) {
  2645. obj.sendEvent(eventName, params);
  2646. }
  2647. for (var i=0, len=actions.length; i < len; ++i) {
  2648. invokeAction(actions[i], params, obj);
  2649. }
  2650. };
  2651. }
  2652. /** @memberOf Ember */
  2653. function hasListeners(obj, eventName) {
  2654. if (iterateSet(obj, eventName, function() { return true; })) {
  2655. return true;
  2656. }
  2657. // no listeners! might as well clean this up so it is faster later.
  2658. var set = metaPath(obj, ['listeners'], true);
  2659. set[eventName] = null;
  2660. return false;
  2661. }
  2662. /** @memberOf Ember */
  2663. function listenersFor(obj, eventName) {
  2664. var ret = [];
  2665. iterateSet(obj, eventName, function (action) {
  2666. ret.push([action.target, action.method]);
  2667. });
  2668. return ret;
  2669. }
  2670. Ember.addListener = addListener;
  2671. Ember.removeListener = removeListener;
  2672. Ember._suspendListener = suspendListener;
  2673. Ember.sendEvent = sendEvent;
  2674. Ember.hasListeners = hasListeners;
  2675. Ember.watchedEvents = watchedEvents;
  2676. Ember.listenersFor = listenersFor;
  2677. Ember.deferEvent = deferEvent;
  2678. })();
  2679. (function() {
  2680. // ==========================================================================
  2681. // Project: Ember Runtime
  2682. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  2683. // Portions ©2008-2010 Apple Inc. All rights reserved.
  2684. // License: Licensed under MIT license (see license.js)
  2685. // ==========================================================================
  2686. // Ember.Logger
  2687. // Ember.watch.flushPending
  2688. // Ember.beginPropertyChanges, Ember.endPropertyChanges
  2689. // Ember.guidFor
  2690. // ..........................................................
  2691. // HELPERS
  2692. //
  2693. var slice = [].slice,
  2694. forEach = Ember.ArrayPolyfills.forEach;
  2695. // invokes passed params - normalizing so you can pass target/func,
  2696. // target/string or just func
  2697. /** @private */
  2698. function invoke(target, method, args, ignore) {
  2699. if (method === undefined) {
  2700. method = target;
  2701. target = undefined;
  2702. }
  2703. if ('string' === typeof method) { method = target[method]; }
  2704. if (args && ignore > 0) {
  2705. args = args.length > ignore ? slice.call(args, ignore) : null;
  2706. }
  2707. // Unfortunately in some browsers we lose the backtrace if we rethrow the existing error,
  2708. // so in the event that we don't have an `onerror` handler we don't wrap in a try/catch
  2709. if ('function' === typeof Ember.onerror) {
  2710. try {
  2711. // IE8's Function.prototype.apply doesn't accept undefined/null arguments.
  2712. return method.apply(target || this, args || []);
  2713. } catch (error) {
  2714. Ember.onerror(error);
  2715. }
  2716. } else {
  2717. // IE8's Function.prototype.apply doesn't accept undefined/null arguments.
  2718. return method.apply(target || this, args || []);
  2719. }
  2720. }
  2721. // ..........................................................
  2722. // RUNLOOP
  2723. //
  2724. var timerMark; // used by timers...
  2725. /** @private */
  2726. var RunLoop = function(prev) {
  2727. this._prev = prev || null;
  2728. this.onceTimers = {};
  2729. };
  2730. RunLoop.prototype = {
  2731. end: function() {
  2732. this.flush();
  2733. },
  2734. prev: function() {
  2735. return this._prev;
  2736. },
  2737. // ..........................................................
  2738. // Delayed Actions
  2739. //
  2740. schedule: function(queueName, target, method) {
  2741. var queues = this._queues, queue;
  2742. if (!queues) { queues = this._queues = {}; }
  2743. queue = queues[queueName];
  2744. if (!queue) { queue = queues[queueName] = []; }
  2745. var args = arguments.length > 3 ? slice.call(arguments, 3) : null;
  2746. queue.push({ target: target, method: method, args: args });
  2747. return this;
  2748. },
  2749. flush: function(queueName) {
  2750. var queueNames, idx, len, queue, log;
  2751. if (!this._queues) { return this; } // nothing to do
  2752. function iter(item) {
  2753. invoke(item.target, item.method, item.args);
  2754. }
  2755. Ember.watch.flushPending(); // make sure all chained watchers are setup
  2756. if (queueName) {
  2757. while (this._queues && (queue = this._queues[queueName])) {
  2758. this._queues[queueName] = null;
  2759. // the sync phase is to allow property changes to propagate. don't
  2760. // invoke observers until that is finished.
  2761. if (queueName === 'sync') {
  2762. log = Ember.LOG_BINDINGS;
  2763. if (log) { Ember.Logger.log('Begin: Flush Sync Queue'); }
  2764. Ember.beginPropertyChanges();
  2765. try {
  2766. forEach.call(queue, iter);
  2767. } finally {
  2768. Ember.endPropertyChanges();
  2769. }
  2770. if (log) { Ember.Logger.log('End: Flush Sync Queue'); }
  2771. } else {
  2772. forEach.call(queue, iter);
  2773. }
  2774. }
  2775. } else {
  2776. queueNames = Ember.run.queues;
  2777. len = queueNames.length;
  2778. idx = 0;
  2779. outerloop:
  2780. while (idx < len) {
  2781. queueName = queueNames[idx];
  2782. queue = this._queues && this._queues[queueName];
  2783. delete this._queues[queueName];
  2784. if (queue) {
  2785. // the sync phase is to allow property changes to propagate. don't
  2786. // invoke observers until that is finished.
  2787. if (queueName === 'sync') {
  2788. log = Ember.LOG_BINDINGS;
  2789. if (log) { Ember.Logger.log('Begin: Flush Sync Queue'); }
  2790. Ember.beginPropertyChanges();
  2791. try {
  2792. forEach.call(queue, iter);
  2793. } finally {
  2794. Ember.endPropertyChanges();
  2795. }
  2796. if (log) { Ember.Logger.log('End: Flush Sync Queue'); }
  2797. } else {
  2798. forEach.call(queue, iter);
  2799. }
  2800. }
  2801. // Loop through prior queues
  2802. for (var i = 0; i <= idx; i++) {
  2803. if (this._queues && this._queues[queueNames[i]]) {
  2804. // Start over at the first queue with contents
  2805. idx = i;
  2806. continue outerloop;
  2807. }
  2808. }
  2809. idx++;
  2810. }
  2811. }
  2812. timerMark = null;
  2813. return this;
  2814. }
  2815. };
  2816. Ember.RunLoop = RunLoop;
  2817. // ..........................................................
  2818. // Ember.run - this is ideally the only public API the dev sees
  2819. //
  2820. /**
  2821. * @namespace Ember.run is both a function and a namespace for
  2822. * RunLoop-related functions.
  2823. * @name Ember.run
  2824. */
  2825. /**
  2826. Runs the passed target and method inside of a RunLoop, ensuring any
  2827. deferred actions including bindings and views updates are flushed at the
  2828. end.
  2829. Normally you should not need to invoke this method yourself. However if
  2830. you are implementing raw event handlers when interfacing with other
  2831. libraries or plugins, you should probably wrap all of your code inside this
  2832. call.
  2833. Ember.run(function(){
  2834. // code to be execute within a RunLoop
  2835. });
  2836. @name run
  2837. @methodOf Ember.run
  2838. @param {Object} target
  2839. (Optional) target of method to call
  2840. @param {Function|String} method
  2841. Method to invoke. May be a function or a string. If you pass a string
  2842. then it will be looked up on the passed target.
  2843. @param {Object...} args
  2844. Any additional arguments you wish to pass to the method.
  2845. @returns {Object} return value from invoking the passed function.
  2846. */
  2847. Ember.run = function(target, method) {
  2848. var ret, loop;
  2849. run.begin();
  2850. try {
  2851. if (target || method) { ret = invoke(target, method, arguments, 2); }
  2852. } finally {
  2853. run.end();
  2854. }
  2855. return ret;
  2856. };
  2857. /** @private */
  2858. var run = Ember.run;
  2859. /**
  2860. Begins a new RunLoop. Any deferred actions invoked after the begin will
  2861. be buffered until you invoke a matching call to Ember.run.end(). This is
  2862. an lower-level way to use a RunLoop instead of using Ember.run().
  2863. Ember.run.begin();
  2864. // code to be execute within a RunLoop
  2865. Ember.run.end();
  2866. @returns {void}
  2867. */
  2868. Ember.run.begin = function() {
  2869. run.currentRunLoop = new RunLoop(run.currentRunLoop);
  2870. };
  2871. /**
  2872. Ends a RunLoop. This must be called sometime after you call Ember.run.begin()
  2873. to flush any deferred actions. This is a lower-level way to use a RunLoop
  2874. instead of using Ember.run().
  2875. Ember.run.begin();
  2876. // code to be execute within a RunLoop
  2877. Ember.run.end();
  2878. @returns {void}
  2879. */
  2880. Ember.run.end = function() {
  2881. Ember.assert('must have a current run loop', run.currentRunLoop);
  2882. try {
  2883. run.currentRunLoop.end();
  2884. }
  2885. finally {
  2886. run.currentRunLoop = run.currentRunLoop.prev();
  2887. }
  2888. };
  2889. /**
  2890. Array of named queues. This array determines the order in which queues
  2891. are flushed at the end of the RunLoop. You can define your own queues by
  2892. simply adding the queue name to this array. Normally you should not need
  2893. to inspect or modify this property.
  2894. @type Array
  2895. @default ['sync', 'actions', 'destroy', 'timers']
  2896. */
  2897. Ember.run.queues = ['sync', 'actions', 'destroy', 'timers'];
  2898. /**
  2899. Adds the passed target/method and any optional arguments to the named
  2900. queue to be executed at the end of the RunLoop. If you have not already
  2901. started a RunLoop when calling this method one will be started for you
  2902. automatically.
  2903. At the end of a RunLoop, any methods scheduled in this way will be invoked.
  2904. Methods will be invoked in an order matching the named queues defined in
  2905. the run.queues property.
  2906. Ember.run.schedule('timers', this, function(){
  2907. // this will be executed at the end of the RunLoop, when timers are run
  2908. console.log("scheduled on timers queue");
  2909. });
  2910. Ember.run.schedule('sync', this, function(){
  2911. // this will be executed at the end of the RunLoop, when bindings are synced
  2912. console.log("scheduled on sync queue");
  2913. });
  2914. // Note the functions will be run in order based on the run queues order. Output would be:
  2915. // scheduled on sync queue
  2916. // scheduled on timers queue
  2917. @param {String} queue
  2918. The name of the queue to schedule against. Default queues are 'sync' and
  2919. 'actions'
  2920. @param {Object} target
  2921. (Optional) target object to use as the context when invoking a method.
  2922. @param {String|Function} method
  2923. The method to invoke. If you pass a string it will be resolved on the
  2924. target object at the time the scheduled item is invoked allowing you to
  2925. change the target function.
  2926. @param {Object} arguments...
  2927. Optional arguments to be passed to the queued method.
  2928. @returns {void}
  2929. */
  2930. Ember.run.schedule = function(queue, target, method) {
  2931. var loop = run.autorun();
  2932. loop.schedule.apply(loop, arguments);
  2933. };
  2934. var scheduledAutorun;
  2935. /** @private */
  2936. function autorun() {
  2937. scheduledAutorun = null;
  2938. if (run.currentRunLoop) { run.end(); }
  2939. }
  2940. // Used by global test teardown
  2941. /** @private */
  2942. Ember.run.hasScheduledTimers = function() {
  2943. return !!(scheduledAutorun || scheduledLater || scheduledNext);
  2944. };
  2945. // Used by global test teardown
  2946. /** @private */
  2947. Ember.run.cancelTimers = function () {
  2948. if (scheduledAutorun) {
  2949. clearTimeout(scheduledAutorun);
  2950. scheduledAutorun = null;
  2951. }
  2952. if (scheduledLater) {
  2953. clearTimeout(scheduledLater);
  2954. scheduledLater = null;
  2955. }
  2956. if (scheduledNext) {
  2957. clearTimeout(scheduledNext);
  2958. scheduledNext = null;
  2959. }
  2960. timers = {};
  2961. };
  2962. /**
  2963. Begins a new RunLoop if necessary and schedules a timer to flush the
  2964. RunLoop at a later time. This method is used by parts of Ember to
  2965. ensure the RunLoop always finishes. You normally do not need to call this
  2966. method directly. Instead use Ember.run().
  2967. Ember.run.autorun();
  2968. @returns {Ember.RunLoop} the new current RunLoop
  2969. */
  2970. Ember.run.autorun = function() {
  2971. if (!run.currentRunLoop) {
  2972. Ember.assert("You have turned on testing mode, which disabled the run-loop's autorun. You will need to wrap any code with asynchronous side-effects in an Ember.run", !Ember.testing);
  2973. run.begin();
  2974. if (!scheduledAutorun) {
  2975. scheduledAutorun = setTimeout(autorun, 1);
  2976. }
  2977. }
  2978. return run.currentRunLoop;
  2979. };
  2980. /**
  2981. Immediately flushes any events scheduled in the 'sync' queue. Bindings
  2982. use this queue so this method is a useful way to immediately force all
  2983. bindings in the application to sync.
  2984. You should call this method anytime you need any changed state to propagate
  2985. throughout the app immediately without repainting the UI.
  2986. Ember.run.sync();
  2987. @returns {void}
  2988. */
  2989. Ember.run.sync = function() {
  2990. run.autorun();
  2991. run.currentRunLoop.flush('sync');
  2992. };
  2993. // ..........................................................
  2994. // TIMERS
  2995. //
  2996. var timers = {}; // active timers...
  2997. var scheduledLater;
  2998. /** @private */
  2999. function invokeLaterTimers() {
  3000. scheduledLater = null;
  3001. var now = (+ new Date()), earliest = -1;
  3002. for (var key in timers) {
  3003. if (!timers.hasOwnProperty(key)) { continue; }
  3004. var timer = timers[key];
  3005. if (timer && timer.expires) {
  3006. if (now >= timer.expires) {
  3007. delete timers[key];
  3008. invoke(timer.target, timer.method, timer.args, 2);
  3009. } else {
  3010. if (earliest<0 || (timer.expires < earliest)) earliest=timer.expires;
  3011. }
  3012. }
  3013. }
  3014. // schedule next timeout to fire...
  3015. if (earliest > 0) { scheduledLater = setTimeout(invokeLaterTimers, earliest-(+ new Date())); }
  3016. }
  3017. /**
  3018. Invokes the passed target/method and optional arguments after a specified
  3019. period if time. The last parameter of this method must always be a number
  3020. of milliseconds.
  3021. You should use this method whenever you need to run some action after a
  3022. period of time instead of using setTimeout(). This method will ensure that
  3023. items that expire during the same script execution cycle all execute
  3024. together, which is often more efficient than using a real setTimeout.
  3025. Ember.run.later(myContext, function(){
  3026. // code here will execute within a RunLoop in about 500ms with this == myContext
  3027. }, 500);
  3028. @param {Object} target
  3029. (optional) target of method to invoke
  3030. @param {Function|String} method
  3031. The method to invoke. If you pass a string it will be resolved on the
  3032. target at the time the method is invoked.
  3033. @param {Object...} args
  3034. Optional arguments to pass to the timeout.
  3035. @param {Number} wait
  3036. Number of milliseconds to wait.
  3037. @returns {String} a string you can use to cancel the timer in Ember.run.cancel() later.
  3038. */
  3039. Ember.run.later = function(target, method) {
  3040. var args, expires, timer, guid, wait;
  3041. // setTimeout compatibility...
  3042. if (arguments.length===2 && 'function' === typeof target) {
  3043. wait = method;
  3044. method = target;
  3045. target = undefined;
  3046. args = [target, method];
  3047. } else {
  3048. args = slice.call(arguments);
  3049. wait = args.pop();
  3050. }
  3051. expires = (+ new Date()) + wait;
  3052. timer = { target: target, method: method, expires: expires, args: args };
  3053. guid = Ember.guidFor(timer);
  3054. timers[guid] = timer;
  3055. run.once(timers, invokeLaterTimers);
  3056. return guid;
  3057. };
  3058. /** @private */
  3059. function invokeOnceTimer(guid, onceTimers) {
  3060. if (onceTimers[this.tguid]) { delete onceTimers[this.tguid][this.mguid]; }
  3061. if (timers[guid]) { invoke(this.target, this.method, this.args, 2); }
  3062. delete timers[guid];
  3063. }
  3064. /**
  3065. Schedules an item to run one time during the current RunLoop. Calling
  3066. this method with the same target/method combination will have no effect.
  3067. Note that although you can pass optional arguments these will not be
  3068. considered when looking for duplicates. New arguments will replace previous
  3069. calls.
  3070. Ember.run(function(){
  3071. var doFoo = function() { foo(); }
  3072. Ember.run.once(myContext, doFoo);
  3073. Ember.run.once(myContext, doFoo);
  3074. // doFoo will only be executed once at the end of the RunLoop
  3075. });
  3076. @param {Object} target
  3077. (optional) target of method to invoke
  3078. @param {Function|String} method
  3079. The method to invoke. If you pass a string it will be resolved on the
  3080. target at the time the method is invoked.
  3081. @param {Object...} args
  3082. Optional arguments to pass to the timeout.
  3083. @returns {Object} timer
  3084. */
  3085. Ember.run.once = function(target, method) {
  3086. var tguid = Ember.guidFor(target),
  3087. mguid = Ember.guidFor(method),
  3088. onceTimers = run.autorun().onceTimers,
  3089. guid = onceTimers[tguid] && onceTimers[tguid][mguid],
  3090. timer;
  3091. if (guid && timers[guid]) {
  3092. timers[guid].args = slice.call(arguments); // replace args
  3093. } else {
  3094. timer = {
  3095. target: target,
  3096. method: method,
  3097. args: slice.call(arguments),
  3098. tguid: tguid,
  3099. mguid: mguid
  3100. };
  3101. guid = Ember.guidFor(timer);
  3102. timers[guid] = timer;
  3103. if (!onceTimers[tguid]) { onceTimers[tguid] = {}; }
  3104. onceTimers[tguid][mguid] = guid; // so it isn't scheduled more than once
  3105. run.schedule('actions', timer, invokeOnceTimer, guid, onceTimers);
  3106. }
  3107. return guid;
  3108. };
  3109. var scheduledNext;
  3110. /** @private */
  3111. function invokeNextTimers() {
  3112. scheduledNext = null;
  3113. for(var key in timers) {
  3114. if (!timers.hasOwnProperty(key)) { continue; }
  3115. var timer = timers[key];
  3116. if (timer.next) {
  3117. delete timers[key];
  3118. invoke(timer.target, timer.method, timer.args, 2);
  3119. }
  3120. }
  3121. }
  3122. /**
  3123. Schedules an item to run after control has been returned to the system.
  3124. This is often equivalent to calling setTimeout(function...,1).
  3125. Ember.run.next(myContext, function(){
  3126. // code to be executed in the next RunLoop, which will be scheduled after the current one
  3127. });
  3128. @param {Object} target
  3129. (optional) target of method to invoke
  3130. @param {Function|String} method
  3131. The method to invoke. If you pass a string it will be resolved on the
  3132. target at the time the method is invoked.
  3133. @param {Object...} args
  3134. Optional arguments to pass to the timeout.
  3135. @returns {Object} timer
  3136. */
  3137. Ember.run.next = function(target, method) {
  3138. var guid,
  3139. timer = {
  3140. target: target,
  3141. method: method,
  3142. args: slice.call(arguments),
  3143. next: true
  3144. };
  3145. guid = Ember.guidFor(timer);
  3146. timers[guid] = timer;
  3147. if (!scheduledNext) { scheduledNext = setTimeout(invokeNextTimers, 1); }
  3148. return guid;
  3149. };
  3150. /**
  3151. Cancels a scheduled item. Must be a value returned by `Ember.run.later()`,
  3152. `Ember.run.once()`, or `Ember.run.next()`.
  3153. var runNext = Ember.run.next(myContext, function(){
  3154. // will not be executed
  3155. });
  3156. Ember.run.cancel(runNext);
  3157. var runLater = Ember.run.later(myContext, function(){
  3158. // will not be executed
  3159. }, 500);
  3160. Ember.run.cancel(runLater);
  3161. var runOnce = Ember.run.once(myContext, function(){
  3162. // will not be executed
  3163. });
  3164. Ember.run.cancel(runOnce);
  3165. @param {Object} timer
  3166. Timer object to cancel
  3167. @returns {void}
  3168. */
  3169. Ember.run.cancel = function(timer) {
  3170. delete timers[timer];
  3171. };
  3172. })();
  3173. (function() {
  3174. // ==========================================================================
  3175. // Project: Ember Runtime
  3176. // Copyright: ©2011 Strobe Inc. and contributors.
  3177. // License: Licensed under MIT license (see license.js)
  3178. // ==========================================================================
  3179. // Ember.Logger
  3180. // get, set, trySet
  3181. // guidFor, isArray, meta
  3182. // addObserver, removeObserver
  3183. // Ember.run.schedule
  3184. // ..........................................................
  3185. // CONSTANTS
  3186. //
  3187. /**
  3188. @static
  3189. Debug parameter you can turn on. This will log all bindings that fire to
  3190. the console. This should be disabled in production code. Note that you
  3191. can also enable this from the console or temporarily.
  3192. @type Boolean
  3193. @default false
  3194. */
  3195. Ember.LOG_BINDINGS = false || !!Ember.ENV.LOG_BINDINGS;
  3196. var get = Ember.get,
  3197. set = Ember.set,
  3198. guidFor = Ember.guidFor,
  3199. isGlobalPath = Ember.isGlobalPath;
  3200. /** @private */
  3201. function getWithGlobals(obj, path) {
  3202. return get(isGlobalPath(path) ? window : obj, path);
  3203. }
  3204. // ..........................................................
  3205. // BINDING
  3206. //
  3207. /** @private */
  3208. var Binding = function(toPath, fromPath) {
  3209. this._direction = 'fwd';
  3210. this._from = fromPath;
  3211. this._to = toPath;
  3212. this._directionMap = Ember.Map.create();
  3213. };
  3214. Binding.prototype = /** @scope Ember.Binding.prototype */ {
  3215. /**
  3216. This copies the Binding so it can be connected to another object.
  3217. @returns {Ember.Binding}
  3218. */
  3219. copy: function () {
  3220. var copy = new Binding(this._to, this._from);
  3221. if (this._oneWay) { copy._oneWay = true; }
  3222. return copy;
  3223. },
  3224. // ..........................................................
  3225. // CONFIG
  3226. //
  3227. /**
  3228. This will set "from" property path to the specified value. It will not
  3229. attempt to resolve this property path to an actual object until you
  3230. connect the binding.
  3231. The binding will search for the property path starting at the root object
  3232. you pass when you connect() the binding. It follows the same rules as
  3233. `get()` - see that method for more information.
  3234. @param {String} propertyPath the property path to connect to
  3235. @returns {Ember.Binding} receiver
  3236. */
  3237. from: function(path) {
  3238. this._from = path;
  3239. return this;
  3240. },
  3241. /**
  3242. This will set the "to" property path to the specified value. It will not
  3243. attempt to resolve this property path to an actual object until you
  3244. connect the binding.
  3245. The binding will search for the property path starting at the root object
  3246. you pass when you connect() the binding. It follows the same rules as
  3247. `get()` - see that method for more information.
  3248. @param {String|Tuple} propertyPath A property path or tuple
  3249. @returns {Ember.Binding} this
  3250. */
  3251. to: function(path) {
  3252. this._to = path;
  3253. return this;
  3254. },
  3255. /**
  3256. Configures the binding as one way. A one-way binding will relay changes
  3257. on the "from" side to the "to" side, but not the other way around. This
  3258. means that if you change the "to" side directly, the "from" side may have
  3259. a different value.
  3260. @returns {Ember.Binding} receiver
  3261. */
  3262. oneWay: function() {
  3263. this._oneWay = true;
  3264. return this;
  3265. },
  3266. /** @private */
  3267. toString: function() {
  3268. var oneWay = this._oneWay ? '[oneWay]' : '';
  3269. return "Ember.Binding<" + guidFor(this) + ">(" + this._from + " -> " + this._to + ")" + oneWay;
  3270. },
  3271. // ..........................................................
  3272. // CONNECT AND SYNC
  3273. //
  3274. /**
  3275. Attempts to connect this binding instance so that it can receive and relay
  3276. changes. This method will raise an exception if you have not set the
  3277. from/to properties yet.
  3278. @param {Object} obj The root object for this binding.
  3279. @returns {Ember.Binding} this
  3280. */
  3281. connect: function(obj) {
  3282. Ember.assert('Must pass a valid object to Ember.Binding.connect()', !!obj);
  3283. var fromPath = this._from, toPath = this._to;
  3284. Ember.trySet(obj, toPath, getWithGlobals(obj, fromPath));
  3285. // add an observer on the object to be notified when the binding should be updated
  3286. Ember.addObserver(obj, fromPath, this, this.fromDidChange);
  3287. // if the binding is a two-way binding, also set up an observer on the target
  3288. if (!this._oneWay) { Ember.addObserver(obj, toPath, this, this.toDidChange); }
  3289. this._readyToSync = true;
  3290. return this;
  3291. },
  3292. /**
  3293. Disconnects the binding instance. Changes will no longer be relayed. You
  3294. will not usually need to call this method.
  3295. @param {Object} obj
  3296. The root object you passed when connecting the binding.
  3297. @returns {Ember.Binding} this
  3298. */
  3299. disconnect: function(obj) {
  3300. Ember.assert('Must pass a valid object to Ember.Binding.disconnect()', !!obj);
  3301. var twoWay = !this._oneWay;
  3302. // remove an observer on the object so we're no longer notified of
  3303. // changes that should update bindings.
  3304. Ember.removeObserver(obj, this._from, this, this.fromDidChange);
  3305. // if the binding is two-way, remove the observer from the target as well
  3306. if (twoWay) { Ember.removeObserver(obj, this._to, this, this.toDidChange); }
  3307. this._readyToSync = false; // disable scheduled syncs...
  3308. return this;
  3309. },
  3310. // ..........................................................
  3311. // PRIVATE
  3312. //
  3313. /** @private - called when the from side changes */
  3314. fromDidChange: function(target) {
  3315. this._scheduleSync(target, 'fwd');
  3316. },
  3317. /** @private - called when the to side changes */
  3318. toDidChange: function(target) {
  3319. this._scheduleSync(target, 'back');
  3320. },
  3321. /** @private */
  3322. _scheduleSync: function(obj, dir) {
  3323. var directionMap = this._directionMap;
  3324. var existingDir = directionMap.get(obj);
  3325. // if we haven't scheduled the binding yet, schedule it
  3326. if (!existingDir) {
  3327. Ember.run.schedule('sync', this, this._sync, obj);
  3328. directionMap.set(obj, dir);
  3329. }
  3330. // If both a 'back' and 'fwd' sync have been scheduled on the same object,
  3331. // default to a 'fwd' sync so that it remains deterministic.
  3332. if (existingDir === 'back' && dir === 'fwd') {
  3333. directionMap.set(obj, 'fwd');
  3334. }
  3335. },
  3336. /** @private */
  3337. _sync: function(obj) {
  3338. var log = Ember.LOG_BINDINGS;
  3339. // don't synchronize destroyed objects or disconnected bindings
  3340. if (obj.isDestroyed || !this._readyToSync) { return; }
  3341. // get the direction of the binding for the object we are
  3342. // synchronizing from
  3343. var directionMap = this._directionMap;
  3344. var direction = directionMap.get(obj);
  3345. var fromPath = this._from, toPath = this._to;
  3346. directionMap.remove(obj);
  3347. // if we're synchronizing from the remote object...
  3348. if (direction === 'fwd') {
  3349. var fromValue = getWithGlobals(obj, this._from);
  3350. if (log) {
  3351. Ember.Logger.log(' ', this.toString(), '->', fromValue, obj);
  3352. }
  3353. if (this._oneWay) {
  3354. Ember.trySet(obj, toPath, fromValue);
  3355. } else {
  3356. Ember._suspendObserver(obj, toPath, this, this.toDidChange, function () {
  3357. Ember.trySet(obj, toPath, fromValue);
  3358. });
  3359. }
  3360. // if we're synchronizing *to* the remote object
  3361. } else if (direction === 'back') {
  3362. var toValue = get(obj, this._to);
  3363. if (log) {
  3364. Ember.Logger.log(' ', this.toString(), '<-', toValue, obj);
  3365. }
  3366. Ember._suspendObserver(obj, fromPath, this, this.fromDidChange, function () {
  3367. Ember.trySet(Ember.isGlobalPath(fromPath) ? window : obj, fromPath, toValue);
  3368. });
  3369. }
  3370. }
  3371. };
  3372. /** @private */
  3373. function mixinProperties(to, from) {
  3374. for (var key in from) {
  3375. if (from.hasOwnProperty(key)) {
  3376. to[key] = from[key];
  3377. }
  3378. }
  3379. }
  3380. mixinProperties(Binding,
  3381. /** @scope Ember.Binding */ {
  3382. /**
  3383. @see Ember.Binding.prototype.from
  3384. */
  3385. from: function() {
  3386. var C = this, binding = new C();
  3387. return binding.from.apply(binding, arguments);
  3388. },
  3389. /**
  3390. @see Ember.Binding.prototype.to
  3391. */
  3392. to: function() {
  3393. var C = this, binding = new C();
  3394. return binding.to.apply(binding, arguments);
  3395. },
  3396. /**
  3397. Creates a new Binding instance and makes it apply in a single direction.
  3398. A one-way binding will relay changes on the "from" side object (supplies
  3399. as the `from` argument) the "to" side, but not the other way around.
  3400. This means that if you change the "to" side directly, the "from" side may have
  3401. a different value.
  3402. @param {String} from from path.
  3403. @param {Boolean} [flag] (Optional) passing nothing here will make the binding oneWay. You can
  3404. instead pass false to disable oneWay, making the binding two way again.
  3405. @see Ember.Binding.prototype.oneWay
  3406. */
  3407. oneWay: function(from, flag) {
  3408. var C = this, binding = new C(null, from);
  3409. return binding.oneWay(flag);
  3410. }
  3411. });
  3412. /**
  3413. @class
  3414. An Ember.Binding connects the properties of two objects so that whenever the
  3415. value of one property changes, the other property will be changed also.
  3416. ## Automatic Creation of Bindings with `/^*Binding/`-named Properties
  3417. You do not usually create Binding objects directly but instead describe
  3418. bindings in your class or object definition using automatic binding detection.
  3419. Properties ending in a `Binding` suffix will be converted to Ember.Binding instances.
  3420. The value of this property should be a string representing a path to another object or
  3421. a custom binding instanced created using Binding helpers (see "Customizing Your Bindings"):
  3422. valueBinding: "MyApp.someController.title"
  3423. This will create a binding from `MyApp.someController.title` to the `value`
  3424. property of your object instance automatically. Now the two values will be
  3425. kept in sync.
  3426. ## One Way Bindings
  3427. One especially useful binding customization you can use is the `oneWay()`
  3428. helper. This helper tells Ember that you are only interested in
  3429. receiving changes on the object you are binding from. For example, if you
  3430. are binding to a preference and you want to be notified if the preference
  3431. has changed, but your object will not be changing the preference itself, you
  3432. could do:
  3433. bigTitlesBinding: Ember.Binding.oneWay("MyApp.preferencesController.bigTitles")
  3434. This way if the value of MyApp.preferencesController.bigTitles changes the
  3435. "bigTitles" property of your object will change also. However, if you
  3436. change the value of your "bigTitles" property, it will not update the
  3437. preferencesController.
  3438. One way bindings are almost twice as fast to setup and twice as fast to
  3439. execute because the binding only has to worry about changes to one side.
  3440. You should consider using one way bindings anytime you have an object that
  3441. may be created frequently and you do not intend to change a property; only
  3442. to monitor it for changes. (such as in the example above).
  3443. ## Adding Bindings Manually
  3444. All of the examples above show you how to configure a custom binding, but
  3445. the result of these customizations will be a binding template, not a fully
  3446. active Binding instance. The binding will actually become active only when you
  3447. instantiate the object the binding belongs to. It is useful however, to
  3448. understand what actually happens when the binding is activated.
  3449. For a binding to function it must have at least a "from" property and a "to"
  3450. property. The from property path points to the object/key that you want to
  3451. bind from while the to path points to the object/key you want to bind to.
  3452. When you define a custom binding, you are usually describing the property
  3453. you want to bind from (such as "MyApp.someController.value" in the examples
  3454. above). When your object is created, it will automatically assign the value
  3455. you want to bind "to" based on the name of your binding key. In the
  3456. examples above, during init, Ember objects will effectively call
  3457. something like this on your binding:
  3458. binding = Ember.Binding.from(this.valueBinding).to("value");
  3459. This creates a new binding instance based on the template you provide, and
  3460. sets the to path to the "value" property of the new object. Now that the
  3461. binding is fully configured with a "from" and a "to", it simply needs to be
  3462. connected to become active. This is done through the connect() method:
  3463. binding.connect(this);
  3464. Note that when you connect a binding you pass the object you want it to be
  3465. connected to. This object will be used as the root for both the from and
  3466. to side of the binding when inspecting relative paths. This allows the
  3467. binding to be automatically inherited by subclassed objects as well.
  3468. Now that the binding is connected, it will observe both the from and to side
  3469. and relay changes.
  3470. If you ever needed to do so (you almost never will, but it is useful to
  3471. understand this anyway), you could manually create an active binding by
  3472. using the Ember.bind() helper method. (This is the same method used by
  3473. to setup your bindings on objects):
  3474. Ember.bind(MyApp.anotherObject, "value", "MyApp.someController.value");
  3475. Both of these code fragments have the same effect as doing the most friendly
  3476. form of binding creation like so:
  3477. MyApp.anotherObject = Ember.Object.create({
  3478. valueBinding: "MyApp.someController.value",
  3479. // OTHER CODE FOR THIS OBJECT...
  3480. });
  3481. Ember's built in binding creation method makes it easy to automatically
  3482. create bindings for you. You should always use the highest-level APIs
  3483. available, even if you understand how it works underneath.
  3484. @since Ember 0.9
  3485. */
  3486. Ember.Binding = Binding;
  3487. /**
  3488. Global helper method to create a new binding. Just pass the root object
  3489. along with a to and from path to create and connect the binding.
  3490. @param {Object} obj
  3491. The root object of the transform.
  3492. @param {String} to
  3493. The path to the 'to' side of the binding. Must be relative to obj.
  3494. @param {String} from
  3495. The path to the 'from' side of the binding. Must be relative to obj or
  3496. a global path.
  3497. @returns {Ember.Binding} binding instance
  3498. */
  3499. Ember.bind = function(obj, to, from) {
  3500. return new Ember.Binding(to, from).connect(obj);
  3501. };
  3502. Ember.oneWay = function(obj, to, from) {
  3503. return new Ember.Binding(to, from).oneWay().connect(obj);
  3504. };
  3505. })();
  3506. (function() {
  3507. // ==========================================================================
  3508. // Project: Ember Runtime
  3509. // Copyright: ©2011 Strobe Inc. and contributors.
  3510. // License: Licensed under MIT license (see license.js)
  3511. // ==========================================================================
  3512. var Mixin, REQUIRED, Alias,
  3513. classToString, superClassString,
  3514. a_map = Ember.ArrayPolyfills.map,
  3515. a_indexOf = Ember.ArrayPolyfills.indexOf,
  3516. a_forEach = Ember.ArrayPolyfills.forEach,
  3517. a_slice = [].slice,
  3518. EMPTY_META = {}, // dummy for non-writable meta
  3519. META_SKIP = { __emberproto__: true, __ember_count__: true },
  3520. o_create = Ember.create,
  3521. defineProperty = Ember.defineProperty,
  3522. guidFor = Ember.guidFor;
  3523. /** @private */
  3524. function mixinsMeta(obj) {
  3525. var m = Ember.meta(obj, true), ret = m.mixins;
  3526. if (!ret) {
  3527. ret = m.mixins = { __emberproto__: obj };
  3528. } else if (ret.__emberproto__ !== obj) {
  3529. ret = m.mixins = o_create(ret);
  3530. ret.__emberproto__ = obj;
  3531. }
  3532. return ret;
  3533. }
  3534. /** @private */
  3535. function initMixin(mixin, args) {
  3536. if (args && args.length > 0) {
  3537. mixin.mixins = a_map.call(args, function(x) {
  3538. if (x instanceof Mixin) { return x; }
  3539. // Note: Manually setup a primitive mixin here. This is the only
  3540. // way to actually get a primitive mixin. This way normal creation
  3541. // of mixins will give you combined mixins...
  3542. var mixin = new Mixin();
  3543. mixin.properties = x;
  3544. return mixin;
  3545. });
  3546. }
  3547. return mixin;
  3548. }
  3549. /** @private */
  3550. function isMethod(obj) {
  3551. return 'function' === typeof obj &&
  3552. obj.isMethod !== false &&
  3553. obj !== Boolean && obj !== Object && obj !== Number && obj !== Array && obj !== Date && obj !== String;
  3554. }
  3555. /** @private */
  3556. function mergeMixins(mixins, m, descs, values, base) {
  3557. var len = mixins.length, idx, mixin, guid, props, value, key, ovalue, concats;
  3558. /** @private */
  3559. function removeKeys(keyName) {
  3560. delete descs[keyName];
  3561. delete values[keyName];
  3562. }
  3563. for(idx=0; idx < len; idx++) {
  3564. mixin = mixins[idx];
  3565. Ember.assert('Expected hash or Mixin instance, got ' + Object.prototype.toString.call(mixin), typeof mixin === 'object' && mixin !== null && Object.prototype.toString.call(mixin) !== '[object Array]');
  3566. if (mixin instanceof Mixin) {
  3567. guid = guidFor(mixin);
  3568. if (m[guid]) { continue; }
  3569. m[guid] = mixin;
  3570. props = mixin.properties;
  3571. } else {
  3572. props = mixin; // apply anonymous mixin properties
  3573. }
  3574. if (props) {
  3575. // reset before adding each new mixin to pickup concats from previous
  3576. concats = values.concatenatedProperties || base.concatenatedProperties;
  3577. if (props.concatenatedProperties) {
  3578. concats = concats ? concats.concat(props.concatenatedProperties) : props.concatenatedProperties;
  3579. }
  3580. for (key in props) {
  3581. if (!props.hasOwnProperty(key)) { continue; }
  3582. value = props[key];
  3583. if (value instanceof Ember.Descriptor) {
  3584. if (value === REQUIRED && descs[key]) { continue; }
  3585. descs[key] = value;
  3586. values[key] = undefined;
  3587. } else {
  3588. // impl super if needed...
  3589. if (isMethod(value)) {
  3590. ovalue = descs[key] === undefined && values[key];
  3591. if (!ovalue) { ovalue = base[key]; }
  3592. if ('function' !== typeof ovalue) { ovalue = null; }
  3593. if (ovalue) {
  3594. var o = value.__ember_observes__, ob = value.__ember_observesBefore__;
  3595. value = Ember.wrap(value, ovalue);
  3596. value.__ember_observes__ = o;
  3597. value.__ember_observesBefore__ = ob;
  3598. }
  3599. } else if ((concats && a_indexOf.call(concats, key) >= 0) || key === 'concatenatedProperties') {
  3600. var baseValue = values[key] || base[key];
  3601. value = baseValue ? baseValue.concat(value) : Ember.makeArray(value);
  3602. }
  3603. descs[key] = undefined;
  3604. values[key] = value;
  3605. }
  3606. }
  3607. // manually copy toString() because some JS engines do not enumerate it
  3608. if (props.hasOwnProperty('toString')) {
  3609. base.toString = props.toString;
  3610. }
  3611. } else if (mixin.mixins) {
  3612. mergeMixins(mixin.mixins, m, descs, values, base);
  3613. if (mixin._without) { a_forEach.call(mixin._without, removeKeys); }
  3614. }
  3615. }
  3616. }
  3617. /** @private */
  3618. function writableReq(obj) {
  3619. var m = Ember.meta(obj), req = m.required;
  3620. if (!req || req.__emberproto__ !== obj) {
  3621. req = m.required = req ? o_create(req) : { __ember_count__: 0 };
  3622. req.__emberproto__ = obj;
  3623. }
  3624. return req;
  3625. }
  3626. var IS_BINDING = Ember.IS_BINDING = /^.+Binding$/;
  3627. /** @private */
  3628. function detectBinding(obj, key, value, m) {
  3629. if (IS_BINDING.test(key)) {
  3630. var bindings = m.bindings;
  3631. if (!bindings) {
  3632. bindings = m.bindings = { __emberproto__: obj };
  3633. } else if (bindings.__emberproto__ !== obj) {
  3634. bindings = m.bindings = o_create(m.bindings);
  3635. bindings.__emberproto__ = obj;
  3636. }
  3637. bindings[key] = value;
  3638. }
  3639. }
  3640. /** @private */
  3641. function connectBindings(obj, m) {
  3642. // TODO Mixin.apply(instance) should disconnect binding if exists
  3643. var bindings = m.bindings, key, binding, to;
  3644. if (bindings) {
  3645. for (key in bindings) {
  3646. binding = key !== '__emberproto__' && bindings[key];
  3647. if (binding) {
  3648. to = key.slice(0, -7); // strip Binding off end
  3649. if (binding instanceof Ember.Binding) {
  3650. binding = binding.copy(); // copy prototypes' instance
  3651. binding.to(to);
  3652. } else { // binding is string path
  3653. binding = new Ember.Binding(to, binding);
  3654. }
  3655. binding.connect(obj);
  3656. obj[key] = binding;
  3657. }
  3658. }
  3659. // mark as applied
  3660. m.bindings = { __emberproto__: obj };
  3661. }
  3662. }
  3663. function finishPartial(obj, m) {
  3664. connectBindings(obj, m || Ember.meta(obj));
  3665. return obj;
  3666. }
  3667. /** @private */
  3668. function applyMixin(obj, mixins, partial) {
  3669. var descs = {}, values = {}, m = Ember.meta(obj), req = m.required,
  3670. key, value, desc, prevValue, paths, len, idx;
  3671. // Go through all mixins and hashes passed in, and:
  3672. //
  3673. // * Handle concatenated properties
  3674. // * Set up _super wrapping if necessary
  3675. // * Set up computed property descriptors
  3676. // * Copying `toString` in broken browsers
  3677. mergeMixins(mixins, mixinsMeta(obj), descs, values, obj);
  3678. for(key in values) {
  3679. if (key === 'contructor') { continue; }
  3680. if (!values.hasOwnProperty(key)) { continue; }
  3681. desc = descs[key];
  3682. value = values[key];
  3683. if (desc === REQUIRED) {
  3684. if (!(key in obj)) {
  3685. Ember.assert('Required property not defined: '+key, !!partial);
  3686. // for partial applies add to hash of required keys
  3687. req = writableReq(obj);
  3688. req.__ember_count__++;
  3689. req[key] = true;
  3690. }
  3691. } else {
  3692. while (desc && desc instanceof Alias) {
  3693. var altKey = desc.methodName;
  3694. if (descs[altKey] || values[altKey]) {
  3695. value = values[altKey];
  3696. desc = descs[altKey];
  3697. } else if (m.descs[altKey]) {
  3698. desc = m.descs[altKey];
  3699. value = undefined;
  3700. } else {
  3701. desc = undefined;
  3702. value = obj[altKey];
  3703. }
  3704. }
  3705. if (desc === undefined && value === undefined) { continue; }
  3706. prevValue = obj[key];
  3707. if ('function' === typeof prevValue) {
  3708. if ((paths = prevValue.__ember_observesBefore__)) {
  3709. len = paths.length;
  3710. for (idx=0; idx < len; idx++) {
  3711. Ember.removeBeforeObserver(obj, paths[idx], null, key);
  3712. }
  3713. } else if ((paths = prevValue.__ember_observes__)) {
  3714. len = paths.length;
  3715. for (idx=0; idx < len; idx++) {
  3716. Ember.removeObserver(obj, paths[idx], null, key);
  3717. }
  3718. }
  3719. }
  3720. detectBinding(obj, key, value, m);
  3721. defineProperty(obj, key, desc, value, m);
  3722. if ('function' === typeof value) {
  3723. if (paths = value.__ember_observesBefore__) {
  3724. len = paths.length;
  3725. for (idx=0; idx < len; idx++) {
  3726. Ember.addBeforeObserver(obj, paths[idx], null, key);
  3727. }
  3728. } else if (paths = value.__ember_observes__) {
  3729. len = paths.length;
  3730. for (idx=0; idx < len; idx++) {
  3731. Ember.addObserver(obj, paths[idx], null, key);
  3732. }
  3733. }
  3734. }
  3735. if (req && req[key]) {
  3736. req = writableReq(obj);
  3737. req.__ember_count__--;
  3738. req[key] = false;
  3739. }
  3740. }
  3741. }
  3742. if (!partial) { // don't apply to prototype
  3743. finishPartial(obj, m);
  3744. }
  3745. // Make sure no required attrs remain
  3746. if (!partial && req && req.__ember_count__>0) {
  3747. var keys = [];
  3748. for (key in req) {
  3749. if (META_SKIP[key]) { continue; }
  3750. keys.push(key);
  3751. }
  3752. // TODO: Remove surrounding if clause from production build
  3753. Ember.assert('Required properties not defined: '+keys.join(','));
  3754. }
  3755. return obj;
  3756. }
  3757. Ember.mixin = function(obj) {
  3758. var args = a_slice.call(arguments, 1);
  3759. applyMixin(obj, args, false);
  3760. return obj;
  3761. };
  3762. /**
  3763. @class
  3764. The `Ember.Mixin` class allows you to create mixins, whose properties can be
  3765. added to other classes. For instance,
  3766. App.Editable = Ember.Mixin.create({
  3767. edit: function() {
  3768. console.log('starting to edit');
  3769. this.set('isEditing', true);
  3770. },
  3771. isEditing: false
  3772. });
  3773. // Mix mixins into classes by passing them as the first arguments to
  3774. // .extend or .create.
  3775. App.CommentView = Ember.View.extend(App.Editable, {
  3776. template: Ember.Handlebars.compile('{{#if isEditing}}...{{else}}...{{/if}}')
  3777. });
  3778. commentView = App.CommentView.create();
  3779. commentView.edit(); // => outputs 'starting to edit'
  3780. Note that Mixins are created with `Ember.Mixin.create`, not
  3781. `Ember.Mixin.extend`.
  3782. */
  3783. Ember.Mixin = function() { return initMixin(this, arguments); };
  3784. /** @private */
  3785. Mixin = Ember.Mixin;
  3786. /** @private */
  3787. Mixin._apply = applyMixin;
  3788. Mixin.applyPartial = function(obj) {
  3789. var args = a_slice.call(arguments, 1);
  3790. return applyMixin(obj, args, true);
  3791. };
  3792. Mixin.finishPartial = finishPartial;
  3793. Mixin.create = function() {
  3794. classToString.processed = false;
  3795. var M = this;
  3796. return initMixin(new M(), arguments);
  3797. };
  3798. var MixinPrototype = Mixin.prototype;
  3799. MixinPrototype.reopen = function() {
  3800. var mixin, tmp;
  3801. if (this.properties) {
  3802. mixin = Mixin.create();
  3803. mixin.properties = this.properties;
  3804. delete this.properties;
  3805. this.mixins = [mixin];
  3806. } else if (!this.mixins) {
  3807. this.mixins = [];
  3808. }
  3809. var len = arguments.length, mixins = this.mixins, idx;
  3810. for(idx=0; idx < len; idx++) {
  3811. mixin = arguments[idx];
  3812. Ember.assert('Expected hash or Mixin instance, got ' + Object.prototype.toString.call(mixin), typeof mixin === 'object' && mixin !== null && Object.prototype.toString.call(mixin) !== '[object Array]');
  3813. if (mixin instanceof Mixin) {
  3814. mixins.push(mixin);
  3815. } else {
  3816. tmp = Mixin.create();
  3817. tmp.properties = mixin;
  3818. mixins.push(tmp);
  3819. }
  3820. }
  3821. return this;
  3822. };
  3823. MixinPrototype.apply = function(obj) {
  3824. return applyMixin(obj, [this], false);
  3825. };
  3826. MixinPrototype.applyPartial = function(obj) {
  3827. return applyMixin(obj, [this], true);
  3828. };
  3829. /** @private */
  3830. function _detect(curMixin, targetMixin, seen) {
  3831. var guid = guidFor(curMixin);
  3832. if (seen[guid]) { return false; }
  3833. seen[guid] = true;
  3834. if (curMixin === targetMixin) { return true; }
  3835. var mixins = curMixin.mixins, loc = mixins ? mixins.length : 0;
  3836. while (--loc >= 0) {
  3837. if (_detect(mixins[loc], targetMixin, seen)) { return true; }
  3838. }
  3839. return false;
  3840. }
  3841. MixinPrototype.detect = function(obj) {
  3842. if (!obj) { return false; }
  3843. if (obj instanceof Mixin) { return _detect(obj, this, {}); }
  3844. var mixins = Ember.meta(obj, false).mixins;
  3845. if (mixins) {
  3846. return !!mixins[guidFor(this)];
  3847. }
  3848. return false;
  3849. };
  3850. MixinPrototype.without = function() {
  3851. var ret = new Mixin(this);
  3852. ret._without = a_slice.call(arguments);
  3853. return ret;
  3854. };
  3855. /** @private */
  3856. function _keys(ret, mixin, seen) {
  3857. if (seen[guidFor(mixin)]) { return; }
  3858. seen[guidFor(mixin)] = true;
  3859. if (mixin.properties) {
  3860. var props = mixin.properties;
  3861. for (var key in props) {
  3862. if (props.hasOwnProperty(key)) { ret[key] = true; }
  3863. }
  3864. } else if (mixin.mixins) {
  3865. a_forEach.call(mixin.mixins, function(x) { _keys(ret, x, seen); });
  3866. }
  3867. }
  3868. MixinPrototype.keys = function() {
  3869. var keys = {}, seen = {}, ret = [];
  3870. _keys(keys, this, seen);
  3871. for(var key in keys) {
  3872. if (keys.hasOwnProperty(key)) { ret.push(key); }
  3873. }
  3874. return ret;
  3875. };
  3876. /** @private - make Mixin's have nice displayNames */
  3877. var NAME_KEY = Ember.GUID_KEY+'_name';
  3878. var get = Ember.get;
  3879. /** @private */
  3880. function processNames(paths, root, seen) {
  3881. var idx = paths.length;
  3882. for(var key in root) {
  3883. if (!root.hasOwnProperty || !root.hasOwnProperty(key)) { continue; }
  3884. var obj = root[key];
  3885. paths[idx] = key;
  3886. if (obj && obj.toString === classToString) {
  3887. obj[NAME_KEY] = paths.join('.');
  3888. } else if (obj && get(obj, 'isNamespace')) {
  3889. if (seen[guidFor(obj)]) { continue; }
  3890. seen[guidFor(obj)] = true;
  3891. processNames(paths, obj, seen);
  3892. }
  3893. }
  3894. paths.length = idx; // cut out last item
  3895. }
  3896. /** @private */
  3897. function findNamespaces() {
  3898. var Namespace = Ember.Namespace, obj, isNamespace;
  3899. if (Namespace.PROCESSED) { return; }
  3900. for (var prop in window) {
  3901. // get(window.globalStorage, 'isNamespace') would try to read the storage for domain isNamespace and cause exception in Firefox.
  3902. // globalStorage is a storage obsoleted by the WhatWG storage specification. See https://developer.mozilla.org/en/DOM/Storage#globalStorage
  3903. if (prop === "globalStorage" && window.StorageList && window.globalStorage instanceof window.StorageList) { continue; }
  3904. // Unfortunately, some versions of IE don't support window.hasOwnProperty
  3905. if (window.hasOwnProperty && !window.hasOwnProperty(prop)) { continue; }
  3906. // At times we are not allowed to access certain properties for security reasons.
  3907. // There are also times where even if we can access them, we are not allowed to access their properties.
  3908. try {
  3909. obj = window[prop];
  3910. isNamespace = obj && get(obj, 'isNamespace');
  3911. } catch (e) {
  3912. continue;
  3913. }
  3914. if (isNamespace) {
  3915. Ember.deprecate("Namespaces should not begin with lowercase.", /^[A-Z]/.test(prop));
  3916. obj[NAME_KEY] = prop;
  3917. }
  3918. }
  3919. }
  3920. Ember.identifyNamespaces = findNamespaces;
  3921. /** @private */
  3922. superClassString = function(mixin) {
  3923. var superclass = mixin.superclass;
  3924. if (superclass) {
  3925. if (superclass[NAME_KEY]) { return superclass[NAME_KEY]; }
  3926. else { return superClassString(superclass); }
  3927. } else {
  3928. return;
  3929. }
  3930. };
  3931. /** @private */
  3932. classToString = function() {
  3933. var Namespace = Ember.Namespace, namespace;
  3934. // TODO: Namespace should really be in Metal
  3935. if (Namespace) {
  3936. if (!this[NAME_KEY] && !classToString.processed) {
  3937. if (!Namespace.PROCESSED) {
  3938. findNamespaces();
  3939. Namespace.PROCESSED = true;
  3940. }
  3941. classToString.processed = true;
  3942. var namespaces = Namespace.NAMESPACES;
  3943. for (var i=0, l=namespaces.length; i<l; i++) {
  3944. namespace = namespaces[i];
  3945. processNames([namespace.toString()], namespace, {});
  3946. }
  3947. }
  3948. }
  3949. if (this[NAME_KEY]) {
  3950. return this[NAME_KEY];
  3951. } else {
  3952. var str = superClassString(this);
  3953. if (str) {
  3954. return "(subclass of " + str + ")";
  3955. } else {
  3956. return "(unknown mixin)";
  3957. }
  3958. }
  3959. };
  3960. MixinPrototype.toString = classToString;
  3961. // returns the mixins currently applied to the specified object
  3962. // TODO: Make Ember.mixin
  3963. Mixin.mixins = function(obj) {
  3964. var ret = [], mixins = Ember.meta(obj, false).mixins, key, mixin;
  3965. if (mixins) {
  3966. for(key in mixins) {
  3967. if (META_SKIP[key]) { continue; }
  3968. mixin = mixins[key];
  3969. // skip primitive mixins since these are always anonymous
  3970. if (!mixin.properties) { ret.push(mixins[key]); }
  3971. }
  3972. }
  3973. return ret;
  3974. };
  3975. REQUIRED = new Ember.Descriptor();
  3976. REQUIRED.toString = function() { return '(Required Property)'; };
  3977. Ember.required = function() {
  3978. return REQUIRED;
  3979. };
  3980. /** @private */
  3981. Alias = function(methodName) {
  3982. this.methodName = methodName;
  3983. };
  3984. Alias.prototype = new Ember.Descriptor();
  3985. Ember.alias = function(methodName) {
  3986. return new Alias(methodName);
  3987. };
  3988. // ..........................................................
  3989. // OBSERVER HELPER
  3990. //
  3991. Ember.observer = function(func) {
  3992. var paths = a_slice.call(arguments, 1);
  3993. func.__ember_observes__ = paths;
  3994. return func;
  3995. };
  3996. // If observers ever become asynchronous, Ember.immediateObserver
  3997. // must remain synchronous.
  3998. Ember.immediateObserver = function() {
  3999. for (var i=0, l=arguments.length; i<l; i++) {
  4000. var arg = arguments[i];
  4001. Ember.assert("Immediate observers must observe internal properties only, not properties on other objects.", typeof arg !== "string" || arg.indexOf('.') === -1);
  4002. }
  4003. return Ember.observer.apply(this, arguments);
  4004. };
  4005. Ember.beforeObserver = function(func) {
  4006. var paths = a_slice.call(arguments, 1);
  4007. func.__ember_observesBefore__ = paths;
  4008. return func;
  4009. };
  4010. })();
  4011. (function() {
  4012. // ==========================================================================
  4013. // Project: Ember Metal
  4014. // Copyright: ©2011 Strobe Inc. and contributors.
  4015. // License: Licensed under MIT license (see license.js)
  4016. // ==========================================================================
  4017. })();
  4018. (function() {
  4019. /**
  4020. * @license
  4021. * ==========================================================================
  4022. * Ember
  4023. * Copyright ©2006-2011, Strobe Inc. and contributors.
  4024. * Portions copyright ©2008-2011 Apple Inc. All rights reserved.
  4025. *
  4026. * Permission is hereby granted, free of charge, to any person obtaining a
  4027. * copy of this software and associated documentation files (the "Software"),
  4028. * to deal in the Software without restriction, including without limitation
  4029. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  4030. * and/or sell copies of the Software, and to permit persons to whom the
  4031. * Software is furnished to do so, subject to the following conditions:
  4032. *
  4033. * The above copyright notice and this permission notice shall be included in
  4034. * all copies or substantial portions of the Software.
  4035. *
  4036. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4037. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4038. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4039. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4040. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  4041. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  4042. * DEALINGS IN THE SOFTWARE.
  4043. *
  4044. * For more information about Ember, visit http://www.emberjs.com
  4045. *
  4046. * ==========================================================================
  4047. */
  4048. })();
  4049. (function() {
  4050. // ==========================================================================
  4051. // Project: Ember Runtime
  4052. // Copyright: ©2011 Strobe Inc. and contributors.
  4053. // License: Licensed under MIT license (see license.js)
  4054. // ==========================================================================
  4055. /*globals ENV */
  4056. var indexOf = Ember.EnumerableUtils.indexOf;
  4057. // ........................................
  4058. // TYPING & ARRAY MESSAGING
  4059. //
  4060. var TYPE_MAP = {};
  4061. var t = "Boolean Number String Function Array Date RegExp Object".split(" ");
  4062. Ember.ArrayPolyfills.forEach.call(t, function(name) {
  4063. TYPE_MAP[ "[object " + name + "]" ] = name.toLowerCase();
  4064. });
  4065. var toString = Object.prototype.toString;
  4066. /**
  4067. Returns a consistent type for the passed item.
  4068. Use this instead of the built-in Ember.typeOf() to get the type of an item.
  4069. It will return the same result across all browsers and includes a bit
  4070. more detail. Here is what will be returned:
  4071. | Return Value | Meaning |
  4072. |---------------|------------------------------------------------------|
  4073. | 'string' | String primitive |
  4074. | 'number' | Number primitive |
  4075. | 'boolean' | Boolean primitive |
  4076. | 'null' | Null value |
  4077. | 'undefined' | Undefined value |
  4078. | 'function' | A function |
  4079. | 'array' | An instance of Array |
  4080. | 'class' | A Ember class (created using Ember.Object.extend()) |
  4081. | 'instance' | A Ember object instance |
  4082. | 'error' | An instance of the Error object |
  4083. | 'object' | A JavaScript object not inheriting from Ember.Object |
  4084. Examples:
  4085. Ember.typeOf(); => 'undefined'
  4086. Ember.typeOf(null); => 'null'
  4087. Ember.typeOf(undefined); => 'undefined'
  4088. Ember.typeOf('michael'); => 'string'
  4089. Ember.typeOf(101); => 'number'
  4090. Ember.typeOf(true); => 'boolean'
  4091. Ember.typeOf(Ember.makeArray); => 'function'
  4092. Ember.typeOf([1,2,90]); => 'array'
  4093. Ember.typeOf(Ember.Object.extend()); => 'class'
  4094. Ember.typeOf(Ember.Object.create()); => 'instance'
  4095. Ember.typeOf(new Error('teamocil')); => 'error'
  4096. // "normal" JavaScript object
  4097. Ember.typeOf({a: 'b'}); => 'object'
  4098. @param item {Object} the item to check
  4099. @returns {String} the type
  4100. */
  4101. Ember.typeOf = function(item) {
  4102. var ret;
  4103. ret = (item === null || item === undefined) ? String(item) : TYPE_MAP[toString.call(item)] || 'object';
  4104. if (ret === 'function') {
  4105. if (Ember.Object && Ember.Object.detect(item)) ret = 'class';
  4106. } else if (ret === 'object') {
  4107. if (item instanceof Error) ret = 'error';
  4108. else if (Ember.Object && item instanceof Ember.Object) ret = 'instance';
  4109. else ret = 'object';
  4110. }
  4111. return ret;
  4112. };
  4113. /**
  4114. Returns true if the passed value is null or undefined. This avoids errors
  4115. from JSLint complaining about use of ==, which can be technically
  4116. confusing.
  4117. Ember.none(); => true
  4118. Ember.none(null); => true
  4119. Ember.none(undefined); => true
  4120. Ember.none(''); => false
  4121. Ember.none([]); => false
  4122. Ember.none(function(){}); => false
  4123. @param {Object} obj Value to test
  4124. @returns {Boolean}
  4125. */
  4126. Ember.none = function(obj) {
  4127. return obj === null || obj === undefined;
  4128. };
  4129. /**
  4130. Verifies that a value is null or an empty string | array | function.
  4131. Constrains the rules on `Ember.none` by returning false for empty
  4132. string and empty arrays.
  4133. Ember.empty(); => true
  4134. Ember.empty(null); => true
  4135. Ember.empty(undefined); => true
  4136. Ember.empty(''); => true
  4137. Ember.empty([]); => true
  4138. Ember.empty('tobias fünke'); => false
  4139. Ember.empty([0,1,2]); => false
  4140. @param {Object} obj Value to test
  4141. @returns {Boolean}
  4142. */
  4143. Ember.empty = function(obj) {
  4144. return obj === null || obj === undefined || (obj.length === 0 && typeof obj !== 'function');
  4145. };
  4146. /**
  4147. This will compare two javascript values of possibly different types.
  4148. It will tell you which one is greater than the other by returning:
  4149. - -1 if the first is smaller than the second,
  4150. - 0 if both are equal,
  4151. - 1 if the first is greater than the second.
  4152. The order is calculated based on Ember.ORDER_DEFINITION, if types are different.
  4153. In case they have the same type an appropriate comparison for this type is made.
  4154. Ember.compare('hello', 'hello'); => 0
  4155. Ember.compare('abc', 'dfg'); => -1
  4156. Ember.compare(2, 1); => 1
  4157. @param {Object} v First value to compare
  4158. @param {Object} w Second value to compare
  4159. @returns {Number} -1 if v < w, 0 if v = w and 1 if v > w.
  4160. */
  4161. Ember.compare = function compare(v, w) {
  4162. if (v === w) { return 0; }
  4163. var type1 = Ember.typeOf(v);
  4164. var type2 = Ember.typeOf(w);
  4165. var Comparable = Ember.Comparable;
  4166. if (Comparable) {
  4167. if (type1==='instance' && Comparable.detect(v.constructor)) {
  4168. return v.constructor.compare(v, w);
  4169. }
  4170. if (type2 === 'instance' && Comparable.detect(w.constructor)) {
  4171. return 1-w.constructor.compare(w, v);
  4172. }
  4173. }
  4174. // If we haven't yet generated a reverse-mapping of Ember.ORDER_DEFINITION,
  4175. // do so now.
  4176. var mapping = Ember.ORDER_DEFINITION_MAPPING;
  4177. if (!mapping) {
  4178. var order = Ember.ORDER_DEFINITION;
  4179. mapping = Ember.ORDER_DEFINITION_MAPPING = {};
  4180. var idx, len;
  4181. for (idx = 0, len = order.length; idx < len; ++idx) {
  4182. mapping[order[idx]] = idx;
  4183. }
  4184. // We no longer need Ember.ORDER_DEFINITION.
  4185. delete Ember.ORDER_DEFINITION;
  4186. }
  4187. var type1Index = mapping[type1];
  4188. var type2Index = mapping[type2];
  4189. if (type1Index < type2Index) { return -1; }
  4190. if (type1Index > type2Index) { return 1; }
  4191. // types are equal - so we have to check values now
  4192. switch (type1) {
  4193. case 'boolean':
  4194. case 'number':
  4195. if (v < w) { return -1; }
  4196. if (v > w) { return 1; }
  4197. return 0;
  4198. case 'string':
  4199. var comp = v.localeCompare(w);
  4200. if (comp < 0) { return -1; }
  4201. if (comp > 0) { return 1; }
  4202. return 0;
  4203. case 'array':
  4204. var vLen = v.length;
  4205. var wLen = w.length;
  4206. var l = Math.min(vLen, wLen);
  4207. var r = 0;
  4208. var i = 0;
  4209. while (r === 0 && i < l) {
  4210. r = compare(v[i],w[i]);
  4211. i++;
  4212. }
  4213. if (r !== 0) { return r; }
  4214. // all elements are equal now
  4215. // shorter array should be ordered first
  4216. if (vLen < wLen) { return -1; }
  4217. if (vLen > wLen) { return 1; }
  4218. // arrays are equal now
  4219. return 0;
  4220. case 'instance':
  4221. if (Ember.Comparable && Ember.Comparable.detect(v)) {
  4222. return v.compare(v, w);
  4223. }
  4224. return 0;
  4225. case 'date':
  4226. var vNum = v.getTime();
  4227. var wNum = w.getTime();
  4228. if (vNum < wNum) { return -1; }
  4229. if (vNum > wNum) { return 1; }
  4230. return 0;
  4231. default:
  4232. return 0;
  4233. }
  4234. };
  4235. /** @private */
  4236. function _copy(obj, deep, seen, copies) {
  4237. var ret, loc, key;
  4238. // primitive data types are immutable, just return them.
  4239. if ('object' !== typeof obj || obj===null) return obj;
  4240. // avoid cyclical loops
  4241. if (deep && (loc=indexOf(seen, obj))>=0) return copies[loc];
  4242. Ember.assert('Cannot clone an Ember.Object that does not implement Ember.Copyable', !(obj instanceof Ember.Object) || (Ember.Copyable && Ember.Copyable.detect(obj)));
  4243. // IMPORTANT: this specific test will detect a native array only. Any other
  4244. // object will need to implement Copyable.
  4245. if (Ember.typeOf(obj) === 'array') {
  4246. ret = obj.slice();
  4247. if (deep) {
  4248. loc = ret.length;
  4249. while(--loc>=0) ret[loc] = _copy(ret[loc], deep, seen, copies);
  4250. }
  4251. } else if (Ember.Copyable && Ember.Copyable.detect(obj)) {
  4252. ret = obj.copy(deep, seen, copies);
  4253. } else {
  4254. ret = {};
  4255. for(key in obj) {
  4256. if (!obj.hasOwnProperty(key)) continue;
  4257. ret[key] = deep ? _copy(obj[key], deep, seen, copies) : obj[key];
  4258. }
  4259. }
  4260. if (deep) {
  4261. seen.push(obj);
  4262. copies.push(ret);
  4263. }
  4264. return ret;
  4265. }
  4266. /**
  4267. Creates a clone of the passed object. This function can take just about
  4268. any type of object and create a clone of it, including primitive values
  4269. (which are not actually cloned because they are immutable).
  4270. If the passed object implements the clone() method, then this function
  4271. will simply call that method and return the result.
  4272. @param {Object} object The object to clone
  4273. @param {Boolean} deep If true, a deep copy of the object is made
  4274. @returns {Object} The cloned object
  4275. */
  4276. Ember.copy = function(obj, deep) {
  4277. // fast paths
  4278. if ('object' !== typeof obj || obj===null) return obj; // can't copy primitives
  4279. if (Ember.Copyable && Ember.Copyable.detect(obj)) return obj.copy(deep);
  4280. return _copy(obj, deep, deep ? [] : null, deep ? [] : null);
  4281. };
  4282. /**
  4283. Convenience method to inspect an object. This method will attempt to
  4284. convert the object into a useful string description.
  4285. @param {Object} obj The object you want to inspect.
  4286. @returns {String} A description of the object
  4287. */
  4288. Ember.inspect = function(obj) {
  4289. var v, ret = [];
  4290. for(var key in obj) {
  4291. if (obj.hasOwnProperty(key)) {
  4292. v = obj[key];
  4293. if (v === 'toString') { continue; } // ignore useless items
  4294. if (Ember.typeOf(v) === 'function') { v = "function() { ... }"; }
  4295. ret.push(key + ": " + v);
  4296. }
  4297. }
  4298. return "{" + ret.join(" , ") + "}";
  4299. };
  4300. /**
  4301. Compares two objects, returning true if they are logically equal. This is
  4302. a deeper comparison than a simple triple equal. For sets it will compare the
  4303. internal objects. For any other object that implements `isEqual()` it will
  4304. respect that method.
  4305. Ember.isEqual('hello', 'hello'); => true
  4306. Ember.isEqual(1, 2); => false
  4307. Ember.isEqual([4,2], [4,2]); => false
  4308. @param {Object} a first object to compare
  4309. @param {Object} b second object to compare
  4310. @returns {Boolean}
  4311. */
  4312. Ember.isEqual = function(a, b) {
  4313. if (a && 'function'===typeof a.isEqual) return a.isEqual(b);
  4314. return a === b;
  4315. };
  4316. /**
  4317. @private
  4318. Used by Ember.compare
  4319. */
  4320. Ember.ORDER_DEFINITION = Ember.ENV.ORDER_DEFINITION || [
  4321. 'undefined',
  4322. 'null',
  4323. 'boolean',
  4324. 'number',
  4325. 'string',
  4326. 'array',
  4327. 'object',
  4328. 'instance',
  4329. 'function',
  4330. 'class',
  4331. 'date'
  4332. ];
  4333. /**
  4334. Returns all of the keys defined on an object or hash. This is useful
  4335. when inspecting objects for debugging. On browsers that support it, this
  4336. uses the native Object.keys implementation.
  4337. @function
  4338. @param {Object} obj
  4339. @returns {Array} Array containing keys of obj
  4340. */
  4341. Ember.keys = Object.keys;
  4342. if (!Ember.keys) {
  4343. Ember.keys = function(obj) {
  4344. var ret = [];
  4345. for(var key in obj) {
  4346. if (obj.hasOwnProperty(key)) { ret.push(key); }
  4347. }
  4348. return ret;
  4349. };
  4350. }
  4351. // ..........................................................
  4352. // ERROR
  4353. //
  4354. /**
  4355. @class
  4356. A subclass of the JavaScript Error object for use in Ember.
  4357. */
  4358. Ember.Error = function() {
  4359. var tmp = Error.prototype.constructor.apply(this, arguments);
  4360. for (var p in tmp) {
  4361. if (tmp.hasOwnProperty(p)) { this[p] = tmp[p]; }
  4362. }
  4363. this.message = tmp.message;
  4364. };
  4365. Ember.Error.prototype = Ember.create(Error.prototype);
  4366. })();
  4367. (function() {
  4368. // ==========================================================================
  4369. // Project: Ember Runtime
  4370. // Copyright: ©2011 Strobe Inc.
  4371. // License: Licensed under MIT license (see license.js)
  4372. // ==========================================================================
  4373. /** @private **/
  4374. var STRING_DASHERIZE_REGEXP = (/[ _]/g);
  4375. var STRING_DASHERIZE_CACHE = {};
  4376. var STRING_DECAMELIZE_REGEXP = (/([a-z])([A-Z])/g);
  4377. var STRING_CAMELIZE_REGEXP = (/(\-|_|\s)+(.)?/g);
  4378. var STRING_UNDERSCORE_REGEXP_1 = (/([a-z\d])([A-Z]+)/g);
  4379. var STRING_UNDERSCORE_REGEXP_2 = (/\-|\s+/g);
  4380. /**
  4381. Defines the hash of localized strings for the current language. Used by
  4382. the `Ember.String.loc()` helper. To localize, add string values to this
  4383. hash.
  4384. @type Hash
  4385. */
  4386. Ember.STRINGS = {};
  4387. /**
  4388. Defines string helper methods including string formatting and localization.
  4389. Unless Ember.EXTEND_PROTOTYPES = false these methods will also be added to the
  4390. String.prototype as well.
  4391. @namespace
  4392. */
  4393. Ember.String = {
  4394. /**
  4395. Apply formatting options to the string. This will look for occurrences
  4396. of %@ in your string and substitute them with the arguments you pass into
  4397. this method. If you want to control the specific order of replacement,
  4398. you can add a number after the key as well to indicate which argument
  4399. you want to insert.
  4400. Ordered insertions are most useful when building loc strings where values
  4401. you need to insert may appear in different orders.
  4402. "Hello %@ %@".fmt('John', 'Doe') => "Hello John Doe"
  4403. "Hello %@2, %@1".fmt('John', 'Doe') => "Hello Doe, John"
  4404. @param {Object...} [args]
  4405. @returns {String} formatted string
  4406. */
  4407. fmt: function(str, formats) {
  4408. // first, replace any ORDERED replacements.
  4409. var idx = 0; // the current index for non-numerical replacements
  4410. return str.replace(/%@([0-9]+)?/g, function(s, argIndex) {
  4411. argIndex = (argIndex) ? parseInt(argIndex,0) - 1 : idx++ ;
  4412. s = formats[argIndex];
  4413. return ((s === null) ? '(null)' : (s === undefined) ? '' : s).toString();
  4414. }) ;
  4415. },
  4416. /**
  4417. Formats the passed string, but first looks up the string in the localized
  4418. strings hash. This is a convenient way to localize text. See
  4419. `Ember.String.fmt()` for more information on formatting.
  4420. Note that it is traditional but not required to prefix localized string
  4421. keys with an underscore or other character so you can easily identify
  4422. localized strings.
  4423. Ember.STRINGS = {
  4424. '_Hello World': 'Bonjour le monde',
  4425. '_Hello %@ %@': 'Bonjour %@ %@'
  4426. };
  4427. Ember.String.loc("_Hello World");
  4428. => 'Bonjour le monde';
  4429. Ember.String.loc("_Hello %@ %@", ["John", "Smith"]);
  4430. => "Bonjour John Smith";
  4431. @param {String} str
  4432. The string to format
  4433. @param {Array} formats
  4434. Optional array of parameters to interpolate into string.
  4435. @returns {String} formatted string
  4436. */
  4437. loc: function(str, formats) {
  4438. str = Ember.STRINGS[str] || str;
  4439. return Ember.String.fmt(str, formats) ;
  4440. },
  4441. /**
  4442. Splits a string into separate units separated by spaces, eliminating any
  4443. empty strings in the process. This is a convenience method for split that
  4444. is mostly useful when applied to the String.prototype.
  4445. Ember.String.w("alpha beta gamma").forEach(function(key) {
  4446. console.log(key);
  4447. });
  4448. > alpha
  4449. > beta
  4450. > gamma
  4451. @param {String} str
  4452. The string to split
  4453. @returns {String} split string
  4454. */
  4455. w: function(str) { return str.split(/\s+/); },
  4456. /**
  4457. Converts a camelized string into all lower case separated by underscores.
  4458. 'innerHTML'.decamelize() => 'inner_html'
  4459. 'action_name'.decamelize() => 'action_name'
  4460. 'css-class-name'.decamelize() => 'css-class-name'
  4461. 'my favorite items'.decamelize() => 'my favorite items'
  4462. @param {String} str
  4463. The string to decamelize.
  4464. @returns {String} the decamelized string.
  4465. */
  4466. decamelize: function(str) {
  4467. return str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase();
  4468. },
  4469. /**
  4470. Replaces underscores or spaces with dashes.
  4471. 'innerHTML'.dasherize() => 'inner-html'
  4472. 'action_name'.dasherize() => 'action-name'
  4473. 'css-class-name'.dasherize() => 'css-class-name'
  4474. 'my favorite items'.dasherize() => 'my-favorite-items'
  4475. @param {String} str
  4476. The string to dasherize.
  4477. @returns {String} the dasherized string.
  4478. */
  4479. dasherize: function(str) {
  4480. var cache = STRING_DASHERIZE_CACHE,
  4481. ret = cache[str];
  4482. if (ret) {
  4483. return ret;
  4484. } else {
  4485. ret = Ember.String.decamelize(str).replace(STRING_DASHERIZE_REGEXP,'-');
  4486. cache[str] = ret;
  4487. }
  4488. return ret;
  4489. },
  4490. /**
  4491. Returns the lowerCaseCamel form of a string.
  4492. 'innerHTML'.camelize() => 'innerHTML'
  4493. 'action_name'.camelize() => 'actionName'
  4494. 'css-class-name'.camelize() => 'cssClassName'
  4495. 'my favorite items'.camelize() => 'myFavoriteItems'
  4496. @param {String} str
  4497. The string to camelize.
  4498. @returns {String} the camelized string.
  4499. */
  4500. camelize: function(str) {
  4501. return str.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) {
  4502. return chr ? chr.toUpperCase() : '';
  4503. });
  4504. },
  4505. /**
  4506. Returns the UpperCamelCase form of a string.
  4507. 'innerHTML'.classify() => 'InnerHTML'
  4508. 'action_name'.classify() => 'ActionName'
  4509. 'css-class-name'.classify() => 'CssClassName'
  4510. 'my favorite items'.classift() => 'MyFavoriteItems'
  4511. */
  4512. classify: function(str) {
  4513. var camelized = Ember.String.camelize(str);
  4514. return camelized.charAt(0).toUpperCase() + camelized.substr(1);
  4515. },
  4516. /**
  4517. More general than decamelize. Returns the lower_case_and_underscored
  4518. form of a string.
  4519. 'innerHTML'.underscore() => 'inner_html'
  4520. 'action_name'.underscore() => 'action_name'
  4521. 'css-class-name'.underscore() => 'css_class_name'
  4522. 'my favorite items'.underscore() => 'my_favorite_items'
  4523. @param {String} str
  4524. The string to underscore.
  4525. @returns {String} the underscored string.
  4526. */
  4527. underscore: function(str) {
  4528. return str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2').
  4529. replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase();
  4530. }
  4531. };
  4532. })();
  4533. (function() {
  4534. // ==========================================================================
  4535. // Project: Ember Runtime
  4536. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  4537. // Portions ©2008-2011 Apple Inc. All rights reserved.
  4538. // License: Licensed under MIT license (see license.js)
  4539. // ==========================================================================
  4540. var fmt = Ember.String.fmt,
  4541. w = Ember.String.w,
  4542. loc = Ember.String.loc,
  4543. camelize = Ember.String.camelize,
  4544. decamelize = Ember.String.decamelize,
  4545. dasherize = Ember.String.dasherize,
  4546. underscore = Ember.String.underscore;
  4547. if (Ember.EXTEND_PROTOTYPES) {
  4548. /**
  4549. @see Ember.String.fmt
  4550. */
  4551. String.prototype.fmt = function() {
  4552. return fmt(this, arguments);
  4553. };
  4554. /**
  4555. @see Ember.String.w
  4556. */
  4557. String.prototype.w = function() {
  4558. return w(this);
  4559. };
  4560. /**
  4561. @see Ember.String.loc
  4562. */
  4563. String.prototype.loc = function() {
  4564. return loc(this, arguments);
  4565. };
  4566. /**
  4567. @see Ember.String.camelize
  4568. */
  4569. String.prototype.camelize = function() {
  4570. return camelize(this);
  4571. };
  4572. /**
  4573. @see Ember.String.decamelize
  4574. */
  4575. String.prototype.decamelize = function() {
  4576. return decamelize(this);
  4577. };
  4578. /**
  4579. @see Ember.String.dasherize
  4580. */
  4581. String.prototype.dasherize = function() {
  4582. return dasherize(this);
  4583. };
  4584. /**
  4585. @see Ember.String.underscore
  4586. */
  4587. String.prototype.underscore = function() {
  4588. return underscore(this);
  4589. };
  4590. }
  4591. })();
  4592. (function() {
  4593. // ==========================================================================
  4594. // Project: Ember Runtime
  4595. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  4596. // Portions ©2008-2011 Apple Inc. All rights reserved.
  4597. // License: Licensed under MIT license (see license.js)
  4598. // ==========================================================================
  4599. var a_slice = Array.prototype.slice;
  4600. if (Ember.EXTEND_PROTOTYPES) {
  4601. /**
  4602. The `property` extension of Javascript's Function prototype is available
  4603. when Ember.EXTEND_PROTOTYPES is true, which is the default.
  4604. Computed properties allow you to treat a function like a property:
  4605. MyApp.president = Ember.Object.create({
  4606. firstName: "Barack",
  4607. lastName: "Obama",
  4608. fullName: function() {
  4609. return this.get('firstName') + ' ' + this.get('lastName');
  4610. // Call this flag to mark the function as a property
  4611. }.property()
  4612. });
  4613. MyApp.president.get('fullName'); => "Barack Obama"
  4614. Treating a function like a property is useful because they can work with
  4615. bindings, just like any other property.
  4616. Many computed properties have dependencies on other properties. For
  4617. example, in the above example, the `fullName` property depends on
  4618. `firstName` and `lastName` to determine its value. You can tell Ember.js
  4619. about these dependencies like this:
  4620. MyApp.president = Ember.Object.create({
  4621. firstName: "Barack",
  4622. lastName: "Obama",
  4623. fullName: function() {
  4624. return this.get('firstName') + ' ' + this.get('lastName');
  4625. // Tell Ember.js that this computed property depends on firstName
  4626. // and lastName
  4627. }.property('firstName', 'lastName')
  4628. });
  4629. Make sure you list these dependencies so Ember.js knows when to update
  4630. bindings that connect to a computed property. Changing a dependency
  4631. will not immediately trigger an update of the computed property, but
  4632. will instead clear the cache so that it is updated when the next `get`
  4633. is called on the property.
  4634. Note: you will usually want to use `property(...)` with `cacheable()`.
  4635. @see Ember.ComputedProperty
  4636. @see Ember.computed
  4637. */
  4638. Function.prototype.property = function() {
  4639. var ret = Ember.computed(this);
  4640. return ret.property.apply(ret, arguments);
  4641. };
  4642. /**
  4643. The `observes` extension of Javascript's Function prototype is available
  4644. when Ember.EXTEND_PROTOTYPES is true, which is the default.
  4645. You can observe property changes simply by adding the `observes`
  4646. call to the end of your method declarations in classes that you write.
  4647. For example:
  4648. Ember.Object.create({
  4649. valueObserver: function() {
  4650. // Executes whenever the "value" property changes
  4651. }.observes('value')
  4652. });
  4653. @see Ember.Observable
  4654. */
  4655. Function.prototype.observes = function() {
  4656. this.__ember_observes__ = a_slice.call(arguments);
  4657. return this;
  4658. };
  4659. /**
  4660. The `observesBefore` extension of Javascript's Function prototype is
  4661. available when Ember.EXTEND_PROTOTYPES is true, which is the default.
  4662. You can get notified when a property changes is about to happen by
  4663. by adding the `observesBefore` call to the end of your method
  4664. declarations in classes that you write. For example:
  4665. Ember.Object.create({
  4666. valueObserver: function() {
  4667. // Executes whenever the "value" property is about to change
  4668. }.observesBefore('value')
  4669. });
  4670. @see Ember.Observable
  4671. */
  4672. Function.prototype.observesBefore = function() {
  4673. this.__ember_observesBefore__ = a_slice.call(arguments);
  4674. return this;
  4675. };
  4676. }
  4677. })();
  4678. (function() {
  4679. // ==========================================================================
  4680. // Project: Ember Runtime
  4681. // Copyright: ©2011 Strobe Inc. and contributors.
  4682. // License: Licensed under MIT license (see license.js)
  4683. // ==========================================================================
  4684. })();
  4685. (function() {
  4686. // ==========================================================================
  4687. // Project: Ember Runtime
  4688. // Copyright: ©2011 Strobe Inc. and contributors.
  4689. // License: Licensed under MIT license (see license.js)
  4690. // ==========================================================================
  4691. // ..........................................................
  4692. // HELPERS
  4693. //
  4694. var get = Ember.get, set = Ember.set;
  4695. var a_slice = Array.prototype.slice;
  4696. var a_indexOf = Ember.EnumerableUtils.indexOf;
  4697. var contexts = [];
  4698. /** @private */
  4699. function popCtx() {
  4700. return contexts.length===0 ? {} : contexts.pop();
  4701. }
  4702. /** @private */
  4703. function pushCtx(ctx) {
  4704. contexts.push(ctx);
  4705. return null;
  4706. }
  4707. /** @private */
  4708. function iter(key, value) {
  4709. var valueProvided = arguments.length === 2;
  4710. function i(item) {
  4711. var cur = get(item, key);
  4712. return valueProvided ? value===cur : !!cur;
  4713. }
  4714. return i ;
  4715. }
  4716. /**
  4717. @class
  4718. This mixin defines the common interface implemented by enumerable objects
  4719. in Ember. Most of these methods follow the standard Array iteration
  4720. API defined up to JavaScript 1.8 (excluding language-specific features that
  4721. cannot be emulated in older versions of JavaScript).
  4722. This mixin is applied automatically to the Array class on page load, so you
  4723. can use any of these methods on simple arrays. If Array already implements
  4724. one of these methods, the mixin will not override them.
  4725. h3. Writing Your Own Enumerable
  4726. To make your own custom class enumerable, you need two items:
  4727. 1. You must have a length property. This property should change whenever
  4728. the number of items in your enumerable object changes. If you using this
  4729. with an Ember.Object subclass, you should be sure to change the length
  4730. property using set().
  4731. 2. If you must implement nextObject(). See documentation.
  4732. Once you have these two methods implement, apply the Ember.Enumerable mixin
  4733. to your class and you will be able to enumerate the contents of your object
  4734. like any other collection.
  4735. h3. Using Ember Enumeration with Other Libraries
  4736. Many other libraries provide some kind of iterator or enumeration like
  4737. facility. This is often where the most common API conflicts occur.
  4738. Ember's API is designed to be as friendly as possible with other
  4739. libraries by implementing only methods that mostly correspond to the
  4740. JavaScript 1.8 API.
  4741. @extends Ember.Mixin
  4742. @since Ember 0.9
  4743. */
  4744. Ember.Enumerable = Ember.Mixin.create(
  4745. /** @scope Ember.Enumerable.prototype */ {
  4746. /** @private - compatibility */
  4747. isEnumerable: true,
  4748. /**
  4749. Implement this method to make your class enumerable.
  4750. This method will be call repeatedly during enumeration. The index value
  4751. will always begin with 0 and increment monotonically. You don't have to
  4752. rely on the index value to determine what object to return, but you should
  4753. always check the value and start from the beginning when you see the
  4754. requested index is 0.
  4755. The previousObject is the object that was returned from the last call
  4756. to nextObject for the current iteration. This is a useful way to
  4757. manage iteration if you are tracing a linked list, for example.
  4758. Finally the context parameter will always contain a hash you can use as
  4759. a "scratchpad" to maintain any other state you need in order to iterate
  4760. properly. The context object is reused and is not reset between
  4761. iterations so make sure you setup the context with a fresh state whenever
  4762. the index parameter is 0.
  4763. Generally iterators will continue to call nextObject until the index
  4764. reaches the your current length-1. If you run out of data before this
  4765. time for some reason, you should simply return undefined.
  4766. The default implementation of this method simply looks up the index.
  4767. This works great on any Array-like objects.
  4768. @param {Number} index the current index of the iteration
  4769. @param {Object} previousObject the value returned by the last call to nextObject.
  4770. @param {Object} context a context object you can use to maintain state.
  4771. @returns {Object} the next object in the iteration or undefined
  4772. */
  4773. nextObject: Ember.required(Function),
  4774. /**
  4775. Helper method returns the first object from a collection. This is usually
  4776. used by bindings and other parts of the framework to extract a single
  4777. object if the enumerable contains only one item.
  4778. If you override this method, you should implement it so that it will
  4779. always return the same value each time it is called. If your enumerable
  4780. contains only one object, this method should always return that object.
  4781. If your enumerable is empty, this method should return undefined.
  4782. var arr = ["a", "b", "c"];
  4783. arr.firstObject(); => "a"
  4784. var arr = [];
  4785. arr.firstObject(); => undefined
  4786. @returns {Object} the object or undefined
  4787. */
  4788. firstObject: Ember.computed(function() {
  4789. if (get(this, 'length')===0) return undefined ;
  4790. // handle generic enumerables
  4791. var context = popCtx(), ret;
  4792. ret = this.nextObject(0, null, context);
  4793. pushCtx(context);
  4794. return ret ;
  4795. }).property('[]').cacheable(),
  4796. /**
  4797. Helper method returns the last object from a collection. If your enumerable
  4798. contains only one object, this method should always return that object.
  4799. If your enumerable is empty, this method should return undefined.
  4800. var arr = ["a", "b", "c"];
  4801. arr.lastObject(); => "c"
  4802. var arr = [];
  4803. arr.lastObject(); => undefined
  4804. @returns {Object} the last object or undefined
  4805. */
  4806. lastObject: Ember.computed(function() {
  4807. var len = get(this, 'length');
  4808. if (len===0) return undefined ;
  4809. var context = popCtx(), idx=0, cur, last = null;
  4810. do {
  4811. last = cur;
  4812. cur = this.nextObject(idx++, last, context);
  4813. } while (cur !== undefined);
  4814. pushCtx(context);
  4815. return last;
  4816. }).property('[]').cacheable(),
  4817. /**
  4818. Returns true if the passed object can be found in the receiver. The
  4819. default version will iterate through the enumerable until the object
  4820. is found. You may want to override this with a more efficient version.
  4821. var arr = ["a", "b", "c"];
  4822. arr.contains("a"); => true
  4823. arr.contains("z"); => false
  4824. @param {Object} obj
  4825. The object to search for.
  4826. @returns {Boolean} true if object is found in enumerable.
  4827. */
  4828. contains: function(obj) {
  4829. return this.find(function(item) { return item===obj; }) !== undefined;
  4830. },
  4831. /**
  4832. Iterates through the enumerable, calling the passed function on each
  4833. item. This method corresponds to the forEach() method defined in
  4834. JavaScript 1.6.
  4835. The callback method you provide should have the following signature (all
  4836. parameters are optional):
  4837. function(item, index, enumerable);
  4838. - *item* is the current item in the iteration.
  4839. - *index* is the current index in the iteration
  4840. - *enumerable* is the enumerable object itself.
  4841. Note that in addition to a callback, you can also pass an optional target
  4842. object that will be set as "this" on the context. This is a good way
  4843. to give your iterator function access to the current object.
  4844. @param {Function} callback The callback to execute
  4845. @param {Object} [target] The target object to use
  4846. @returns {Object} receiver
  4847. */
  4848. forEach: function(callback, target) {
  4849. if (typeof callback !== "function") throw new TypeError() ;
  4850. var len = get(this, 'length'), last = null, context = popCtx();
  4851. if (target === undefined) target = null;
  4852. for(var idx=0;idx<len;idx++) {
  4853. var next = this.nextObject(idx, last, context) ;
  4854. callback.call(target, next, idx, this);
  4855. last = next ;
  4856. }
  4857. last = null ;
  4858. context = pushCtx(context);
  4859. return this ;
  4860. },
  4861. /**
  4862. Alias for mapProperty
  4863. @param {String} key name of the property
  4864. @returns {Array} The mapped array.
  4865. */
  4866. getEach: function(key) {
  4867. return this.mapProperty(key);
  4868. },
  4869. /**
  4870. Sets the value on the named property for each member. This is more
  4871. efficient than using other methods defined on this helper. If the object
  4872. implements Ember.Observable, the value will be changed to set(), otherwise
  4873. it will be set directly. null objects are skipped.
  4874. @param {String} key The key to set
  4875. @param {Object} value The object to set
  4876. @returns {Object} receiver
  4877. */
  4878. setEach: function(key, value) {
  4879. return this.forEach(function(item) {
  4880. set(item, key, value);
  4881. });
  4882. },
  4883. /**
  4884. Maps all of the items in the enumeration to another value, returning
  4885. a new array. This method corresponds to map() defined in JavaScript 1.6.
  4886. The callback method you provide should have the following signature (all
  4887. parameters are optional):
  4888. function(item, index, enumerable);
  4889. - *item* is the current item in the iteration.
  4890. - *index* is the current index in the iteration
  4891. - *enumerable* is the enumerable object itself.
  4892. It should return the mapped value.
  4893. Note that in addition to a callback, you can also pass an optional target
  4894. object that will be set as "this" on the context. This is a good way
  4895. to give your iterator function access to the current object.
  4896. @param {Function} callback The callback to execute
  4897. @param {Object} [target] The target object to use
  4898. @returns {Array} The mapped array.
  4899. */
  4900. map: function(callback, target) {
  4901. var ret = [];
  4902. this.forEach(function(x, idx, i) {
  4903. ret[idx] = callback.call(target, x, idx,i);
  4904. });
  4905. return ret ;
  4906. },
  4907. /**
  4908. Similar to map, this specialized function returns the value of the named
  4909. property on all items in the enumeration.
  4910. @param {String} key name of the property
  4911. @returns {Array} The mapped array.
  4912. */
  4913. mapProperty: function(key) {
  4914. return this.map(function(next) {
  4915. return get(next, key);
  4916. });
  4917. },
  4918. /**
  4919. Returns an array with all of the items in the enumeration that the passed
  4920. function returns true for. This method corresponds to filter() defined in
  4921. JavaScript 1.6.
  4922. The callback method you provide should have the following signature (all
  4923. parameters are optional):
  4924. function(item, index, enumerable);
  4925. - *item* is the current item in the iteration.
  4926. - *index* is the current index in the iteration
  4927. - *enumerable* is the enumerable object itself.
  4928. It should return the true to include the item in the results, false otherwise.
  4929. Note that in addition to a callback, you can also pass an optional target
  4930. object that will be set as "this" on the context. This is a good way
  4931. to give your iterator function access to the current object.
  4932. @param {Function} callback The callback to execute
  4933. @param {Object} [target] The target object to use
  4934. @returns {Array} A filtered array.
  4935. */
  4936. filter: function(callback, target) {
  4937. var ret = [];
  4938. this.forEach(function(x, idx, i) {
  4939. if (callback.call(target, x, idx, i)) ret.push(x);
  4940. });
  4941. return ret ;
  4942. },
  4943. /**
  4944. Returns an array with just the items with the matched property. You
  4945. can pass an optional second argument with the target value. Otherwise
  4946. this will match any property that evaluates to true.
  4947. @param {String} key the property to test
  4948. @param {String} [value] optional value to test against.
  4949. @returns {Array} filtered array
  4950. */
  4951. filterProperty: function(key, value) {
  4952. return this.filter(iter.apply(this, arguments));
  4953. },
  4954. /**
  4955. Returns the first item in the array for which the callback returns true.
  4956. This method works similar to the filter() method defined in JavaScript 1.6
  4957. except that it will stop working on the array once a match is found.
  4958. The callback method you provide should have the following signature (all
  4959. parameters are optional):
  4960. function(item, index, enumerable);
  4961. - *item* is the current item in the iteration.
  4962. - *index* is the current index in the iteration
  4963. - *enumerable* is the enumerable object itself.
  4964. It should return the true to include the item in the results, false otherwise.
  4965. Note that in addition to a callback, you can also pass an optional target
  4966. object that will be set as "this" on the context. This is a good way
  4967. to give your iterator function access to the current object.
  4968. @param {Function} callback The callback to execute
  4969. @param {Object} [target] The target object to use
  4970. @returns {Object} Found item or null.
  4971. */
  4972. find: function(callback, target) {
  4973. var len = get(this, 'length') ;
  4974. if (target === undefined) target = null;
  4975. var last = null, next, found = false, ret ;
  4976. var context = popCtx();
  4977. for(var idx=0;idx<len && !found;idx++) {
  4978. next = this.nextObject(idx, last, context) ;
  4979. if (found = callback.call(target, next, idx, this)) ret = next ;
  4980. last = next ;
  4981. }
  4982. next = last = null ;
  4983. context = pushCtx(context);
  4984. return ret ;
  4985. },
  4986. /**
  4987. Returns the first item with a property matching the passed value. You
  4988. can pass an optional second argument with the target value. Otherwise
  4989. this will match any property that evaluates to true.
  4990. This method works much like the more generic find() method.
  4991. @param {String} key the property to test
  4992. @param {String} [value] optional value to test against.
  4993. @returns {Object} found item or null
  4994. */
  4995. findProperty: function(key, value) {
  4996. return this.find(iter.apply(this, arguments));
  4997. },
  4998. /**
  4999. Returns true if the passed function returns true for every item in the
  5000. enumeration. This corresponds with the every() method in JavaScript 1.6.
  5001. The callback method you provide should have the following signature (all
  5002. parameters are optional):
  5003. function(item, index, enumerable);
  5004. - *item* is the current item in the iteration.
  5005. - *index* is the current index in the iteration
  5006. - *enumerable* is the enumerable object itself.
  5007. It should return the true or false.
  5008. Note that in addition to a callback, you can also pass an optional target
  5009. object that will be set as "this" on the context. This is a good way
  5010. to give your iterator function access to the current object.
  5011. Example Usage:
  5012. if (people.every(isEngineer)) { Paychecks.addBigBonus(); }
  5013. @param {Function} callback The callback to execute
  5014. @param {Object} [target] The target object to use
  5015. @returns {Boolean}
  5016. */
  5017. every: function(callback, target) {
  5018. return !this.find(function(x, idx, i) {
  5019. return !callback.call(target, x, idx, i);
  5020. });
  5021. },
  5022. /**
  5023. Returns true if the passed property resolves to true for all items in the
  5024. enumerable. This method is often simpler/faster than using a callback.
  5025. @param {String} key the property to test
  5026. @param {String} [value] optional value to test against.
  5027. @returns {Array} filtered array
  5028. */
  5029. everyProperty: function(key, value) {
  5030. return this.every(iter.apply(this, arguments));
  5031. },
  5032. /**
  5033. Returns true if the passed function returns true for any item in the
  5034. enumeration. This corresponds with the every() method in JavaScript 1.6.
  5035. The callback method you provide should have the following signature (all
  5036. parameters are optional):
  5037. function(item, index, enumerable);
  5038. - *item* is the current item in the iteration.
  5039. - *index* is the current index in the iteration
  5040. - *enumerable* is the enumerable object itself.
  5041. It should return the true to include the item in the results, false otherwise.
  5042. Note that in addition to a callback, you can also pass an optional target
  5043. object that will be set as "this" on the context. This is a good way
  5044. to give your iterator function access to the current object.
  5045. Usage Example:
  5046. if (people.some(isManager)) { Paychecks.addBiggerBonus(); }
  5047. @param {Function} callback The callback to execute
  5048. @param {Object} [target] The target object to use
  5049. @returns {Array} A filtered array.
  5050. */
  5051. some: function(callback, target) {
  5052. return !!this.find(function(x, idx, i) {
  5053. return !!callback.call(target, x, idx, i);
  5054. });
  5055. },
  5056. /**
  5057. Returns true if the passed property resolves to true for any item in the
  5058. enumerable. This method is often simpler/faster than using a callback.
  5059. @param {String} key the property to test
  5060. @param {String} [value] optional value to test against.
  5061. @returns {Boolean} true
  5062. */
  5063. someProperty: function(key, value) {
  5064. return this.some(iter.apply(this, arguments));
  5065. },
  5066. /**
  5067. This will combine the values of the enumerator into a single value. It
  5068. is a useful way to collect a summary value from an enumeration. This
  5069. corresponds to the reduce() method defined in JavaScript 1.8.
  5070. The callback method you provide should have the following signature (all
  5071. parameters are optional):
  5072. function(previousValue, item, index, enumerable);
  5073. - *previousValue* is the value returned by the last call to the iterator.
  5074. - *item* is the current item in the iteration.
  5075. - *index* is the current index in the iteration
  5076. - *enumerable* is the enumerable object itself.
  5077. Return the new cumulative value.
  5078. In addition to the callback you can also pass an initialValue. An error
  5079. will be raised if you do not pass an initial value and the enumerator is
  5080. empty.
  5081. Note that unlike the other methods, this method does not allow you to
  5082. pass a target object to set as this for the callback. It's part of the
  5083. spec. Sorry.
  5084. @param {Function} callback The callback to execute
  5085. @param {Object} initialValue Initial value for the reduce
  5086. @param {String} reducerProperty internal use only.
  5087. @returns {Object} The reduced value.
  5088. */
  5089. reduce: function(callback, initialValue, reducerProperty) {
  5090. if (typeof callback !== "function") { throw new TypeError(); }
  5091. var ret = initialValue;
  5092. this.forEach(function(item, i) {
  5093. ret = callback.call(null, ret, item, i, this, reducerProperty);
  5094. }, this);
  5095. return ret;
  5096. },
  5097. /**
  5098. Invokes the named method on every object in the receiver that
  5099. implements it. This method corresponds to the implementation in
  5100. Prototype 1.6.
  5101. @param {String} methodName the name of the method
  5102. @param {Object...} args optional arguments to pass as well.
  5103. @returns {Array} return values from calling invoke.
  5104. */
  5105. invoke: function(methodName) {
  5106. var args, ret = [];
  5107. if (arguments.length>1) args = a_slice.call(arguments, 1);
  5108. this.forEach(function(x, idx) {
  5109. var method = x && x[methodName];
  5110. if ('function' === typeof method) {
  5111. ret[idx] = args ? method.apply(x, args) : method.call(x);
  5112. }
  5113. }, this);
  5114. return ret;
  5115. },
  5116. /**
  5117. Simply converts the enumerable into a genuine array. The order is not
  5118. guaranteed. Corresponds to the method implemented by Prototype.
  5119. @returns {Array} the enumerable as an array.
  5120. */
  5121. toArray: function() {
  5122. var ret = [];
  5123. this.forEach(function(o, idx) { ret[idx] = o; });
  5124. return ret ;
  5125. },
  5126. /**
  5127. Returns a copy of the array with all null elements removed.
  5128. var arr = ["a", null, "c", null];
  5129. arr.compact(); => ["a", "c"]
  5130. @returns {Array} the array without null elements.
  5131. */
  5132. compact: function() { return this.without(null); },
  5133. /**
  5134. Returns a new enumerable that excludes the passed value. The default
  5135. implementation returns an array regardless of the receiver type unless
  5136. the receiver does not contain the value.
  5137. var arr = ["a", "b", "a", "c"];
  5138. arr.without("a"); => ["b", "c"]
  5139. @param {Object} value
  5140. @returns {Ember.Enumerable}
  5141. */
  5142. without: function(value) {
  5143. if (!this.contains(value)) return this; // nothing to do
  5144. var ret = [] ;
  5145. this.forEach(function(k) {
  5146. if (k !== value) ret[ret.length] = k;
  5147. }) ;
  5148. return ret ;
  5149. },
  5150. /**
  5151. Returns a new enumerable that contains only unique values. The default
  5152. implementation returns an array regardless of the receiver type.
  5153. var arr = ["a", "a", "b", "b"];
  5154. arr.uniq(); => ["a", "b"]
  5155. @returns {Ember.Enumerable}
  5156. */
  5157. uniq: function() {
  5158. var ret = [];
  5159. this.forEach(function(k){
  5160. if (a_indexOf(ret, k)<0) ret.push(k);
  5161. });
  5162. return ret;
  5163. },
  5164. /**
  5165. This property will trigger anytime the enumerable's content changes.
  5166. You can observe this property to be notified of changes to the enumerables
  5167. content.
  5168. For plain enumerables, this property is read only. Ember.Array overrides
  5169. this method.
  5170. @type Ember.Array
  5171. */
  5172. '[]': Ember.computed(function(key, value) {
  5173. return this;
  5174. }).property().cacheable(),
  5175. // ..........................................................
  5176. // ENUMERABLE OBSERVERS
  5177. //
  5178. /**
  5179. Registers an enumerable observer. Must implement Ember.EnumerableObserver
  5180. mixin.
  5181. */
  5182. addEnumerableObserver: function(target, opts) {
  5183. var willChange = (opts && opts.willChange) || 'enumerableWillChange',
  5184. didChange = (opts && opts.didChange) || 'enumerableDidChange';
  5185. var hasObservers = get(this, 'hasEnumerableObservers');
  5186. if (!hasObservers) Ember.propertyWillChange(this, 'hasEnumerableObservers');
  5187. Ember.addListener(this, '@enumerable:before', target, willChange);
  5188. Ember.addListener(this, '@enumerable:change', target, didChange);
  5189. if (!hasObservers) Ember.propertyDidChange(this, 'hasEnumerableObservers');
  5190. return this;
  5191. },
  5192. /**
  5193. Removes a registered enumerable observer.
  5194. */
  5195. removeEnumerableObserver: function(target, opts) {
  5196. var willChange = (opts && opts.willChange) || 'enumerableWillChange',
  5197. didChange = (opts && opts.didChange) || 'enumerableDidChange';
  5198. var hasObservers = get(this, 'hasEnumerableObservers');
  5199. if (hasObservers) Ember.propertyWillChange(this, 'hasEnumerableObservers');
  5200. Ember.removeListener(this, '@enumerable:before', target, willChange);
  5201. Ember.removeListener(this, '@enumerable:change', target, didChange);
  5202. if (hasObservers) Ember.propertyDidChange(this, 'hasEnumerableObservers');
  5203. return this;
  5204. },
  5205. /**
  5206. Becomes true whenever the array currently has observers watching changes
  5207. on the array.
  5208. @type Boolean
  5209. */
  5210. hasEnumerableObservers: Ember.computed(function() {
  5211. return Ember.hasListeners(this, '@enumerable:change') || Ember.hasListeners(this, '@enumerable:before');
  5212. }).property().cacheable(),
  5213. /**
  5214. Invoke this method just before the contents of your enumerable will
  5215. change. You can either omit the parameters completely or pass the objects
  5216. to be removed or added if available or just a count.
  5217. @param {Ember.Enumerable|Number} removing
  5218. An enumerable of the objects to be removed or the number of items to
  5219. be removed.
  5220. @param {Ember.Enumerable|Number} adding
  5221. An enumerable of the objects to be added or the number of items to be
  5222. added.
  5223. @returns {Ember.Enumerable} receiver
  5224. */
  5225. enumerableContentWillChange: function(removing, adding) {
  5226. var removeCnt, addCnt, hasDelta;
  5227. if ('number' === typeof removing) removeCnt = removing;
  5228. else if (removing) removeCnt = get(removing, 'length');
  5229. else removeCnt = removing = -1;
  5230. if ('number' === typeof adding) addCnt = adding;
  5231. else if (adding) addCnt = get(adding,'length');
  5232. else addCnt = adding = -1;
  5233. hasDelta = addCnt<0 || removeCnt<0 || addCnt-removeCnt!==0;
  5234. if (removing === -1) removing = null;
  5235. if (adding === -1) adding = null;
  5236. Ember.propertyWillChange(this, '[]');
  5237. if (hasDelta) Ember.propertyWillChange(this, 'length');
  5238. Ember.sendEvent(this, '@enumerable:before', [this, removing, adding]);
  5239. return this;
  5240. },
  5241. /**
  5242. Invoke this method when the contents of your enumerable has changed.
  5243. This will notify any observers watching for content changes. If your are
  5244. implementing an ordered enumerable (such as an array), also pass the
  5245. start and end values where the content changed so that it can be used to
  5246. notify range observers.
  5247. @param {Number} start
  5248. optional start offset for the content change. For unordered
  5249. enumerables, you should always pass -1.
  5250. @param {Ember.Enumerable|Number} removing
  5251. An enumerable of the objects to be removed or the number of items to
  5252. be removed.
  5253. @param {Ember.Enumerable|Number} adding
  5254. An enumerable of the objects to be added or the number of items to be
  5255. added.
  5256. @returns {Object} receiver
  5257. */
  5258. enumerableContentDidChange: function(removing, adding) {
  5259. var notify = this.propertyDidChange, removeCnt, addCnt, hasDelta;
  5260. if ('number' === typeof removing) removeCnt = removing;
  5261. else if (removing) removeCnt = get(removing, 'length');
  5262. else removeCnt = removing = -1;
  5263. if ('number' === typeof adding) addCnt = adding;
  5264. else if (adding) addCnt = get(adding, 'length');
  5265. else addCnt = adding = -1;
  5266. hasDelta = addCnt<0 || removeCnt<0 || addCnt-removeCnt!==0;
  5267. if (removing === -1) removing = null;
  5268. if (adding === -1) adding = null;
  5269. Ember.sendEvent(this, '@enumerable:change', [this, removing, adding]);
  5270. if (hasDelta) Ember.propertyDidChange(this, 'length');
  5271. Ember.propertyDidChange(this, '[]');
  5272. return this ;
  5273. },
  5274. /**
  5275. Converts the enumerable into an array and sorts by the keys
  5276. specified in the argument.
  5277. You may provide multiple arguments to sort by multiple properties.
  5278. @method sortProperty
  5279. @param {String} property name(s) to sort on
  5280. @return {Array} The sorted array.
  5281. */
  5282. sortProperty: function() {
  5283. var sortKeys = arguments;
  5284. return this.toArray().sort(function(a, b){
  5285. for(var i = 0; i < sortKeys.length; i++) {
  5286. var key = sortKeys[i],
  5287. propA = Ember.get(a, key),
  5288. propB = Ember.get(b, key);
  5289. // return 1 or -1 else continue to the next sortKey
  5290. var compareValue = Ember.compare(propA, propB);
  5291. if (compareValue) { return compareValue; }
  5292. }
  5293. return 0;
  5294. });
  5295. },
  5296. /**
  5297. Returns an array with all of the items in the enumeration where the passed
  5298. function returns false for. This method is the inverse of filter().
  5299. The callback method you provide should have the following signature (all
  5300. parameters are optional):
  5301. ```javascript
  5302. function(item, index, enumerable);
  5303. ```
  5304. - *item* is the current item in the iteration.
  5305. - *index* is the current index in the iteration
  5306. - *enumerable* is the enumerable object itself.
  5307. It should return the a falsey value to include the item in the results.
  5308. Note that in addition to a callback, you can also pass an optional target
  5309. object that will be set as "this" on the context. This is a good way
  5310. to give your iterator function access to the current object.
  5311. @method reject
  5312. @param {Function} callback The callback to execute
  5313. @param {Object} [target] The target object to use
  5314. @return {Array} A rejected array.
  5315. */
  5316. reject: function(callback, target) {
  5317. return this.filter(function() {
  5318. return !(callback.apply(target, arguments));
  5319. });
  5320. },
  5321. /**
  5322. Returns an array with the items that do not have truthy values for
  5323. key. You can pass an optional second argument with the target value. Otherwise
  5324. this will match any property that evaluates to false.
  5325. @method rejectProperty
  5326. @param {String} key the property to test
  5327. @param {String} [value] optional value to test against.
  5328. @return {Array} rejected array
  5329. */
  5330. rejectProperty: function(key, value) {
  5331. var exactValue = function(item) { return Ember.get(item, key) === value; },
  5332. hasValue = function(item) { return !!Ember.get(item, key); },
  5333. use = (arguments.length === 2 ? exactValue : hasValue);
  5334. return this.reject(use);
  5335. },
  5336. /**
  5337. Returns a copy of the array without elements with `key` equal to `null` and `undefined`.
  5338. ```javascript
  5339. var arr = [Ember.Object.create({a: null}), {a: 1}, {a: false}, {a: ''}, {a: undefined}, {a: 0}, {a: null}];
  5340. arr.compactProperty("a"); // [{a: 1}, {a: false}, {a: ''}, {a: 0}]
  5341. ```
  5342. @method compactProperty
  5343. @param {String} key name of the property
  5344. @return {Array} the array without elements with `key` equal to `null` and `undefined`.
  5345. */
  5346. compactProperty: function(key) {
  5347. return this.filter(function(item) { return !Ember.isNone(Ember.get(item, key)); });
  5348. }
  5349. }) ;
  5350. })();
  5351. (function() {
  5352. // ==========================================================================
  5353. // Project: Ember Runtime
  5354. // Copyright: ©2011 Strobe Inc. and contributors.
  5355. // License: Licensed under MIT license (see license.js)
  5356. // ==========================================================================
  5357. // ..........................................................
  5358. // HELPERS
  5359. //
  5360. var get = Ember.get, set = Ember.set, meta = Ember.meta, map = Ember.EnumerableUtils.map, cacheFor = Ember.cacheFor;
  5361. /** @private */
  5362. function none(obj) { return obj===null || obj===undefined; }
  5363. // ..........................................................
  5364. // ARRAY
  5365. //
  5366. /**
  5367. @namespace
  5368. This module implements Observer-friendly Array-like behavior. This mixin is
  5369. picked up by the Array class as well as other controllers, etc. that want to
  5370. appear to be arrays.
  5371. Unlike Ember.Enumerable, this mixin defines methods specifically for
  5372. collections that provide index-ordered access to their contents. When you
  5373. are designing code that needs to accept any kind of Array-like object, you
  5374. should use these methods instead of Array primitives because these will
  5375. properly notify observers of changes to the array.
  5376. Although these methods are efficient, they do add a layer of indirection to
  5377. your application so it is a good idea to use them only when you need the
  5378. flexibility of using both true JavaScript arrays and "virtual" arrays such
  5379. as controllers and collections.
  5380. You can use the methods defined in this module to access and modify array
  5381. contents in a KVO-friendly way. You can also be notified whenever the
  5382. membership if an array changes by changing the syntax of the property to
  5383. .observes('*myProperty.[]') .
  5384. To support Ember.Array in your own class, you must override two
  5385. primitives to use it: replace() and objectAt().
  5386. Note that the Ember.Array mixin also incorporates the Ember.Enumerable mixin. All
  5387. Ember.Array-like objects are also enumerable.
  5388. @extends Ember.Enumerable
  5389. @since Ember 0.9.0
  5390. */
  5391. Ember.Array = Ember.Mixin.create(Ember.Enumerable, /** @scope Ember.Array.prototype */ {
  5392. /** @private - compatibility */
  5393. isSCArray: true,
  5394. /**
  5395. @field {Number} length
  5396. Your array must support the length property. Your replace methods should
  5397. set this property whenever it changes.
  5398. */
  5399. length: Ember.required(),
  5400. /**
  5401. Returns the object at the given index. If the given index is negative or
  5402. is greater or equal than the array length, returns `undefined`.
  5403. This is one of the primitives you must implement to support `Ember.Array`.
  5404. If your object supports retrieving the value of an array item using `get()`
  5405. (i.e. `myArray.get(0)`), then you do not need to implement this method
  5406. yourself.
  5407. var arr = ['a', 'b', 'c', 'd'];
  5408. arr.objectAt(0); => "a"
  5409. arr.objectAt(3); => "d"
  5410. arr.objectAt(-1); => undefined
  5411. arr.objectAt(4); => undefined
  5412. arr.objectAt(5); => undefined
  5413. @param {Number} idx
  5414. The index of the item to return.
  5415. */
  5416. objectAt: function(idx) {
  5417. if ((idx < 0) || (idx>=get(this, 'length'))) return undefined ;
  5418. return get(this, idx);
  5419. },
  5420. /**
  5421. This returns the objects at the specified indexes, using `objectAt`.
  5422. var arr = ['a', 'b', 'c', 'd'];
  5423. arr.objectsAt([0, 1, 2]) => ["a", "b", "c"]
  5424. arr.objectsAt([2, 3, 4]) => ["c", "d", undefined]
  5425. @param {Array} indexes
  5426. An array of indexes of items to return.
  5427. */
  5428. objectsAt: function(indexes) {
  5429. var self = this;
  5430. return map(indexes, function(idx){ return self.objectAt(idx); });
  5431. },
  5432. /** @private (nodoc) - overrides Ember.Enumerable version */
  5433. nextObject: function(idx) {
  5434. return this.objectAt(idx);
  5435. },
  5436. /**
  5437. @field []
  5438. This is the handler for the special array content property. If you get
  5439. this property, it will return this. If you set this property it a new
  5440. array, it will replace the current content.
  5441. This property overrides the default property defined in Ember.Enumerable.
  5442. */
  5443. '[]': Ember.computed(function(key, value) {
  5444. if (value !== undefined) this.replace(0, get(this, 'length'), value) ;
  5445. return this ;
  5446. }).property().cacheable(),
  5447. firstObject: Ember.computed(function() {
  5448. return this.objectAt(0);
  5449. }).property().cacheable(),
  5450. lastObject: Ember.computed(function() {
  5451. return this.objectAt(get(this, 'length')-1);
  5452. }).property().cacheable(),
  5453. /** @private (nodoc) - optimized version from Enumerable */
  5454. contains: function(obj){
  5455. return this.indexOf(obj) >= 0;
  5456. },
  5457. // Add any extra methods to Ember.Array that are native to the built-in Array.
  5458. /**
  5459. Returns a new array that is a slice of the receiver. This implementation
  5460. uses the observable array methods to retrieve the objects for the new
  5461. slice.
  5462. var arr = ['red', 'green', 'blue'];
  5463. arr.slice(0); => ['red', 'green', 'blue']
  5464. arr.slice(0, 2); => ['red', 'green']
  5465. arr.slice(1, 100); => ['green', 'blue']
  5466. @param beginIndex {Integer} (Optional) index to begin slicing from.
  5467. @param endIndex {Integer} (Optional) index to end the slice at.
  5468. @returns {Array} New array with specified slice
  5469. */
  5470. slice: function(beginIndex, endIndex) {
  5471. var ret = [];
  5472. var length = get(this, 'length') ;
  5473. if (none(beginIndex)) beginIndex = 0 ;
  5474. if (none(endIndex) || (endIndex > length)) endIndex = length ;
  5475. while(beginIndex < endIndex) {
  5476. ret[ret.length] = this.objectAt(beginIndex++) ;
  5477. }
  5478. return ret ;
  5479. },
  5480. /**
  5481. Returns the index of the given object's first occurrence.
  5482. If no startAt argument is given, the starting location to
  5483. search is 0. If it's negative, will count backward from
  5484. the end of the array. Returns -1 if no match is found.
  5485. var arr = ["a", "b", "c", "d", "a"];
  5486. arr.indexOf("a"); => 0
  5487. arr.indexOf("z"); => -1
  5488. arr.indexOf("a", 2); => 4
  5489. arr.indexOf("a", -1); => 4
  5490. arr.indexOf("b", 3); => -1
  5491. arr.indexOf("a", 100); => -1
  5492. @param {Object} object the item to search for
  5493. @param {Number} startAt optional starting location to search, default 0
  5494. @returns {Number} index or -1 if not found
  5495. */
  5496. indexOf: function(object, startAt) {
  5497. var idx, len = get(this, 'length');
  5498. if (startAt === undefined) startAt = 0;
  5499. if (startAt < 0) startAt += len;
  5500. for(idx=startAt;idx<len;idx++) {
  5501. if (this.objectAt(idx, true) === object) return idx ;
  5502. }
  5503. return -1;
  5504. },
  5505. /**
  5506. Returns the index of the given object's last occurrence.
  5507. If no startAt argument is given, the search starts from
  5508. the last position. If it's negative, will count backward
  5509. from the end of the array. Returns -1 if no match is found.
  5510. var arr = ["a", "b", "c", "d", "a"];
  5511. arr.lastIndexOf("a"); => 4
  5512. arr.lastIndexOf("z"); => -1
  5513. arr.lastIndexOf("a", 2); => 0
  5514. arr.lastIndexOf("a", -1); => 4
  5515. arr.lastIndexOf("b", 3); => 1
  5516. arr.lastIndexOf("a", 100); => 4
  5517. @param {Object} object the item to search for
  5518. @param {Number} startAt optional starting location to search, default 0
  5519. @returns {Number} index or -1 if not found
  5520. */
  5521. lastIndexOf: function(object, startAt) {
  5522. var idx, len = get(this, 'length');
  5523. if (startAt === undefined || startAt >= len) startAt = len-1;
  5524. if (startAt < 0) startAt += len;
  5525. for(idx=startAt;idx>=0;idx--) {
  5526. if (this.objectAt(idx) === object) return idx ;
  5527. }
  5528. return -1;
  5529. },
  5530. // ..........................................................
  5531. // ARRAY OBSERVERS
  5532. //
  5533. /**
  5534. Adds an array observer to the receiving array. The array observer object
  5535. normally must implement two methods:
  5536. * `arrayWillChange(start, removeCount, addCount)` - This method will be
  5537. called just before the array is modified.
  5538. * `arrayDidChange(start, removeCount, addCount)` - This method will be
  5539. called just after the array is modified.
  5540. Both callbacks will be passed the starting index of the change as well a
  5541. a count of the items to be removed and added. You can use these callbacks
  5542. to optionally inspect the array during the change, clear caches, or do
  5543. any other bookkeeping necessary.
  5544. In addition to passing a target, you can also include an options hash
  5545. which you can use to override the method names that will be invoked on the
  5546. target.
  5547. @param {Object} target
  5548. The observer object.
  5549. @param {Hash} opts
  5550. Optional hash of configuration options including willChange, didChange,
  5551. and a context option.
  5552. @returns {Ember.Array} receiver
  5553. */
  5554. addArrayObserver: function(target, opts) {
  5555. var willChange = (opts && opts.willChange) || 'arrayWillChange',
  5556. didChange = (opts && opts.didChange) || 'arrayDidChange';
  5557. var hasObservers = get(this, 'hasArrayObservers');
  5558. if (!hasObservers) Ember.propertyWillChange(this, 'hasArrayObservers');
  5559. Ember.addListener(this, '@array:before', target, willChange);
  5560. Ember.addListener(this, '@array:change', target, didChange);
  5561. if (!hasObservers) Ember.propertyDidChange(this, 'hasArrayObservers');
  5562. return this;
  5563. },
  5564. /**
  5565. Removes an array observer from the object if the observer is current
  5566. registered. Calling this method multiple times with the same object will
  5567. have no effect.
  5568. @param {Object} target
  5569. The object observing the array.
  5570. @returns {Ember.Array} receiver
  5571. */
  5572. removeArrayObserver: function(target, opts) {
  5573. var willChange = (opts && opts.willChange) || 'arrayWillChange',
  5574. didChange = (opts && opts.didChange) || 'arrayDidChange';
  5575. var hasObservers = get(this, 'hasArrayObservers');
  5576. if (hasObservers) Ember.propertyWillChange(this, 'hasArrayObservers');
  5577. Ember.removeListener(this, '@array:before', target, willChange);
  5578. Ember.removeListener(this, '@array:change', target, didChange);
  5579. if (hasObservers) Ember.propertyDidChange(this, 'hasArrayObservers');
  5580. return this;
  5581. },
  5582. /**
  5583. Becomes true whenever the array currently has observers watching changes
  5584. on the array.
  5585. @type Boolean
  5586. */
  5587. hasArrayObservers: Ember.computed(function() {
  5588. return Ember.hasListeners(this, '@array:change') || Ember.hasListeners(this, '@array:before');
  5589. }).property().cacheable(),
  5590. /**
  5591. If you are implementing an object that supports Ember.Array, call this
  5592. method just before the array content changes to notify any observers and
  5593. invalidate any related properties. Pass the starting index of the change
  5594. as well as a delta of the amounts to change.
  5595. @param {Number} startIdx
  5596. The starting index in the array that will change.
  5597. @param {Number} removeAmt
  5598. The number of items that will be removed. If you pass null assumes 0
  5599. @param {Number} addAmt
  5600. The number of items that will be added. If you pass null assumes 0.
  5601. @returns {Ember.Array} receiver
  5602. */
  5603. arrayContentWillChange: function(startIdx, removeAmt, addAmt) {
  5604. // if no args are passed assume everything changes
  5605. if (startIdx===undefined) {
  5606. startIdx = 0;
  5607. removeAmt = addAmt = -1;
  5608. } else {
  5609. if (removeAmt === undefined) removeAmt=-1;
  5610. if (addAmt === undefined) addAmt=-1;
  5611. }
  5612. // Make sure the @each proxy is set up if anyone is observing @each
  5613. if (Ember.isWatching(this, '@each')) { get(this, '@each'); }
  5614. Ember.sendEvent(this, '@array:before', [this, startIdx, removeAmt, addAmt]);
  5615. var removing, lim;
  5616. if (startIdx>=0 && removeAmt>=0 && get(this, 'hasEnumerableObservers')) {
  5617. removing = [];
  5618. lim = startIdx+removeAmt;
  5619. for(var idx=startIdx;idx<lim;idx++) removing.push(this.objectAt(idx));
  5620. } else {
  5621. removing = removeAmt;
  5622. }
  5623. this.enumerableContentWillChange(removing, addAmt);
  5624. return this;
  5625. },
  5626. arrayContentDidChange: function(startIdx, removeAmt, addAmt) {
  5627. // if no args are passed assume everything changes
  5628. if (startIdx===undefined) {
  5629. startIdx = 0;
  5630. removeAmt = addAmt = -1;
  5631. } else {
  5632. if (removeAmt === undefined) removeAmt=-1;
  5633. if (addAmt === undefined) addAmt=-1;
  5634. }
  5635. var adding, lim;
  5636. if (startIdx>=0 && addAmt>=0 && get(this, 'hasEnumerableObservers')) {
  5637. adding = [];
  5638. lim = startIdx+addAmt;
  5639. for(var idx=startIdx;idx<lim;idx++) adding.push(this.objectAt(idx));
  5640. } else {
  5641. adding = addAmt;
  5642. }
  5643. this.enumerableContentDidChange(removeAmt, adding);
  5644. Ember.sendEvent(this, '@array:change', [this, startIdx, removeAmt, addAmt]);
  5645. var length = get(this, 'length'),
  5646. cachedFirst = cacheFor(this, 'firstObject'),
  5647. cachedLast = cacheFor(this, 'lastObject');
  5648. if (this.objectAt(0) !== cachedFirst) {
  5649. Ember.propertyWillChange(this, 'firstObject');
  5650. Ember.propertyDidChange(this, 'firstObject');
  5651. }
  5652. if (this.objectAt(length-1) !== cachedLast) {
  5653. Ember.propertyWillChange(this, 'lastObject');
  5654. Ember.propertyDidChange(this, 'lastObject');
  5655. }
  5656. return this;
  5657. },
  5658. // ..........................................................
  5659. // ENUMERATED PROPERTIES
  5660. //
  5661. /**
  5662. Returns a special object that can be used to observe individual properties
  5663. on the array. Just get an equivalent property on this object and it will
  5664. return an enumerable that maps automatically to the named key on the
  5665. member objects.
  5666. */
  5667. '@each': Ember.computed(function() {
  5668. if (!this.__each) this.__each = new Ember.EachProxy(this);
  5669. return this.__each;
  5670. }).property().cacheable()
  5671. }) ;
  5672. })();
  5673. (function() {
  5674. // ==========================================================================
  5675. // Project: Ember Runtime
  5676. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  5677. // Portions ©2008-2011 Apple Inc. All rights reserved.
  5678. // License: Licensed under MIT license (see license.js)
  5679. // ==========================================================================
  5680. /**
  5681. @namespace
  5682. Implements some standard methods for comparing objects. Add this mixin to
  5683. any class you create that can compare its instances.
  5684. You should implement the compare() method.
  5685. @extends Ember.Mixin
  5686. @since Ember 0.9
  5687. */
  5688. Ember.Comparable = Ember.Mixin.create( /** @scope Ember.Comparable.prototype */{
  5689. /**
  5690. walk like a duck. Indicates that the object can be compared.
  5691. @type Boolean
  5692. @default true
  5693. @constant
  5694. */
  5695. isComparable: true,
  5696. /**
  5697. Override to return the result of the comparison of the two parameters. The
  5698. compare method should return:
  5699. - `-1` if `a < b`
  5700. - `0` if `a == b`
  5701. - `1` if `a > b`
  5702. Default implementation raises an exception.
  5703. @param a {Object} the first object to compare
  5704. @param b {Object} the second object to compare
  5705. @returns {Integer} the result of the comparison
  5706. */
  5707. compare: Ember.required(Function)
  5708. });
  5709. })();
  5710. (function() {
  5711. // ==========================================================================
  5712. // Project: Ember Runtime
  5713. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  5714. // Portions ©2008-2010 Apple Inc. All rights reserved.
  5715. // License: Licensed under MIT license (see license.js)
  5716. // ==========================================================================
  5717. var get = Ember.get, set = Ember.set;
  5718. /**
  5719. @namespace
  5720. Implements some standard methods for copying an object. Add this mixin to
  5721. any object you create that can create a copy of itself. This mixin is
  5722. added automatically to the built-in array.
  5723. You should generally implement the copy() method to return a copy of the
  5724. receiver.
  5725. Note that frozenCopy() will only work if you also implement Ember.Freezable.
  5726. @extends Ember.Mixin
  5727. @since Ember 0.9
  5728. */
  5729. Ember.Copyable = Ember.Mixin.create(
  5730. /** @scope Ember.Copyable.prototype */ {
  5731. /**
  5732. Override to return a copy of the receiver. Default implementation raises
  5733. an exception.
  5734. @function
  5735. @param deep {Boolean} if true, a deep copy of the object should be made
  5736. @returns {Object} copy of receiver
  5737. */
  5738. copy: Ember.required(Function),
  5739. /**
  5740. If the object implements Ember.Freezable, then this will return a new copy
  5741. if the object is not frozen and the receiver if the object is frozen.
  5742. Raises an exception if you try to call this method on a object that does
  5743. not support freezing.
  5744. You should use this method whenever you want a copy of a freezable object
  5745. since a freezable object can simply return itself without actually
  5746. consuming more memory.
  5747. @returns {Object} copy of receiver or receiver
  5748. */
  5749. frozenCopy: function() {
  5750. if (Ember.Freezable && Ember.Freezable.detect(this)) {
  5751. return get(this, 'isFrozen') ? this : this.copy().freeze();
  5752. } else {
  5753. throw new Error(Ember.String.fmt("%@ does not support freezing", [this]));
  5754. }
  5755. }
  5756. });
  5757. })();
  5758. (function() {
  5759. // ==========================================================================
  5760. // Project: Ember Runtime
  5761. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  5762. // Portions ©2008-2010 Apple Inc. All rights reserved.
  5763. // License: Licensed under MIT license (see license.js)
  5764. // ==========================================================================
  5765. var get = Ember.get, set = Ember.set;
  5766. /**
  5767. @namespace
  5768. The Ember.Freezable mixin implements some basic methods for marking an object
  5769. as frozen. Once an object is frozen it should be read only. No changes
  5770. may be made the internal state of the object.
  5771. ## Enforcement
  5772. To fully support freezing in your subclass, you must include this mixin and
  5773. override any method that might alter any property on the object to instead
  5774. raise an exception. You can check the state of an object by checking the
  5775. isFrozen property.
  5776. Although future versions of JavaScript may support language-level freezing
  5777. object objects, that is not the case today. Even if an object is freezable,
  5778. it is still technically possible to modify the object, even though it could
  5779. break other parts of your application that do not expect a frozen object to
  5780. change. It is, therefore, very important that you always respect the
  5781. isFrozen property on all freezable objects.
  5782. ## Example Usage
  5783. The example below shows a simple object that implement the Ember.Freezable
  5784. protocol.
  5785. Contact = Ember.Object.extend(Ember.Freezable, {
  5786. firstName: null,
  5787. lastName: null,
  5788. // swaps the names
  5789. swapNames: function() {
  5790. if (this.get('isFrozen')) throw Ember.FROZEN_ERROR;
  5791. var tmp = this.get('firstName');
  5792. this.set('firstName', this.get('lastName'));
  5793. this.set('lastName', tmp);
  5794. return this;
  5795. }
  5796. });
  5797. c = Context.create({ firstName: "John", lastName: "Doe" });
  5798. c.swapNames(); => returns c
  5799. c.freeze();
  5800. c.swapNames(); => EXCEPTION
  5801. ## Copying
  5802. Usually the Ember.Freezable protocol is implemented in cooperation with the
  5803. Ember.Copyable protocol, which defines a frozenCopy() method that will return
  5804. a frozen object, if the object implements this method as well.
  5805. @extends Ember.Mixin
  5806. @since Ember 0.9
  5807. */
  5808. Ember.Freezable = Ember.Mixin.create(
  5809. /** @scope Ember.Freezable.prototype */ {
  5810. /**
  5811. Set to true when the object is frozen. Use this property to detect whether
  5812. your object is frozen or not.
  5813. @type Boolean
  5814. */
  5815. isFrozen: false,
  5816. /**
  5817. Freezes the object. Once this method has been called the object should
  5818. no longer allow any properties to be edited.
  5819. @returns {Object} receiver
  5820. */
  5821. freeze: function() {
  5822. if (get(this, 'isFrozen')) return this;
  5823. set(this, 'isFrozen', true);
  5824. return this;
  5825. }
  5826. });
  5827. Ember.FROZEN_ERROR = "Frozen object cannot be modified.";
  5828. })();
  5829. (function() {
  5830. // ==========================================================================
  5831. // Project: Ember Runtime
  5832. // Copyright: ©2011 Strobe Inc. and contributors.
  5833. // License: Licensed under MIT license (see license.js)
  5834. // ==========================================================================
  5835. var forEach = Ember.EnumerableUtils.forEach;
  5836. /**
  5837. @class
  5838. This mixin defines the API for modifying generic enumerables. These methods
  5839. can be applied to an object regardless of whether it is ordered or
  5840. unordered.
  5841. Note that an Enumerable can change even if it does not implement this mixin.
  5842. For example, a MappedEnumerable cannot be directly modified but if its
  5843. underlying enumerable changes, it will change also.
  5844. ## Adding Objects
  5845. To add an object to an enumerable, use the addObject() method. This
  5846. method will only add the object to the enumerable if the object is not
  5847. already present and the object if of a type supported by the enumerable.
  5848. set.addObject(contact);
  5849. ## Removing Objects
  5850. To remove an object form an enumerable, use the removeObject() method. This
  5851. will only remove the object if it is already in the enumerable, otherwise
  5852. this method has no effect.
  5853. set.removeObject(contact);
  5854. ## Implementing In Your Own Code
  5855. If you are implementing an object and want to support this API, just include
  5856. this mixin in your class and implement the required methods. In your unit
  5857. tests, be sure to apply the Ember.MutableEnumerableTests to your object.
  5858. @extends Ember.Mixin
  5859. @extends Ember.Enumerable
  5860. */
  5861. Ember.MutableEnumerable = Ember.Mixin.create(Ember.Enumerable,
  5862. /** @scope Ember.MutableEnumerable.prototype */ {
  5863. /**
  5864. __Required.__ You must implement this method to apply this mixin.
  5865. Attempts to add the passed object to the receiver if the object is not
  5866. already present in the collection. If the object is present, this method
  5867. has no effect.
  5868. If the passed object is of a type not supported by the receiver
  5869. then this method should raise an exception.
  5870. @function
  5871. @param {Object} object
  5872. The object to add to the enumerable.
  5873. @returns {Object} the passed object
  5874. */
  5875. addObject: Ember.required(Function),
  5876. /**
  5877. Adds each object in the passed enumerable to the receiver.
  5878. @param {Ember.Enumerable} objects the objects to add.
  5879. @returns {Object} receiver
  5880. */
  5881. addObjects: function(objects) {
  5882. Ember.beginPropertyChanges(this);
  5883. forEach(objects, function(obj) { this.addObject(obj); }, this);
  5884. Ember.endPropertyChanges(this);
  5885. return this;
  5886. },
  5887. /**
  5888. __Required.__ You must implement this method to apply this mixin.
  5889. Attempts to remove the passed object from the receiver collection if the
  5890. object is in present in the collection. If the object is not present,
  5891. this method has no effect.
  5892. If the passed object is of a type not supported by the receiver
  5893. then this method should raise an exception.
  5894. @function
  5895. @param {Object} object
  5896. The object to remove from the enumerable.
  5897. @returns {Object} the passed object
  5898. */
  5899. removeObject: Ember.required(Function),
  5900. /**
  5901. Removes each objects in the passed enumerable from the receiver.
  5902. @param {Ember.Enumerable} objects the objects to remove
  5903. @returns {Object} receiver
  5904. */
  5905. removeObjects: function(objects) {
  5906. Ember.beginPropertyChanges(this);
  5907. forEach(objects, function(obj) { this.removeObject(obj); }, this);
  5908. Ember.endPropertyChanges(this);
  5909. return this;
  5910. }
  5911. });
  5912. })();
  5913. (function() {
  5914. // ==========================================================================
  5915. // Project: Ember Runtime
  5916. // Copyright: ©2011 Strobe Inc. and contributors.
  5917. // License: Licensed under MIT license (see license.js)
  5918. // ==========================================================================
  5919. // ..........................................................
  5920. // CONSTANTS
  5921. //
  5922. var OUT_OF_RANGE_EXCEPTION = "Index out of range" ;
  5923. var EMPTY = [];
  5924. // ..........................................................
  5925. // HELPERS
  5926. //
  5927. var get = Ember.get, set = Ember.set, forEach = Ember.EnumerableUtils.forEach;
  5928. /**
  5929. @class
  5930. This mixin defines the API for modifying array-like objects. These methods
  5931. can be applied only to a collection that keeps its items in an ordered set.
  5932. Note that an Array can change even if it does not implement this mixin.
  5933. For example, one might implement a SparseArray that cannot be directly
  5934. modified, but if its underlying enumerable changes, it will change also.
  5935. @extends Ember.Mixin
  5936. @extends Ember.Array
  5937. @extends Ember.MutableEnumerable
  5938. */
  5939. Ember.MutableArray = Ember.Mixin.create(Ember.Array, Ember.MutableEnumerable,
  5940. /** @scope Ember.MutableArray.prototype */ {
  5941. /**
  5942. __Required.__ You must implement this method to apply this mixin.
  5943. This is one of the primitives you must implement to support Ember.Array. You
  5944. should replace amt objects started at idx with the objects in the passed
  5945. array. You should also call this.enumerableContentDidChange() ;
  5946. @function
  5947. @param {Number} idx
  5948. Starting index in the array to replace. If idx >= length, then append
  5949. to the end of the array.
  5950. @param {Number} amt
  5951. Number of elements that should be removed from the array, starting at
  5952. *idx*.
  5953. @param {Array} objects
  5954. An array of zero or more objects that should be inserted into the array
  5955. at *idx*
  5956. */
  5957. replace: Ember.required(),
  5958. /**
  5959. Remove all elements from self. This is useful if you
  5960. want to reuse an existing array without having to recreate it.
  5961. var colors = ["red", "green", "blue"];
  5962. color.length(); => 3
  5963. colors.clear(); => []
  5964. colors.length(); => 0
  5965. @returns {Ember.Array} An empty Array.
  5966. */
  5967. clear: function () {
  5968. var len = get(this, 'length');
  5969. if (len === 0) return this;
  5970. this.replace(0, len, EMPTY);
  5971. return this;
  5972. },
  5973. /**
  5974. This will use the primitive replace() method to insert an object at the
  5975. specified index.
  5976. var colors = ["red", "green", "blue"];
  5977. colors.insertAt(2, "yellow"); => ["red", "green", "yellow", "blue"]
  5978. colors.insertAt(5, "orange"); => Error: Index out of range
  5979. @param {Number} idx index of insert the object at.
  5980. @param {Object} object object to insert
  5981. */
  5982. insertAt: function(idx, object) {
  5983. if (idx > get(this, 'length')) throw new Error(OUT_OF_RANGE_EXCEPTION) ;
  5984. this.replace(idx, 0, [object]) ;
  5985. return this ;
  5986. },
  5987. /**
  5988. Remove an object at the specified index using the replace() primitive
  5989. method. You can pass either a single index, or a start and a length.
  5990. If you pass a start and length that is beyond the
  5991. length this method will throw an Ember.OUT_OF_RANGE_EXCEPTION
  5992. var colors = ["red", "green", "blue", "yellow", "orange"];
  5993. colors.removeAt(0); => ["green", "blue", "yellow", "orange"]
  5994. colors.removeAt(2, 2); => ["green", "blue"]
  5995. colors.removeAt(4, 2); => Error: Index out of range
  5996. @param {Number} start index, start of range
  5997. @param {Number} len length of passing range
  5998. @returns {Object} receiver
  5999. */
  6000. removeAt: function(start, len) {
  6001. var delta = 0;
  6002. if ('number' === typeof start) {
  6003. if ((start < 0) || (start >= get(this, 'length'))) {
  6004. throw new Error(OUT_OF_RANGE_EXCEPTION);
  6005. }
  6006. // fast case
  6007. if (len === undefined) len = 1;
  6008. this.replace(start, len, EMPTY);
  6009. }
  6010. return this ;
  6011. },
  6012. /**
  6013. Push the object onto the end of the array. Works just like push() but it
  6014. is KVO-compliant.
  6015. var colors = ["red", "green", "blue"];
  6016. colors.pushObject("black"); => ["red", "green", "blue", "black"]
  6017. colors.pushObject(["yellow", "orange"]); => ["red", "green", "blue", "black", ["yellow", "orange"]]
  6018. */
  6019. pushObject: function(obj) {
  6020. this.insertAt(get(this, 'length'), obj) ;
  6021. return obj ;
  6022. },
  6023. /**
  6024. Add the objects in the passed numerable to the end of the array. Defers
  6025. notifying observers of the change until all objects are added.
  6026. var colors = ["red", "green", "blue"];
  6027. colors.pushObjects("black"); => ["red", "green", "blue", "black"]
  6028. colors.pushObjects(["yellow", "orange"]); => ["red", "green", "blue", "black", "yellow", "orange"]
  6029. @param {Ember.Enumerable} objects the objects to add
  6030. @returns {Ember.Array} receiver
  6031. */
  6032. pushObjects: function(objects) {
  6033. this.replace(get(this, 'length'), 0, objects);
  6034. return this;
  6035. },
  6036. /**
  6037. Pop object from array or nil if none are left. Works just like pop() but
  6038. it is KVO-compliant.
  6039. var colors = ["red", "green", "blue"];
  6040. colors.popObject(); => "blue"
  6041. console.log(colors); => ["red", "green"]
  6042. */
  6043. popObject: function() {
  6044. var len = get(this, 'length') ;
  6045. if (len === 0) return null ;
  6046. var ret = this.objectAt(len-1) ;
  6047. this.removeAt(len-1, 1) ;
  6048. return ret ;
  6049. },
  6050. /**
  6051. Shift an object from start of array or nil if none are left. Works just
  6052. like shift() but it is KVO-compliant.
  6053. var colors = ["red", "green", "blue"];
  6054. colors.shiftObject(); => "red"
  6055. console.log(colors); => ["green", "blue"]
  6056. */
  6057. shiftObject: function() {
  6058. if (get(this, 'length') === 0) return null ;
  6059. var ret = this.objectAt(0) ;
  6060. this.removeAt(0) ;
  6061. return ret ;
  6062. },
  6063. /**
  6064. Unshift an object to start of array. Works just like unshift() but it is
  6065. KVO-compliant.
  6066. var colors = ["red", "green", "blue"];
  6067. colors.unshiftObject("yellow"); => ["yellow", "red", "green", "blue"]
  6068. colors.unshiftObject(["black", "white"]); => [["black", "white"], "yellow", "red", "green", "blue"]
  6069. */
  6070. unshiftObject: function(obj) {
  6071. this.insertAt(0, obj) ;
  6072. return obj ;
  6073. },
  6074. /**
  6075. Adds the named objects to the beginning of the array. Defers notifying
  6076. observers until all objects have been added.
  6077. var colors = ["red", "green", "blue"];
  6078. colors.unshiftObjects(["black", "white"]); => ["black", "white", "red", "green", "blue"]
  6079. colors.unshiftObjects("yellow"); => Type Error: 'undefined' is not a function
  6080. @param {Ember.Enumerable} objects the objects to add
  6081. @returns {Ember.Array} receiver
  6082. */
  6083. unshiftObjects: function(objects) {
  6084. this.replace(0, 0, objects);
  6085. return this;
  6086. },
  6087. /**
  6088. Reverse objects in the array. Works just like reverse() but it is
  6089. KVO-compliant.
  6090. @return {Ember.Array} receiver
  6091. */
  6092. reverseObjects: function() {
  6093. var len = get(this, 'length');
  6094. if (len === 0) return this;
  6095. var objects = this.toArray().reverse();
  6096. this.replace(0, len, objects);
  6097. return this;
  6098. },
  6099. // ..........................................................
  6100. // IMPLEMENT Ember.MutableEnumerable
  6101. //
  6102. /** @private (nodoc) */
  6103. removeObject: function(obj) {
  6104. var loc = get(this, 'length') || 0;
  6105. while(--loc >= 0) {
  6106. var curObject = this.objectAt(loc) ;
  6107. if (curObject === obj) this.removeAt(loc) ;
  6108. }
  6109. return this ;
  6110. },
  6111. /** @private (nodoc) */
  6112. addObject: function(obj) {
  6113. if (!this.contains(obj)) this.pushObject(obj);
  6114. return this ;
  6115. }
  6116. });
  6117. })();
  6118. (function() {
  6119. // ==========================================================================
  6120. // Project: Ember Runtime
  6121. // Copyright: ©2011 Strobe Inc. and contributors.
  6122. // License: Licensed under MIT license (see license.js)
  6123. // ==========================================================================
  6124. var get = Ember.get, set = Ember.set, defineProperty = Ember.defineProperty;
  6125. /**
  6126. @class
  6127. ## Overview
  6128. This mixin provides properties and property observing functionality, core
  6129. features of the Ember object model.
  6130. Properties and observers allow one object to observe changes to a
  6131. property on another object. This is one of the fundamental ways that
  6132. models, controllers and views communicate with each other in an Ember
  6133. application.
  6134. Any object that has this mixin applied can be used in observer
  6135. operations. That includes Ember.Object and most objects you will
  6136. interact with as you write your Ember application.
  6137. Note that you will not generally apply this mixin to classes yourself,
  6138. but you will use the features provided by this module frequently, so it
  6139. is important to understand how to use it.
  6140. ## Using get() and set()
  6141. Because of Ember's support for bindings and observers, you will always
  6142. access properties using the get method, and set properties using the
  6143. set method. This allows the observing objects to be notified and
  6144. computed properties to be handled properly.
  6145. More documentation about `get` and `set` are below.
  6146. ## Observing Property Changes
  6147. You typically observe property changes simply by adding the `observes`
  6148. call to the end of your method declarations in classes that you write.
  6149. For example:
  6150. Ember.Object.create({
  6151. valueObserver: function() {
  6152. // Executes whenever the "value" property changes
  6153. }.observes('value')
  6154. });
  6155. Although this is the most common way to add an observer, this capability
  6156. is actually built into the Ember.Object class on top of two methods
  6157. defined in this mixin: `addObserver` and `removeObserver`. You can use
  6158. these two methods to add and remove observers yourself if you need to
  6159. do so at runtime.
  6160. To add an observer for a property, call:
  6161. object.addObserver('propertyKey', targetObject, targetAction)
  6162. This will call the `targetAction` method on the `targetObject` to be called
  6163. whenever the value of the `propertyKey` changes.
  6164. Note that if `propertyKey` is a computed property, the observer will be
  6165. called when any of the property dependencies are changed, even if the
  6166. resulting value of the computed property is unchanged. This is necessary
  6167. because computed properties are not computed until `get` is called.
  6168. @extends Ember.Mixin
  6169. */
  6170. Ember.Observable = Ember.Mixin.create(/** @scope Ember.Observable.prototype */ {
  6171. /** @private - compatibility */
  6172. isObserverable: true,
  6173. /**
  6174. Retrieves the value of a property from the object.
  6175. This method is usually similar to using object[keyName] or object.keyName,
  6176. however it supports both computed properties and the unknownProperty
  6177. handler.
  6178. Because `get` unifies the syntax for accessing all these kinds
  6179. of properties, it can make many refactorings easier, such as replacing a
  6180. simple property with a computed property, or vice versa.
  6181. ### Computed Properties
  6182. Computed properties are methods defined with the `property` modifier
  6183. declared at the end, such as:
  6184. fullName: function() {
  6185. return this.getEach('firstName', 'lastName').compact().join(' ');
  6186. }.property('firstName', 'lastName')
  6187. When you call `get` on a computed property, the function will be
  6188. called and the return value will be returned instead of the function
  6189. itself.
  6190. ### Unknown Properties
  6191. Likewise, if you try to call `get` on a property whose value is
  6192. undefined, the unknownProperty() method will be called on the object.
  6193. If this method returns any value other than undefined, it will be returned
  6194. instead. This allows you to implement "virtual" properties that are
  6195. not defined upfront.
  6196. @param {String} key The property to retrieve
  6197. @returns {Object} The property value or undefined.
  6198. */
  6199. get: function(keyName) {
  6200. return get(this, keyName);
  6201. },
  6202. /**
  6203. To get multiple properties at once, call getProperties
  6204. with a list of strings or an array:
  6205. record.getProperties('firstName', 'lastName', 'zipCode'); // => { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
  6206. is equivalent to:
  6207. record.getProperties(['firstName', 'lastName', 'zipCode']); // => { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
  6208. @param {String...|Array} list of keys to get
  6209. @returns {Hash}
  6210. */
  6211. getProperties: function() {
  6212. var ret = {};
  6213. var propertyNames = arguments;
  6214. if (arguments.length === 1 && Ember.typeOf(arguments[0]) === 'array') {
  6215. propertyNames = arguments[0];
  6216. }
  6217. for(var i = 0; i < propertyNames.length; i++) {
  6218. ret[propertyNames[i]] = get(this, propertyNames[i]);
  6219. }
  6220. return ret;
  6221. },
  6222. /**
  6223. Sets the provided key or path to the value.
  6224. This method is generally very similar to calling object[key] = value or
  6225. object.key = value, except that it provides support for computed
  6226. properties, the unknownProperty() method and property observers.
  6227. ### Computed Properties
  6228. If you try to set a value on a key that has a computed property handler
  6229. defined (see the get() method for an example), then set() will call
  6230. that method, passing both the value and key instead of simply changing
  6231. the value itself. This is useful for those times when you need to
  6232. implement a property that is composed of one or more member
  6233. properties.
  6234. ### Unknown Properties
  6235. If you try to set a value on a key that is undefined in the target
  6236. object, then the unknownProperty() handler will be called instead. This
  6237. gives you an opportunity to implement complex "virtual" properties that
  6238. are not predefined on the object. If unknownProperty() returns
  6239. undefined, then set() will simply set the value on the object.
  6240. ### Property Observers
  6241. In addition to changing the property, set() will also register a
  6242. property change with the object. Unless you have placed this call
  6243. inside of a beginPropertyChanges() and endPropertyChanges(), any "local"
  6244. observers (i.e. observer methods declared on the same object), will be
  6245. called immediately. Any "remote" observers (i.e. observer methods
  6246. declared on another object) will be placed in a queue and called at a
  6247. later time in a coalesced manner.
  6248. ### Chaining
  6249. In addition to property changes, set() returns the value of the object
  6250. itself so you can do chaining like this:
  6251. record.set('firstName', 'Charles').set('lastName', 'Jolley');
  6252. @param {String} key The property to set
  6253. @param {Object} value The value to set or null.
  6254. @returns {Ember.Observable}
  6255. */
  6256. set: function(keyName, value) {
  6257. set(this, keyName, value);
  6258. return this;
  6259. },
  6260. /**
  6261. To set multiple properties at once, call setProperties
  6262. with a Hash:
  6263. record.setProperties({ firstName: 'Charles', lastName: 'Jolley' });
  6264. @param {Hash} hash the hash of keys and values to set
  6265. @returns {Ember.Observable}
  6266. */
  6267. setProperties: function(hash) {
  6268. return Ember.setProperties(this, hash);
  6269. },
  6270. /**
  6271. Begins a grouping of property changes.
  6272. You can use this method to group property changes so that notifications
  6273. will not be sent until the changes are finished. If you plan to make a
  6274. large number of changes to an object at one time, you should call this
  6275. method at the beginning of the changes to begin deferring change
  6276. notifications. When you are done making changes, call endPropertyChanges()
  6277. to deliver the deferred change notifications and end deferring.
  6278. @returns {Ember.Observable}
  6279. */
  6280. beginPropertyChanges: function() {
  6281. Ember.beginPropertyChanges();
  6282. return this;
  6283. },
  6284. /**
  6285. Ends a grouping of property changes.
  6286. You can use this method to group property changes so that notifications
  6287. will not be sent until the changes are finished. If you plan to make a
  6288. large number of changes to an object at one time, you should call
  6289. beginPropertyChanges() at the beginning of the changes to defer change
  6290. notifications. When you are done making changes, call this method to
  6291. deliver the deferred change notifications and end deferring.
  6292. @returns {Ember.Observable}
  6293. */
  6294. endPropertyChanges: function() {
  6295. Ember.endPropertyChanges();
  6296. return this;
  6297. },
  6298. /**
  6299. Notify the observer system that a property is about to change.
  6300. Sometimes you need to change a value directly or indirectly without
  6301. actually calling get() or set() on it. In this case, you can use this
  6302. method and propertyDidChange() instead. Calling these two methods
  6303. together will notify all observers that the property has potentially
  6304. changed value.
  6305. Note that you must always call propertyWillChange and propertyDidChange as
  6306. a pair. If you do not, it may get the property change groups out of order
  6307. and cause notifications to be delivered more often than you would like.
  6308. @param {String} key The property key that is about to change.
  6309. @returns {Ember.Observable}
  6310. */
  6311. propertyWillChange: function(keyName){
  6312. Ember.propertyWillChange(this, keyName);
  6313. return this;
  6314. },
  6315. /**
  6316. Notify the observer system that a property has just changed.
  6317. Sometimes you need to change a value directly or indirectly without
  6318. actually calling get() or set() on it. In this case, you can use this
  6319. method and propertyWillChange() instead. Calling these two methods
  6320. together will notify all observers that the property has potentially
  6321. changed value.
  6322. Note that you must always call propertyWillChange and propertyDidChange as
  6323. a pair. If you do not, it may get the property change groups out of order
  6324. and cause notifications to be delivered more often than you would like.
  6325. @param {String} keyName The property key that has just changed.
  6326. @returns {Ember.Observable}
  6327. */
  6328. propertyDidChange: function(keyName) {
  6329. Ember.propertyDidChange(this, keyName);
  6330. return this;
  6331. },
  6332. /**
  6333. Convenience method to call `propertyWillChange` and `propertyDidChange` in
  6334. succession.
  6335. @param {String} keyName The property key to be notified about.
  6336. @returns {Ember.Observable}
  6337. */
  6338. notifyPropertyChange: function(keyName) {
  6339. this.propertyWillChange(keyName);
  6340. this.propertyDidChange(keyName);
  6341. return this;
  6342. },
  6343. addBeforeObserver: function(key, target, method) {
  6344. Ember.addBeforeObserver(this, key, target, method);
  6345. },
  6346. /**
  6347. Adds an observer on a property.
  6348. This is the core method used to register an observer for a property.
  6349. Once you call this method, anytime the key's value is set, your observer
  6350. will be notified. Note that the observers are triggered anytime the
  6351. value is set, regardless of whether it has actually changed. Your
  6352. observer should be prepared to handle that.
  6353. You can also pass an optional context parameter to this method. The
  6354. context will be passed to your observer method whenever it is triggered.
  6355. Note that if you add the same target/method pair on a key multiple times
  6356. with different context parameters, your observer will only be called once
  6357. with the last context you passed.
  6358. ### Observer Methods
  6359. Observer methods you pass should generally have the following signature if
  6360. you do not pass a "context" parameter:
  6361. fooDidChange: function(sender, key, value, rev);
  6362. The sender is the object that changed. The key is the property that
  6363. changes. The value property is currently reserved and unused. The rev
  6364. is the last property revision of the object when it changed, which you can
  6365. use to detect if the key value has really changed or not.
  6366. If you pass a "context" parameter, the context will be passed before the
  6367. revision like so:
  6368. fooDidChange: function(sender, key, value, context, rev);
  6369. Usually you will not need the value, context or revision parameters at
  6370. the end. In this case, it is common to write observer methods that take
  6371. only a sender and key value as parameters or, if you aren't interested in
  6372. any of these values, to write an observer that has no parameters at all.
  6373. @param {String} key The key to observer
  6374. @param {Object} target The target object to invoke
  6375. @param {String|Function} method The method to invoke.
  6376. @returns {Ember.Object} self
  6377. */
  6378. addObserver: function(key, target, method) {
  6379. Ember.addObserver(this, key, target, method);
  6380. },
  6381. /**
  6382. Remove an observer you have previously registered on this object. Pass
  6383. the same key, target, and method you passed to addObserver() and your
  6384. target will no longer receive notifications.
  6385. @param {String} key The key to observer
  6386. @param {Object} target The target object to invoke
  6387. @param {String|Function} method The method to invoke.
  6388. @returns {Ember.Observable} receiver
  6389. */
  6390. removeObserver: function(key, target, method) {
  6391. Ember.removeObserver(this, key, target, method);
  6392. },
  6393. /**
  6394. Returns true if the object currently has observers registered for a
  6395. particular key. You can use this method to potentially defer performing
  6396. an expensive action until someone begins observing a particular property
  6397. on the object.
  6398. @param {String} key Key to check
  6399. @returns {Boolean}
  6400. */
  6401. hasObserverFor: function(key) {
  6402. return Ember.hasListeners(this, key+':change');
  6403. },
  6404. /**
  6405. This method will be called when a client attempts to get the value of a
  6406. property that has not been defined in one of the typical ways. Override
  6407. this method to create "virtual" properties.
  6408. @param {String} key The name of the unknown property that was requested.
  6409. @returns {Object} The property value or undefined. Default is undefined.
  6410. */
  6411. unknownProperty: function(key) {
  6412. return undefined;
  6413. },
  6414. /**
  6415. This method will be called when a client attempts to set the value of a
  6416. property that has not been defined in one of the typical ways. Override
  6417. this method to create "virtual" properties.
  6418. @param {String} key The name of the unknown property to be set.
  6419. @param {Object} value The value the unknown property is to be set to.
  6420. */
  6421. setUnknownProperty: function(key, value) {
  6422. defineProperty(this, key);
  6423. set(this, key, value);
  6424. },
  6425. /**
  6426. @deprecated
  6427. @param {String} path The property path to retrieve
  6428. @returns {Object} The property value or undefined.
  6429. */
  6430. getPath: function(path) {
  6431. Ember.deprecate("getPath is deprecated since get now supports paths");
  6432. return this.get(path);
  6433. },
  6434. /**
  6435. @deprecated
  6436. @param {String} path The path to the property that will be set
  6437. @param {Object} value The value to set or null.
  6438. @returns {Ember.Observable}
  6439. */
  6440. setPath: function(path, value) {
  6441. Ember.deprecate("setPath is deprecated since set now supports paths");
  6442. return this.set(path, value);
  6443. },
  6444. /**
  6445. Retrieves the value of a property, or a default value in the case that the property
  6446. returns undefined.
  6447. person.getWithDefault('lastName', 'Doe');
  6448. @param {String} keyName The name of the property to retrieve
  6449. @param {Object} defaultValue The value to return if the property value is undefined
  6450. @returns {Object} The property value or the defaultValue.
  6451. */
  6452. getWithDefault: function(keyName, defaultValue) {
  6453. return Ember.getWithDefault(this, keyName, defaultValue);
  6454. },
  6455. /**
  6456. Set the value of a property to the current value plus some amount.
  6457. person.incrementProperty('age');
  6458. team.incrementProperty('score', 2);
  6459. @param {String} keyName The name of the property to increment
  6460. @param {Object} increment The amount to increment by. Defaults to 1
  6461. @returns {Object} The new property value
  6462. */
  6463. incrementProperty: function(keyName, increment) {
  6464. if (!increment) { increment = 1; }
  6465. set(this, keyName, (get(this, keyName) || 0)+increment);
  6466. return get(this, keyName);
  6467. },
  6468. /**
  6469. Set the value of a property to the current value minus some amount.
  6470. player.decrementProperty('lives');
  6471. orc.decrementProperty('health', 5);
  6472. @param {String} keyName The name of the property to decrement
  6473. @param {Object} increment The amount to decrement by. Defaults to 1
  6474. @returns {Object} The new property value
  6475. */
  6476. decrementProperty: function(keyName, increment) {
  6477. if (!increment) { increment = 1; }
  6478. set(this, keyName, (get(this, keyName) || 0)-increment);
  6479. return get(this, keyName);
  6480. },
  6481. /**
  6482. Set the value of a boolean property to the opposite of it's
  6483. current value.
  6484. starship.toggleProperty('warpDriveEnaged');
  6485. @param {String} keyName The name of the property to toggle
  6486. @returns {Object} The new property value
  6487. */
  6488. toggleProperty: function(keyName) {
  6489. set(this, keyName, !get(this, keyName));
  6490. return get(this, keyName);
  6491. },
  6492. /**
  6493. Returns the cached value of a computed property, if it exists.
  6494. This allows you to inspect the value of a computed property
  6495. without accidentally invoking it if it is intended to be
  6496. generated lazily.
  6497. @param {String} keyName
  6498. @returns {Object} The cached value of the computed property, if any
  6499. */
  6500. cacheFor: function(keyName) {
  6501. return Ember.cacheFor(this, keyName);
  6502. },
  6503. /** @private - intended for debugging purposes */
  6504. observersForKey: function(keyName) {
  6505. return Ember.observersFor(this, keyName);
  6506. }
  6507. });
  6508. })();
  6509. (function() {
  6510. var get = Ember.get, set = Ember.set;
  6511. Ember.TargetActionSupport = Ember.Mixin.create({
  6512. target: null,
  6513. action: null,
  6514. targetObject: Ember.computed(function() {
  6515. var target = get(this, 'target');
  6516. if (Ember.typeOf(target) === "string") {
  6517. var value = get(this, target);
  6518. if (value === undefined) { value = get(window, target); }
  6519. return value;
  6520. } else {
  6521. return target;
  6522. }
  6523. }).property('target').cacheable(),
  6524. triggerAction: function() {
  6525. var action = get(this, 'action'),
  6526. target = get(this, 'targetObject');
  6527. if (target && action) {
  6528. var ret;
  6529. if (typeof target.send === 'function') {
  6530. ret = target.send(action, this);
  6531. } else {
  6532. if (typeof action === 'string') {
  6533. action = target[action];
  6534. }
  6535. ret = action.call(target, this);
  6536. }
  6537. if (ret !== false) ret = true;
  6538. return ret;
  6539. } else {
  6540. return false;
  6541. }
  6542. }
  6543. });
  6544. })();
  6545. (function() {
  6546. /**
  6547. @class
  6548. @extends Ember.Mixin
  6549. */
  6550. Ember.Evented = Ember.Mixin.create(
  6551. /** @scope Ember.Evented.prototype */ {
  6552. on: function(name, target, method) {
  6553. Ember.addListener(this, name, target, method);
  6554. },
  6555. one: function(name, target, method) {
  6556. if (!method) {
  6557. method = target;
  6558. target = null;
  6559. }
  6560. var self = this;
  6561. var wrapped = function() {
  6562. Ember.removeListener(self, name, target, wrapped);
  6563. if ('string' === typeof method) { method = this[method]; }
  6564. // Internally, a `null` target means that the target is
  6565. // the first parameter to addListener. That means that
  6566. // the `this` passed into this function is the target
  6567. // determined by the event system.
  6568. method.apply(this, arguments);
  6569. };
  6570. this.on(name, target, wrapped);
  6571. },
  6572. trigger: function(name) {
  6573. var args = [], i, l;
  6574. for (i = 1, l = arguments.length; i < l; i++) {
  6575. args.push(arguments[i]);
  6576. }
  6577. Ember.sendEvent(this, name, args);
  6578. },
  6579. fire: function(name) {
  6580. Ember.deprecate("Ember.Evented#fire() has been deprecated in favor of trigger() for compatibility with jQuery. It will be removed in 1.0. Please update your code to call trigger() instead.");
  6581. this.trigger.apply(this, arguments);
  6582. },
  6583. off: function(name, target, method) {
  6584. Ember.removeListener(this, name, target, method);
  6585. },
  6586. has: function(name) {
  6587. return Ember.hasListeners(this, name);
  6588. }
  6589. });
  6590. })();
  6591. (function() {
  6592. // ==========================================================================
  6593. // Project: Ember Runtime
  6594. // Copyright: ©2011 Strobe Inc. and contributors.
  6595. // License: Licensed under MIT license (see license.js)
  6596. // ==========================================================================
  6597. })();
  6598. (function() {
  6599. // ==========================================================================
  6600. // Project: Ember Runtime
  6601. // Copyright: ©2011 Strobe Inc. and contributors.
  6602. // License: Licensed under MIT license (see license.js)
  6603. // ==========================================================================
  6604. // NOTE: this object should never be included directly. Instead use Ember.
  6605. // Ember.Object. We only define this separately so that Ember.Set can depend on it
  6606. var classToString = Ember.Mixin.prototype.toString;
  6607. var set = Ember.set, get = Ember.get;
  6608. var o_create = Ember.create,
  6609. o_defineProperty = Ember.platform.defineProperty,
  6610. a_slice = Array.prototype.slice,
  6611. meta = Ember.meta,
  6612. rewatch = Ember.rewatch,
  6613. finishChains = Ember.finishChains,
  6614. finishPartial = Ember.Mixin.finishPartial,
  6615. reopen = Ember.Mixin.prototype.reopen;
  6616. var undefinedDescriptor = {
  6617. configurable: true,
  6618. writable: true,
  6619. enumerable: false,
  6620. value: undefined
  6621. };
  6622. /** @private */
  6623. function makeCtor() {
  6624. // Note: avoid accessing any properties on the object since it makes the
  6625. // method a lot faster. This is glue code so we want it to be as fast as
  6626. // possible.
  6627. var wasApplied = false, initMixins;
  6628. var Class = function() {
  6629. if (!wasApplied) {
  6630. Class.proto(); // prepare prototype...
  6631. }
  6632. var m = Ember.meta(this);
  6633. m.proto = this;
  6634. if (initMixins) {
  6635. this.reopen.apply(this, initMixins);
  6636. initMixins = null;
  6637. }
  6638. o_defineProperty(this, Ember.GUID_KEY, undefinedDescriptor);
  6639. o_defineProperty(this, '_super', undefinedDescriptor);
  6640. finishPartial(this, m);
  6641. delete m.proto;
  6642. finishChains(this);
  6643. this.init.apply(this, arguments);
  6644. };
  6645. Class.toString = classToString;
  6646. Class.willReopen = function() {
  6647. if (wasApplied) {
  6648. Class.PrototypeMixin = Ember.Mixin.create(Class.PrototypeMixin);
  6649. }
  6650. wasApplied = false;
  6651. };
  6652. Class._initMixins = function(args) { initMixins = args; };
  6653. Class.proto = function() {
  6654. var superclass = Class.superclass;
  6655. if (superclass) { superclass.proto(); }
  6656. if (!wasApplied) {
  6657. wasApplied = true;
  6658. Class.PrototypeMixin.applyPartial(Class.prototype);
  6659. rewatch(Class.prototype);
  6660. }
  6661. return this.prototype;
  6662. };
  6663. return Class;
  6664. }
  6665. var CoreObject = makeCtor();
  6666. CoreObject.PrototypeMixin = Ember.Mixin.create(
  6667. /** @scope Ember.CoreObject.prototype */ {
  6668. reopen: function() {
  6669. Ember.Mixin._apply(this, arguments, true);
  6670. return this;
  6671. },
  6672. isInstance: true,
  6673. /** @private */
  6674. init: function() {},
  6675. /** @field */
  6676. isDestroyed: false,
  6677. /** @field */
  6678. isDestroying: false,
  6679. /**
  6680. Destroys an object by setting the isDestroyed flag and removing its
  6681. metadata, which effectively destroys observers and bindings.
  6682. If you try to set a property on a destroyed object, an exception will be
  6683. raised.
  6684. Note that destruction is scheduled for the end of the run loop and does not
  6685. happen immediately.
  6686. @returns {Ember.Object} receiver
  6687. */
  6688. destroy: function() {
  6689. if (this.isDestroying) { return; }
  6690. this.isDestroying = true;
  6691. if (this.willDestroy) { this.willDestroy(); }
  6692. set(this, 'isDestroyed', true);
  6693. Ember.run.schedule('destroy', this, this._scheduledDestroy);
  6694. return this;
  6695. },
  6696. /**
  6697. Invoked by the run loop to actually destroy the object. This is
  6698. scheduled for execution by the `destroy` method.
  6699. @private
  6700. */
  6701. _scheduledDestroy: function() {
  6702. Ember.destroy(this);
  6703. if (this.didDestroy) { this.didDestroy(); }
  6704. },
  6705. bind: function(to, from) {
  6706. if (!(from instanceof Ember.Binding)) { from = Ember.Binding.from(from); }
  6707. from.to(to).connect(this);
  6708. return from;
  6709. },
  6710. toString: function() {
  6711. return '<'+this.constructor.toString()+':'+Ember.guidFor(this)+'>';
  6712. }
  6713. });
  6714. if (Ember.config.overridePrototypeMixin) {
  6715. Ember.config.overridePrototypeMixin(CoreObject.PrototypeMixin);
  6716. }
  6717. CoreObject.__super__ = null;
  6718. var ClassMixin = Ember.Mixin.create(
  6719. /** @scope Ember.ClassMixin.prototype */ {
  6720. ClassMixin: Ember.required(),
  6721. PrototypeMixin: Ember.required(),
  6722. isClass: true,
  6723. isMethod: false,
  6724. extend: function() {
  6725. var Class = makeCtor(), proto;
  6726. Class.ClassMixin = Ember.Mixin.create(this.ClassMixin);
  6727. Class.PrototypeMixin = Ember.Mixin.create(this.PrototypeMixin);
  6728. Class.ClassMixin.ownerConstructor = Class;
  6729. Class.PrototypeMixin.ownerConstructor = Class;
  6730. reopen.apply(Class.PrototypeMixin, arguments);
  6731. Class.superclass = this;
  6732. Class.__super__ = this.prototype;
  6733. proto = Class.prototype = o_create(this.prototype);
  6734. proto.constructor = Class;
  6735. Ember.generateGuid(proto, 'ember');
  6736. meta(proto).proto = proto; // this will disable observers on prototype
  6737. Class.ClassMixin.apply(Class);
  6738. return Class;
  6739. },
  6740. create: function() {
  6741. var C = this;
  6742. if (arguments.length>0) { this._initMixins(arguments); }
  6743. return new C();
  6744. },
  6745. reopen: function() {
  6746. this.willReopen();
  6747. reopen.apply(this.PrototypeMixin, arguments);
  6748. return this;
  6749. },
  6750. reopenClass: function() {
  6751. reopen.apply(this.ClassMixin, arguments);
  6752. Ember.Mixin._apply(this, arguments, false);
  6753. return this;
  6754. },
  6755. detect: function(obj) {
  6756. if ('function' !== typeof obj) { return false; }
  6757. while(obj) {
  6758. if (obj===this) { return true; }
  6759. obj = obj.superclass;
  6760. }
  6761. return false;
  6762. },
  6763. detectInstance: function(obj) {
  6764. return obj instanceof this;
  6765. },
  6766. /**
  6767. In some cases, you may want to annotate computed properties with additional
  6768. metadata about how they function or what values they operate on. For example,
  6769. computed property functions may close over variables that are then no longer
  6770. available for introspection.
  6771. You can pass a hash of these values to a computed property like this:
  6772. person: function() {
  6773. var personId = this.get('personId');
  6774. return App.Person.create({ id: personId });
  6775. }.property().meta({ type: App.Person })
  6776. Once you've done this, you can retrieve the values saved to the computed
  6777. property from your class like this:
  6778. MyClass.metaForProperty('person');
  6779. This will return the original hash that was passed to `meta()`.
  6780. */
  6781. metaForProperty: function(key) {
  6782. var desc = meta(this.proto(), false).descs[key];
  6783. Ember.assert("metaForProperty() could not find a computed property with key '"+key+"'.", !!desc && desc instanceof Ember.ComputedProperty);
  6784. return desc._meta || {};
  6785. },
  6786. /**
  6787. Iterate over each computed property for the class, passing its name
  6788. and any associated metadata (see `metaForProperty`) to the callback.
  6789. */
  6790. eachComputedProperty: function(callback, binding) {
  6791. var proto = this.proto(),
  6792. descs = meta(proto).descs,
  6793. empty = {},
  6794. property;
  6795. for (var name in descs) {
  6796. property = descs[name];
  6797. if (property instanceof Ember.ComputedProperty) {
  6798. callback.call(binding || this, name, property._meta || empty);
  6799. }
  6800. }
  6801. }
  6802. });
  6803. if (Ember.config.overrideClassMixin) {
  6804. Ember.config.overrideClassMixin(ClassMixin);
  6805. }
  6806. CoreObject.ClassMixin = ClassMixin;
  6807. ClassMixin.apply(CoreObject);
  6808. /**
  6809. @class
  6810. */
  6811. Ember.CoreObject = CoreObject;
  6812. })();
  6813. (function() {
  6814. // ==========================================================================
  6815. // Project: Ember Runtime
  6816. // Copyright: ©2011 Strobe Inc. and contributors.
  6817. // License: Licensed under MIT license (see license.js)
  6818. // ==========================================================================
  6819. var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor, none = Ember.none;
  6820. /**
  6821. @class
  6822. An unordered collection of objects.
  6823. A Set works a bit like an array except that its items are not ordered.
  6824. You can create a set to efficiently test for membership for an object. You
  6825. can also iterate through a set just like an array, even accessing objects
  6826. by index, however there is no guarantee as to their order.
  6827. All Sets are observable via the Enumerable Observer API - which works
  6828. on any enumerable object including both Sets and Arrays.
  6829. ## Creating a Set
  6830. You can create a set like you would most objects using
  6831. `new Ember.Set()`. Most new sets you create will be empty, but you can
  6832. also initialize the set with some content by passing an array or other
  6833. enumerable of objects to the constructor.
  6834. Finally, you can pass in an existing set and the set will be copied. You
  6835. can also create a copy of a set by calling `Ember.Set#copy()`.
  6836. #js
  6837. // creates a new empty set
  6838. var foundNames = new Ember.Set();
  6839. // creates a set with four names in it.
  6840. var names = new Ember.Set(["Charles", "Tom", "Juan", "Alex"]); // :P
  6841. // creates a copy of the names set.
  6842. var namesCopy = new Ember.Set(names);
  6843. // same as above.
  6844. var anotherNamesCopy = names.copy();
  6845. ## Adding/Removing Objects
  6846. You generally add or remove objects from a set using `add()` or
  6847. `remove()`. You can add any type of object including primitives such as
  6848. numbers, strings, and booleans.
  6849. Unlike arrays, objects can only exist one time in a set. If you call `add()`
  6850. on a set with the same object multiple times, the object will only be added
  6851. once. Likewise, calling `remove()` with the same object multiple times will
  6852. remove the object the first time and have no effect on future calls until
  6853. you add the object to the set again.
  6854. NOTE: You cannot add/remove null or undefined to a set. Any attempt to do so
  6855. will be ignored.
  6856. In addition to add/remove you can also call `push()`/`pop()`. Push behaves
  6857. just like `add()` but `pop()`, unlike `remove()` will pick an arbitrary
  6858. object, remove it and return it. This is a good way to use a set as a job
  6859. queue when you don't care which order the jobs are executed in.
  6860. ## Testing for an Object
  6861. To test for an object's presence in a set you simply call
  6862. `Ember.Set#contains()`.
  6863. ## Observing changes
  6864. When using `Ember.Set`, you can observe the `"[]"` property to be
  6865. alerted whenever the content changes. You can also add an enumerable
  6866. observer to the set to be notified of specific objects that are added and
  6867. removed from the set. See `Ember.Enumerable` for more information on
  6868. enumerables.
  6869. This is often unhelpful. If you are filtering sets of objects, for instance,
  6870. it is very inefficient to re-filter all of the items each time the set
  6871. changes. It would be better if you could just adjust the filtered set based
  6872. on what was changed on the original set. The same issue applies to merging
  6873. sets, as well.
  6874. ## Other Methods
  6875. `Ember.Set` primary implements other mixin APIs. For a complete reference
  6876. on the methods you will use with `Ember.Set`, please consult these mixins.
  6877. The most useful ones will be `Ember.Enumerable` and
  6878. `Ember.MutableEnumerable` which implement most of the common iterator
  6879. methods you are used to on Array.
  6880. Note that you can also use the `Ember.Copyable` and `Ember.Freezable`
  6881. APIs on `Ember.Set` as well. Once a set is frozen it can no longer be
  6882. modified. The benefit of this is that when you call frozenCopy() on it,
  6883. Ember will avoid making copies of the set. This allows you to write
  6884. code that can know with certainty when the underlying set data will or
  6885. will not be modified.
  6886. @extends Ember.Enumerable
  6887. @extends Ember.MutableEnumerable
  6888. @extends Ember.Copyable
  6889. @extends Ember.Freezable
  6890. @since Ember 0.9
  6891. */
  6892. Ember.Set = Ember.CoreObject.extend(Ember.MutableEnumerable, Ember.Copyable, Ember.Freezable,
  6893. /** @scope Ember.Set.prototype */ {
  6894. // ..........................................................
  6895. // IMPLEMENT ENUMERABLE APIS
  6896. //
  6897. /**
  6898. This property will change as the number of objects in the set changes.
  6899. @type number
  6900. @default 0
  6901. */
  6902. length: 0,
  6903. /**
  6904. Clears the set. This is useful if you want to reuse an existing set
  6905. without having to recreate it.
  6906. var colors = new Ember.Set(["red", "green", "blue"]);
  6907. colors.length; => 3
  6908. colors.clear();
  6909. colors.length; => 0
  6910. @returns {Ember.Set} An empty Set
  6911. */
  6912. clear: function() {
  6913. if (this.isFrozen) { throw new Error(Ember.FROZEN_ERROR); }
  6914. var len = get(this, 'length');
  6915. if (len === 0) { return this; }
  6916. var guid;
  6917. this.enumerableContentWillChange(len, 0);
  6918. Ember.propertyWillChange(this, 'firstObject');
  6919. Ember.propertyWillChange(this, 'lastObject');
  6920. for (var i=0; i < len; i++){
  6921. guid = guidFor(this[i]);
  6922. delete this[guid];
  6923. delete this[i];
  6924. }
  6925. set(this, 'length', 0);
  6926. Ember.propertyDidChange(this, 'firstObject');
  6927. Ember.propertyDidChange(this, 'lastObject');
  6928. this.enumerableContentDidChange(len, 0);
  6929. return this;
  6930. },
  6931. /**
  6932. Returns true if the passed object is also an enumerable that contains the
  6933. same objects as the receiver.
  6934. var colors = ["red", "green", "blue"],
  6935. same_colors = new Ember.Set(colors);
  6936. same_colors.isEqual(colors); => true
  6937. same_colors.isEqual(["purple", "brown"]); => false
  6938. @param {Ember.Set} obj the other object.
  6939. @returns {Boolean}
  6940. */
  6941. isEqual: function(obj) {
  6942. // fail fast
  6943. if (!Ember.Enumerable.detect(obj)) return false;
  6944. var loc = get(this, 'length');
  6945. if (get(obj, 'length') !== loc) return false;
  6946. while(--loc >= 0) {
  6947. if (!obj.contains(this[loc])) return false;
  6948. }
  6949. return true;
  6950. },
  6951. /**
  6952. Adds an object to the set. Only non-null objects can be added to a set
  6953. and those can only be added once. If the object is already in the set or
  6954. the passed value is null this method will have no effect.
  6955. This is an alias for `Ember.MutableEnumerable.addObject()`.
  6956. var colors = new Ember.Set();
  6957. colors.add("blue"); => ["blue"]
  6958. colors.add("blue"); => ["blue"]
  6959. colors.add("red"); => ["blue", "red"]
  6960. colors.add(null); => ["blue", "red"]
  6961. colors.add(undefined); => ["blue", "red"]
  6962. @function
  6963. @param {Object} obj The object to add.
  6964. @returns {Ember.Set} The set itself.
  6965. */
  6966. add: Ember.alias('addObject'),
  6967. /**
  6968. Removes the object from the set if it is found. If you pass a null value
  6969. or an object that is already not in the set, this method will have no
  6970. effect. This is an alias for `Ember.MutableEnumerable.removeObject()`.
  6971. var colors = new Ember.Set(["red", "green", "blue"]);
  6972. colors.remove("red"); => ["blue", "green"]
  6973. colors.remove("purple"); => ["blue", "green"]
  6974. colors.remove(null); => ["blue", "green"]
  6975. @function
  6976. @param {Object} obj The object to remove
  6977. @returns {Ember.Set} The set itself.
  6978. */
  6979. remove: Ember.alias('removeObject'),
  6980. /**
  6981. Removes the last element from the set and returns it, or null if it's empty.
  6982. var colors = new Ember.Set(["green", "blue"]);
  6983. colors.pop(); => "blue"
  6984. colors.pop(); => "green"
  6985. colors.pop(); => null
  6986. @returns {Object} The removed object from the set or null.
  6987. */
  6988. pop: function() {
  6989. if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
  6990. var obj = this.length > 0 ? this[this.length-1] : null;
  6991. this.remove(obj);
  6992. return obj;
  6993. },
  6994. /**
  6995. Inserts the given object on to the end of the set. It returns
  6996. the set itself.
  6997. This is an alias for `Ember.MutableEnumerable.addObject()`.
  6998. var colors = new Ember.Set();
  6999. colors.push("red"); => ["red"]
  7000. colors.push("green"); => ["red", "green"]
  7001. colors.push("blue"); => ["red", "green", "blue"]
  7002. @function
  7003. @returns {Ember.Set} The set itself.
  7004. */
  7005. push: Ember.alias('addObject'),
  7006. /**
  7007. Removes the last element from the set and returns it, or null if it's empty.
  7008. This is an alias for `Ember.Set.pop()`.
  7009. var colors = new Ember.Set(["green", "blue"]);
  7010. colors.shift(); => "blue"
  7011. colors.shift(); => "green"
  7012. colors.shift(); => null
  7013. @function
  7014. @returns {Object} The removed object from the set or null.
  7015. */
  7016. shift: Ember.alias('pop'),
  7017. /**
  7018. Inserts the given object on to the end of the set. It returns
  7019. the set itself.
  7020. This is an alias of `Ember.Set.push()`
  7021. var colors = new Ember.Set();
  7022. colors.unshift("red"); => ["red"]
  7023. colors.unshift("green"); => ["red", "green"]
  7024. colors.unshift("blue"); => ["red", "green", "blue"]
  7025. @function
  7026. @returns {Ember.Set} The set itself.
  7027. */
  7028. unshift: Ember.alias('push'),
  7029. /**
  7030. Adds each object in the passed enumerable to the set.
  7031. This is an alias of `Ember.MutableEnumerable.addObjects()`
  7032. var colors = new Ember.Set();
  7033. colors.addEach(["red", "green", "blue"]); => ["red", "green", "blue"]
  7034. @function
  7035. @param {Ember.Enumerable} objects the objects to add.
  7036. @returns {Ember.Set} The set itself.
  7037. */
  7038. addEach: Ember.alias('addObjects'),
  7039. /**
  7040. Removes each object in the passed enumerable to the set.
  7041. This is an alias of `Ember.MutableEnumerable.removeObjects()`
  7042. var colors = new Ember.Set(["red", "green", "blue"]);
  7043. colors.removeEach(["red", "blue"]); => ["green"]
  7044. @function
  7045. @param {Ember.Enumerable} objects the objects to remove.
  7046. @returns {Ember.Set} The set itself.
  7047. */
  7048. removeEach: Ember.alias('removeObjects'),
  7049. // ..........................................................
  7050. // PRIVATE ENUMERABLE SUPPORT
  7051. //
  7052. /** @private */
  7053. init: function(items) {
  7054. this._super();
  7055. if (items) this.addObjects(items);
  7056. },
  7057. /** @private (nodoc) - implement Ember.Enumerable */
  7058. nextObject: function(idx) {
  7059. return this[idx];
  7060. },
  7061. /** @private - more optimized version */
  7062. firstObject: Ember.computed(function() {
  7063. return this.length > 0 ? this[0] : undefined;
  7064. }).property().cacheable(),
  7065. /** @private - more optimized version */
  7066. lastObject: Ember.computed(function() {
  7067. return this.length > 0 ? this[this.length-1] : undefined;
  7068. }).property().cacheable(),
  7069. /** @private (nodoc) - implements Ember.MutableEnumerable */
  7070. addObject: function(obj) {
  7071. if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
  7072. if (none(obj)) return this; // nothing to do
  7073. var guid = guidFor(obj),
  7074. idx = this[guid],
  7075. len = get(this, 'length'),
  7076. added ;
  7077. if (idx>=0 && idx<len && (this[idx] === obj)) return this; // added
  7078. added = [obj];
  7079. this.enumerableContentWillChange(null, added);
  7080. Ember.propertyWillChange(this, 'lastObject');
  7081. len = get(this, 'length');
  7082. this[guid] = len;
  7083. this[len] = obj;
  7084. set(this, 'length', len+1);
  7085. Ember.propertyDidChange(this, 'lastObject');
  7086. this.enumerableContentDidChange(null, added);
  7087. return this;
  7088. },
  7089. /** @private (nodoc) - implements Ember.MutableEnumerable */
  7090. removeObject: function(obj) {
  7091. if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
  7092. if (none(obj)) return this; // nothing to do
  7093. var guid = guidFor(obj),
  7094. idx = this[guid],
  7095. len = get(this, 'length'),
  7096. isFirst = idx === 0,
  7097. isLast = idx === len-1,
  7098. last, removed;
  7099. if (idx>=0 && idx<len && (this[idx] === obj)) {
  7100. removed = [obj];
  7101. this.enumerableContentWillChange(removed, null);
  7102. if (isFirst) { Ember.propertyWillChange(this, 'firstObject'); }
  7103. if (isLast) { Ember.propertyWillChange(this, 'lastObject'); }
  7104. // swap items - basically move the item to the end so it can be removed
  7105. if (idx < len-1) {
  7106. last = this[len-1];
  7107. this[idx] = last;
  7108. this[guidFor(last)] = idx;
  7109. }
  7110. delete this[guid];
  7111. delete this[len-1];
  7112. set(this, 'length', len-1);
  7113. if (isFirst) { Ember.propertyDidChange(this, 'firstObject'); }
  7114. if (isLast) { Ember.propertyDidChange(this, 'lastObject'); }
  7115. this.enumerableContentDidChange(removed, null);
  7116. }
  7117. return this;
  7118. },
  7119. /** @private (nodoc) - optimized version */
  7120. contains: function(obj) {
  7121. return this[guidFor(obj)]>=0;
  7122. },
  7123. /** @private (nodoc) */
  7124. copy: function() {
  7125. var C = this.constructor, ret = new C(), loc = get(this, 'length');
  7126. set(ret, 'length', loc);
  7127. while(--loc>=0) {
  7128. ret[loc] = this[loc];
  7129. ret[guidFor(this[loc])] = loc;
  7130. }
  7131. return ret;
  7132. },
  7133. /** @private */
  7134. toString: function() {
  7135. var len = this.length, idx, array = [];
  7136. for(idx = 0; idx < len; idx++) {
  7137. array[idx] = this[idx];
  7138. }
  7139. return "Ember.Set<%@>".fmt(array.join(','));
  7140. }
  7141. });
  7142. })();
  7143. (function() {
  7144. // ==========================================================================
  7145. // Project: Ember Runtime
  7146. // Copyright: ©2011 Strobe Inc. and contributors.
  7147. // License: Licensed under MIT license (see license.js)
  7148. // ==========================================================================
  7149. /**
  7150. @class
  7151. `Ember.Object` is the main base class for all Ember objects. It is a subclass
  7152. of `Ember.CoreObject` with the `Ember.Observable` mixin applied. For details,
  7153. see the documentation for each of these.
  7154. @extends Ember.CoreObject
  7155. @extends Ember.Observable
  7156. */
  7157. Ember.Object = Ember.CoreObject.extend(Ember.Observable);
  7158. })();
  7159. (function() {
  7160. // ==========================================================================
  7161. // Project: Ember Runtime
  7162. // Copyright: ©2011 Strobe Inc. and contributors.
  7163. // License: Licensed under MIT license (see license.js)
  7164. // ==========================================================================
  7165. var indexOf = Ember.ArrayPolyfills.indexOf;
  7166. /**
  7167. @private
  7168. A Namespace is an object usually used to contain other objects or methods
  7169. such as an application or framework. Create a namespace anytime you want
  7170. to define one of these new containers.
  7171. # Example Usage
  7172. MyFramework = Ember.Namespace.create({
  7173. VERSION: '1.0.0'
  7174. });
  7175. */
  7176. Ember.Namespace = Ember.Object.extend({
  7177. isNamespace: true,
  7178. init: function() {
  7179. Ember.Namespace.NAMESPACES.push(this);
  7180. Ember.Namespace.PROCESSED = false;
  7181. },
  7182. toString: function() {
  7183. Ember.identifyNamespaces();
  7184. return this[Ember.GUID_KEY+'_name'];
  7185. },
  7186. destroy: function() {
  7187. var namespaces = Ember.Namespace.NAMESPACES;
  7188. window[this.toString()] = undefined;
  7189. namespaces.splice(indexOf.call(namespaces, this), 1);
  7190. this._super();
  7191. }
  7192. });
  7193. Ember.Namespace.NAMESPACES = [Ember];
  7194. Ember.Namespace.PROCESSED = false;
  7195. })();
  7196. (function() {
  7197. // ==========================================================================
  7198. // Project: Ember Runtime
  7199. // Copyright: ©2011 Strobe Inc. and contributors.
  7200. // License: Licensed under MIT license (see license.js)
  7201. // ==========================================================================
  7202. /**
  7203. @private
  7204. Defines a namespace that will contain an executable application. This is
  7205. very similar to a normal namespace except that it is expected to include at
  7206. least a 'ready' function which can be run to initialize the application.
  7207. Currently Ember.Application is very similar to Ember.Namespace. However, this
  7208. class may be augmented by additional frameworks so it is important to use
  7209. this instance when building new applications.
  7210. # Example Usage
  7211. MyApp = Ember.Application.create({
  7212. VERSION: '1.0.0',
  7213. store: Ember.Store.create().from(Ember.fixtures)
  7214. });
  7215. MyApp.ready = function() {
  7216. //..init code goes here...
  7217. }
  7218. */
  7219. Ember.Application = Ember.Namespace.extend();
  7220. })();
  7221. (function() {
  7222. // ==========================================================================
  7223. // Project: Ember Runtime
  7224. // Copyright: ©2011 Strobe Inc. and contributors.
  7225. // License: Licensed under MIT license (see license.js)
  7226. // ==========================================================================
  7227. var get = Ember.get, set = Ember.set;
  7228. /**
  7229. @class
  7230. An ArrayProxy wraps any other object that implements Ember.Array and/or
  7231. Ember.MutableArray, forwarding all requests. This makes it very useful for
  7232. a number of binding use cases or other cases where being able to swap
  7233. out the underlying array is useful.
  7234. A simple example of usage:
  7235. var pets = ['dog', 'cat', 'fish'];
  7236. var ap = Ember.ArrayProxy.create({ content: Ember.A(pets) });
  7237. ap.get('firstObject'); // => 'dog'
  7238. ap.set('content', ['amoeba', 'paramecium']);
  7239. ap.get('firstObject'); // => 'amoeba'
  7240. This class can also be useful as a layer to transform the contents of
  7241. an array, as they are accessed. This can be done by overriding
  7242. `objectAtContent`:
  7243. var pets = ['dog', 'cat', 'fish'];
  7244. var ap = Ember.ArrayProxy.create({
  7245. content: Ember.A(pets),
  7246. objectAtContent: function(idx) {
  7247. return this.get('content').objectAt(idx).toUpperCase();
  7248. }
  7249. });
  7250. ap.get('firstObject'); // => 'DOG'
  7251. @extends Ember.Object
  7252. @extends Ember.Array
  7253. @extends Ember.MutableArray
  7254. */
  7255. Ember.ArrayProxy = Ember.Object.extend(Ember.MutableArray,
  7256. /** @scope Ember.ArrayProxy.prototype */ {
  7257. /**
  7258. The content array. Must be an object that implements Ember.Array and/or
  7259. Ember.MutableArray.
  7260. @type Ember.Array
  7261. */
  7262. content: null,
  7263. /**
  7264. The array that the proxy pretends to be. In the default `ArrayProxy`
  7265. implementation, this and `content` are the same. Subclasses of `ArrayProxy`
  7266. can override this property to provide things like sorting and filtering.
  7267. */
  7268. arrangedContent: Ember.computed('content', function() {
  7269. return get(this, 'content');
  7270. }).cacheable(),
  7271. /**
  7272. Should actually retrieve the object at the specified index from the
  7273. content. You can override this method in subclasses to transform the
  7274. content item to something new.
  7275. This method will only be called if content is non-null.
  7276. @param {Number} idx
  7277. The index to retrieve.
  7278. @returns {Object} the value or undefined if none found
  7279. */
  7280. objectAtContent: function(idx) {
  7281. return get(this, 'arrangedContent').objectAt(idx);
  7282. },
  7283. /**
  7284. Should actually replace the specified objects on the content array.
  7285. You can override this method in subclasses to transform the content item
  7286. into something new.
  7287. This method will only be called if content is non-null.
  7288. @param {Number} idx
  7289. The starting index
  7290. @param {Number} amt
  7291. The number of items to remove from the content.
  7292. @param {Array} objects
  7293. Optional array of objects to insert or null if no objects.
  7294. @returns {void}
  7295. */
  7296. replaceContent: function(idx, amt, objects) {
  7297. get(this, 'arrangedContent').replace(idx, amt, objects);
  7298. },
  7299. /**
  7300. Invoked when the content property is about to change. Notifies observers that the
  7301. entire array content will change.
  7302. */
  7303. _contentWillChange: Ember.beforeObserver(function() {
  7304. var content = get(this, 'content');
  7305. if (content) {
  7306. content.removeArrayObserver(this, {
  7307. willChange: 'contentArrayWillChange',
  7308. didChange: 'contentArrayDidChange'
  7309. });
  7310. }
  7311. }, 'content'),
  7312. contentArrayWillChange: Ember.K,
  7313. contentArrayDidChange: Ember.K,
  7314. /**
  7315. Invoked when the content property changes. Notifies observers that the
  7316. entire array content has changed.
  7317. */
  7318. _contentDidChange: Ember.observer(function() {
  7319. var content = get(this, 'content'),
  7320. len = content ? get(content, 'length') : 0;
  7321. Ember.assert("Can't set ArrayProxy's content to itself", content !== this);
  7322. if (content) {
  7323. content.addArrayObserver(this, {
  7324. willChange: 'contentArrayWillChange',
  7325. didChange: 'contentArrayDidChange'
  7326. });
  7327. }
  7328. }, 'content'),
  7329. _arrangedContentWillChange: Ember.beforeObserver(function() {
  7330. var arrangedContent = get(this, 'arrangedContent'),
  7331. len = arrangedContent ? get(arrangedContent, 'length') : 0;
  7332. this.arrangedContentArrayWillChange(this, 0, len, undefined);
  7333. if (arrangedContent) {
  7334. arrangedContent.removeArrayObserver(this, {
  7335. willChange: 'arrangedContentArrayWillChange',
  7336. didChange: 'arrangedContentArrayDidChange'
  7337. });
  7338. }
  7339. }, 'arrangedContent'),
  7340. _arrangedContentDidChange: Ember.observer(function() {
  7341. var arrangedContent = get(this, 'arrangedContent'),
  7342. len = arrangedContent ? get(arrangedContent, 'length') : 0;
  7343. Ember.assert("Can't set ArrayProxy's content to itself", arrangedContent !== this);
  7344. if (arrangedContent) {
  7345. arrangedContent.addArrayObserver(this, {
  7346. willChange: 'arrangedContentArrayWillChange',
  7347. didChange: 'arrangedContentArrayDidChange'
  7348. });
  7349. }
  7350. this.arrangedContentArrayDidChange(this, 0, undefined, len);
  7351. }, 'arrangedContent'),
  7352. /** @private (nodoc) */
  7353. objectAt: function(idx) {
  7354. return get(this, 'content') && this.objectAtContent(idx);
  7355. },
  7356. /** @private (nodoc) */
  7357. length: Ember.computed(function() {
  7358. var arrangedContent = get(this, 'arrangedContent');
  7359. return arrangedContent ? get(arrangedContent, 'length') : 0;
  7360. // No dependencies since Enumerable notifies length of change
  7361. }).property().cacheable(),
  7362. /** @private (nodoc) */
  7363. replace: function(idx, amt, objects) {
  7364. if (get(this, 'content')) this.replaceContent(idx, amt, objects);
  7365. return this;
  7366. },
  7367. /** @private (nodoc) */
  7368. arrangedContentArrayWillChange: function(item, idx, removedCnt, addedCnt) {
  7369. this.arrayContentWillChange(idx, removedCnt, addedCnt);
  7370. },
  7371. /** @private (nodoc) */
  7372. arrangedContentArrayDidChange: function(item, idx, removedCnt, addedCnt) {
  7373. this.arrayContentDidChange(idx, removedCnt, addedCnt);
  7374. },
  7375. /** @private (nodoc) */
  7376. init: function() {
  7377. this._super();
  7378. this._contentWillChange();
  7379. this._contentDidChange();
  7380. this._arrangedContentWillChange();
  7381. this._arrangedContentDidChange();
  7382. }
  7383. });
  7384. })();
  7385. (function() {
  7386. var get = Ember.get,
  7387. set = Ember.set,
  7388. fmt = Ember.String.fmt,
  7389. addBeforeObserver = Ember.addBeforeObserver,
  7390. addObserver = Ember.addObserver,
  7391. removeBeforeObserver = Ember.removeBeforeObserver,
  7392. removeObserver = Ember.removeObserver,
  7393. propertyWillChange = Ember.propertyWillChange,
  7394. propertyDidChange = Ember.propertyDidChange;
  7395. function contentPropertyWillChange(content, contentKey) {
  7396. var key = contentKey.slice(8); // remove "content."
  7397. if (key in this) { return; } // if shadowed in proxy
  7398. propertyWillChange(this, key);
  7399. }
  7400. function contentPropertyDidChange(content, contentKey) {
  7401. var key = contentKey.slice(8); // remove "content."
  7402. if (key in this) { return; } // if shadowed in proxy
  7403. propertyDidChange(this, key);
  7404. }
  7405. /**
  7406. @class
  7407. `Ember.ObjectProxy` forwards all properties not defined by the proxy itself
  7408. to a proxied `content` object.
  7409. object = Ember.Object.create({
  7410. name: 'Foo'
  7411. });
  7412. proxy = Ember.ObjectProxy.create({
  7413. content: object
  7414. });
  7415. // Access and change existing properties
  7416. proxy.get('name') // => 'Foo'
  7417. proxy.set('name', 'Bar');
  7418. object.get('name') // => 'Bar'
  7419. // Create new 'description' property on `object`
  7420. proxy.set('description', 'Foo is a whizboo baz');
  7421. object.get('description') // => 'Foo is a whizboo baz'
  7422. While `content` is unset, setting a property to be delegated will throw an Error.
  7423. proxy = Ember.ObjectProxy.create({
  7424. content: null,
  7425. flag: null
  7426. });
  7427. proxy.set('flag', true);
  7428. proxy.get('flag'); // => true
  7429. proxy.get('foo'); // => undefined
  7430. proxy.set('foo', 'data'); // throws Error
  7431. Delegated properties can be bound to and will change when content is updated.
  7432. Computed properties on the proxy itself can depend on delegated properties.
  7433. ProxyWithComputedProperty = Ember.ObjectProxy.extend({
  7434. fullName: function () {
  7435. var firstName = this.get('firstName'),
  7436. lastName = this.get('lastName');
  7437. if (firstName && lastName) {
  7438. return firstName + ' ' + lastName;
  7439. }
  7440. return firstName || lastName;
  7441. }.property('firstName', 'lastName')
  7442. });
  7443. proxy = ProxyWithComputedProperty.create();
  7444. proxy.get('fullName'); => undefined
  7445. proxy.set('content', {
  7446. firstName: 'Tom', lastName: 'Dale'
  7447. }); // triggers property change for fullName on proxy
  7448. proxy.get('fullName'); => 'Tom Dale'
  7449. */
  7450. Ember.ObjectProxy = Ember.Object.extend(
  7451. /** @scope Ember.ObjectProxy.prototype */ {
  7452. /**
  7453. The object whose properties will be forwarded.
  7454. @type Ember.Object
  7455. @default null
  7456. */
  7457. content: null,
  7458. _contentDidChange: Ember.observer(function() {
  7459. Ember.assert("Can't set ObjectProxy's content to itself", this.get('content') !== this);
  7460. }, 'content'),
  7461. /** @private */
  7462. willWatchProperty: function (key) {
  7463. var contentKey = 'content.' + key;
  7464. addBeforeObserver(this, contentKey, null, contentPropertyWillChange);
  7465. addObserver(this, contentKey, null, contentPropertyDidChange);
  7466. },
  7467. /** @private */
  7468. didUnwatchProperty: function (key) {
  7469. var contentKey = 'content.' + key;
  7470. removeBeforeObserver(this, contentKey, null, contentPropertyWillChange);
  7471. removeObserver(this, contentKey, null, contentPropertyDidChange);
  7472. },
  7473. /** @private */
  7474. unknownProperty: function (key) {
  7475. var content = get(this, 'content');
  7476. if (content) {
  7477. return get(content, key);
  7478. }
  7479. },
  7480. /** @private */
  7481. setUnknownProperty: function (key, value) {
  7482. var content = get(this, 'content');
  7483. Ember.assert(fmt("Cannot delegate set('%@', %@) to the 'content' property of object proxy %@: its 'content' is undefined.", [key, value, this]), content);
  7484. return set(content, key, value);
  7485. }
  7486. });
  7487. })();
  7488. (function() {
  7489. // ==========================================================================
  7490. // Project: Ember Runtime
  7491. // Copyright: ©2011 Strobe Inc. and contributors.
  7492. // License: Licensed under MIT license (see license.js)
  7493. // ==========================================================================
  7494. var set = Ember.set, get = Ember.get, guidFor = Ember.guidFor;
  7495. var forEach = Ember.EnumerableUtils.forEach;
  7496. var EachArray = Ember.Object.extend(Ember.Array, {
  7497. init: function(content, keyName, owner) {
  7498. this._super();
  7499. this._keyName = keyName;
  7500. this._owner = owner;
  7501. this._content = content;
  7502. },
  7503. objectAt: function(idx) {
  7504. var item = this._content.objectAt(idx);
  7505. return item && get(item, this._keyName);
  7506. },
  7507. length: Ember.computed(function() {
  7508. var content = this._content;
  7509. return content ? get(content, 'length') : 0;
  7510. }).property().cacheable()
  7511. });
  7512. var IS_OBSERVER = /^.+:(before|change)$/;
  7513. /** @private */
  7514. function addObserverForContentKey(content, keyName, proxy, idx, loc) {
  7515. var objects = proxy._objects, guid;
  7516. if (!objects) objects = proxy._objects = {};
  7517. while(--loc>=idx) {
  7518. var item = content.objectAt(loc);
  7519. if (item) {
  7520. Ember.addBeforeObserver(item, keyName, proxy, 'contentKeyWillChange');
  7521. Ember.addObserver(item, keyName, proxy, 'contentKeyDidChange');
  7522. // keep track of the indicies each item was found at so we can map
  7523. // it back when the obj changes.
  7524. guid = guidFor(item);
  7525. if (!objects[guid]) objects[guid] = [];
  7526. objects[guid].push(loc);
  7527. }
  7528. }
  7529. }
  7530. /** @private */
  7531. function removeObserverForContentKey(content, keyName, proxy, idx, loc) {
  7532. var objects = proxy._objects;
  7533. if (!objects) objects = proxy._objects = {};
  7534. var indicies, guid;
  7535. while(--loc>=idx) {
  7536. var item = content.objectAt(loc);
  7537. if (item) {
  7538. Ember.removeBeforeObserver(item, keyName, proxy, 'contentKeyWillChange');
  7539. Ember.removeObserver(item, keyName, proxy, 'contentKeyDidChange');
  7540. guid = guidFor(item);
  7541. indicies = objects[guid];
  7542. indicies[indicies.indexOf(loc)] = null;
  7543. }
  7544. }
  7545. }
  7546. /**
  7547. @private
  7548. @class
  7549. This is the object instance returned when you get the @each property on an
  7550. array. It uses the unknownProperty handler to automatically create
  7551. EachArray instances for property names.
  7552. @extends Ember.Object
  7553. */
  7554. Ember.EachProxy = Ember.Object.extend({
  7555. init: function(content) {
  7556. this._super();
  7557. this._content = content;
  7558. content.addArrayObserver(this);
  7559. // in case someone is already observing some keys make sure they are
  7560. // added
  7561. forEach(Ember.watchedEvents(this), function(eventName) {
  7562. this.didAddListener(eventName);
  7563. }, this);
  7564. },
  7565. /**
  7566. You can directly access mapped properties by simply requesting them.
  7567. The unknownProperty handler will generate an EachArray of each item.
  7568. */
  7569. unknownProperty: function(keyName, value) {
  7570. var ret;
  7571. ret = new EachArray(this._content, keyName, this);
  7572. Ember.defineProperty(this, keyName, null, ret);
  7573. this.beginObservingContentKey(keyName);
  7574. return ret;
  7575. },
  7576. // ..........................................................
  7577. // ARRAY CHANGES
  7578. // Invokes whenever the content array itself changes.
  7579. arrayWillChange: function(content, idx, removedCnt, addedCnt) {
  7580. var keys = this._keys, key, array, lim;
  7581. lim = removedCnt>0 ? idx+removedCnt : -1;
  7582. Ember.beginPropertyChanges(this);
  7583. for(key in keys) {
  7584. if (!keys.hasOwnProperty(key)) { continue; }
  7585. if (lim>0) removeObserverForContentKey(content, key, this, idx, lim);
  7586. Ember.propertyWillChange(this, key);
  7587. }
  7588. Ember.propertyWillChange(this._content, '@each');
  7589. Ember.endPropertyChanges(this);
  7590. },
  7591. arrayDidChange: function(content, idx, removedCnt, addedCnt) {
  7592. var keys = this._keys, key, array, lim;
  7593. lim = addedCnt>0 ? idx+addedCnt : -1;
  7594. Ember.beginPropertyChanges(this);
  7595. for(key in keys) {
  7596. if (!keys.hasOwnProperty(key)) { continue; }
  7597. if (lim>0) addObserverForContentKey(content, key, this, idx, lim);
  7598. Ember.propertyDidChange(this, key);
  7599. }
  7600. Ember.propertyDidChange(this._content, '@each');
  7601. Ember.endPropertyChanges(this);
  7602. },
  7603. // ..........................................................
  7604. // LISTEN FOR NEW OBSERVERS AND OTHER EVENT LISTENERS
  7605. // Start monitoring keys based on who is listening...
  7606. didAddListener: function(eventName) {
  7607. if (IS_OBSERVER.test(eventName)) {
  7608. this.beginObservingContentKey(eventName.slice(0, -7));
  7609. }
  7610. },
  7611. didRemoveListener: function(eventName) {
  7612. if (IS_OBSERVER.test(eventName)) {
  7613. this.stopObservingContentKey(eventName.slice(0, -7));
  7614. }
  7615. },
  7616. // ..........................................................
  7617. // CONTENT KEY OBSERVING
  7618. // Actual watch keys on the source content.
  7619. beginObservingContentKey: function(keyName) {
  7620. var keys = this._keys;
  7621. if (!keys) keys = this._keys = {};
  7622. if (!keys[keyName]) {
  7623. keys[keyName] = 1;
  7624. var content = this._content,
  7625. len = get(content, 'length');
  7626. addObserverForContentKey(content, keyName, this, 0, len);
  7627. } else {
  7628. keys[keyName]++;
  7629. }
  7630. },
  7631. stopObservingContentKey: function(keyName) {
  7632. var keys = this._keys;
  7633. if (keys && (keys[keyName]>0) && (--keys[keyName]<=0)) {
  7634. var content = this._content,
  7635. len = get(content, 'length');
  7636. removeObserverForContentKey(content, keyName, this, 0, len);
  7637. }
  7638. },
  7639. contentKeyWillChange: function(obj, keyName) {
  7640. Ember.propertyWillChange(this, keyName);
  7641. },
  7642. contentKeyDidChange: function(obj, keyName) {
  7643. Ember.propertyDidChange(this, keyName);
  7644. }
  7645. });
  7646. })();
  7647. (function() {
  7648. // ==========================================================================
  7649. // Project: Ember Runtime
  7650. // Copyright: ©2011 Strobe Inc. and contributors.
  7651. // License: Licensed under MIT license (see license.js)
  7652. // ==========================================================================
  7653. var get = Ember.get, set = Ember.set;
  7654. // Add Ember.Array to Array.prototype. Remove methods with native
  7655. // implementations and supply some more optimized versions of generic methods
  7656. // because they are so common.
  7657. var NativeArray = Ember.Mixin.create(Ember.MutableArray, Ember.Observable, Ember.Copyable, {
  7658. // because length is a built-in property we need to know to just get the
  7659. // original property.
  7660. get: function(key) {
  7661. if (key==='length') return this.length;
  7662. else if ('number' === typeof key) return this[key];
  7663. else return this._super(key);
  7664. },
  7665. objectAt: function(idx) {
  7666. return this[idx];
  7667. },
  7668. // primitive for array support.
  7669. replace: function(idx, amt, objects) {
  7670. if (this.isFrozen) throw Ember.FROZEN_ERROR ;
  7671. // if we replaced exactly the same number of items, then pass only the
  7672. // replaced range. Otherwise, pass the full remaining array length
  7673. // since everything has shifted
  7674. var len = objects ? get(objects, 'length') : 0;
  7675. this.arrayContentWillChange(idx, amt, len);
  7676. if (!objects || objects.length === 0) {
  7677. this.splice(idx, amt) ;
  7678. } else {
  7679. var args = [idx, amt].concat(objects) ;
  7680. this.splice.apply(this,args) ;
  7681. }
  7682. this.arrayContentDidChange(idx, amt, len);
  7683. return this ;
  7684. },
  7685. // If you ask for an unknown property, then try to collect the value
  7686. // from member items.
  7687. unknownProperty: function(key, value) {
  7688. var ret;// = this.reducedProperty(key, value) ;
  7689. if ((value !== undefined) && ret === undefined) {
  7690. ret = this[key] = value;
  7691. }
  7692. return ret ;
  7693. },
  7694. // If browser did not implement indexOf natively, then override with
  7695. // specialized version
  7696. indexOf: function(object, startAt) {
  7697. var idx, len = this.length;
  7698. if (startAt === undefined) startAt = 0;
  7699. else startAt = (startAt < 0) ? Math.ceil(startAt) : Math.floor(startAt);
  7700. if (startAt < 0) startAt += len;
  7701. for(idx=startAt;idx<len;idx++) {
  7702. if (this[idx] === object) return idx ;
  7703. }
  7704. return -1;
  7705. },
  7706. lastIndexOf: function(object, startAt) {
  7707. var idx, len = this.length;
  7708. if (startAt === undefined) startAt = len-1;
  7709. else startAt = (startAt < 0) ? Math.ceil(startAt) : Math.floor(startAt);
  7710. if (startAt < 0) startAt += len;
  7711. for(idx=startAt;idx>=0;idx--) {
  7712. if (this[idx] === object) return idx ;
  7713. }
  7714. return -1;
  7715. },
  7716. copy: function() {
  7717. return this.slice();
  7718. }
  7719. });
  7720. // Remove any methods implemented natively so we don't override them
  7721. var ignore = ['length'];
  7722. Ember.EnumerableUtils.forEach(NativeArray.keys(), function(methodName) {
  7723. if (Array.prototype[methodName]) ignore.push(methodName);
  7724. });
  7725. if (ignore.length>0) {
  7726. NativeArray = NativeArray.without.apply(NativeArray, ignore);
  7727. }
  7728. /**
  7729. The NativeArray mixin contains the properties needed to to make the native
  7730. Array support Ember.MutableArray and all of its dependent APIs. Unless you
  7731. have Ember.EXTEND_PROTOTYPES set to false, this will be applied automatically.
  7732. Otherwise you can apply the mixin at anytime by calling
  7733. `Ember.NativeArray.activate`.
  7734. @namespace
  7735. @extends Ember.MutableArray
  7736. @extends Ember.Array
  7737. @extends Ember.Enumerable
  7738. @extends Ember.MutableEnumerable
  7739. @extends Ember.Copyable
  7740. @extends Ember.Freezable
  7741. */
  7742. Ember.NativeArray = NativeArray;
  7743. /**
  7744. Creates an Ember.NativeArray from an Array like object.
  7745. Does not modify the original object.
  7746. @returns {Ember.NativeArray}
  7747. */
  7748. Ember.A = function(arr){
  7749. if (arr === undefined) { arr = []; }
  7750. return Ember.NativeArray.apply(arr);
  7751. };
  7752. /**
  7753. Activates the mixin on the Array.prototype if not already applied. Calling
  7754. this method more than once is safe.
  7755. @returns {void}
  7756. */
  7757. Ember.NativeArray.activate = function() {
  7758. NativeArray.apply(Array.prototype);
  7759. Ember.A = function(arr) { return arr || []; };
  7760. };
  7761. if (Ember.EXTEND_PROTOTYPES) Ember.NativeArray.activate();
  7762. })();
  7763. (function() {
  7764. // ==========================================================================
  7765. // Project: Ember Runtime
  7766. // Copyright: ©2011 Strobe Inc. and contributors.
  7767. // License: Licensed under MIT license (see license.js)
  7768. // ==========================================================================
  7769. var get = Ember.get, set = Ember.set;
  7770. Ember._PromiseChain = Ember.Object.extend({
  7771. promises: null,
  7772. failureCallback: Ember.K,
  7773. successCallback: Ember.K,
  7774. abortCallback: Ember.K,
  7775. promiseSuccessCallback: Ember.K,
  7776. /**
  7777. @private
  7778. */
  7779. runNextPromise: function() {
  7780. if (get(this, 'isDestroyed')) { return; }
  7781. var item = get(this, 'promises').shiftObject();
  7782. if (item) {
  7783. var promise = get(item, 'promise') || item;
  7784. Ember.assert("Cannot find promise to invoke", Ember.canInvoke(promise, 'then'));
  7785. var self = this;
  7786. var successCallback = function() {
  7787. self.promiseSuccessCallback.call(this, item, arguments);
  7788. self.runNextPromise();
  7789. };
  7790. var failureCallback = get(self, 'failureCallback');
  7791. promise.then(successCallback, failureCallback);
  7792. } else {
  7793. this.successCallback();
  7794. }
  7795. },
  7796. start: function() {
  7797. this.runNextPromise();
  7798. return this;
  7799. },
  7800. abort: function() {
  7801. this.abortCallback();
  7802. this.destroy();
  7803. },
  7804. init: function() {
  7805. set(this, 'promises', Ember.A(get(this, 'promises')));
  7806. this._super();
  7807. }
  7808. });
  7809. })();
  7810. (function() {
  7811. var loadHooks = {};
  7812. var loaded = {};
  7813. Ember.onLoad = function(name, callback) {
  7814. var object;
  7815. loadHooks[name] = loadHooks[name] || Ember.A();
  7816. loadHooks[name].pushObject(callback);
  7817. if (object = loaded[name]) {
  7818. callback(object);
  7819. }
  7820. };
  7821. Ember.runLoadHooks = function(name, object) {
  7822. var hooks;
  7823. loaded[name] = object;
  7824. if (hooks = loadHooks[name]) {
  7825. loadHooks[name].forEach(function(callback) {
  7826. callback(object);
  7827. });
  7828. }
  7829. };
  7830. })();
  7831. (function() {
  7832. // ==========================================================================
  7833. // Project: Ember Runtime
  7834. // Copyright: ©2011 Strobe Inc. and contributors.
  7835. // License: Licensed under MIT license (see license.js)
  7836. // ==========================================================================
  7837. })();
  7838. (function() {
  7839. Ember.ControllerMixin = Ember.Mixin.create({
  7840. /**
  7841. The object to which events from the view should be sent.
  7842. For example, when a Handlebars template uses the `{{action}}` helper,
  7843. it will attempt to send the event to the view's controller's `target`.
  7844. By default, a controller's `target` is set to the router after it is
  7845. instantiated by `Ember.Application#initialize`.
  7846. */
  7847. target: null,
  7848. store: null
  7849. });
  7850. Ember.Controller = Ember.Object.extend(Ember.ControllerMixin);
  7851. })();
  7852. (function() {
  7853. var get = Ember.get, set = Ember.set, forEach = Ember.EnumerableUtils.forEach;
  7854. /**
  7855. @class
  7856. @extends Ember.Mixin
  7857. @extends Ember.MutableEnumerable
  7858. */
  7859. Ember.SortableMixin = Ember.Mixin.create(Ember.MutableEnumerable,
  7860. /** @scope Ember.Observable.prototype */ {
  7861. sortProperties: null,
  7862. sortAscending: true,
  7863. addObject: function(obj) {
  7864. var content = get(this, 'content');
  7865. content.pushObject(obj);
  7866. },
  7867. removeObject: function(obj) {
  7868. var content = get(this, 'content');
  7869. content.removeObject(obj);
  7870. },
  7871. orderBy: function(item1, item2) {
  7872. var result = 0,
  7873. sortProperties = get(this, 'sortProperties'),
  7874. sortAscending = get(this, 'sortAscending');
  7875. Ember.assert("you need to define `sortProperties`", !!sortProperties);
  7876. forEach(sortProperties, function(propertyName) {
  7877. if (result === 0) {
  7878. result = Ember.compare(get(item1, propertyName), get(item2, propertyName));
  7879. if ((result !== 0) && !sortAscending) {
  7880. result = (-1) * result;
  7881. }
  7882. }
  7883. });
  7884. return result;
  7885. },
  7886. destroy: function() {
  7887. var content = get(this, 'content'),
  7888. sortProperties = get(this, 'sortProperties');
  7889. if (content && sortProperties) {
  7890. forEach(content, function(item) {
  7891. forEach(sortProperties, function(sortProperty) {
  7892. Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange');
  7893. }, this);
  7894. }, this);
  7895. }
  7896. return this._super();
  7897. },
  7898. isSorted: Ember.computed('sortProperties', function() {
  7899. return !!get(this, 'sortProperties');
  7900. }),
  7901. arrangedContent: Ember.computed('content', 'sortProperties.@each', function(key, value) {
  7902. var content = get(this, 'content'),
  7903. isSorted = get(this, 'isSorted'),
  7904. sortProperties = get(this, 'sortProperties'),
  7905. self = this;
  7906. if (content && isSorted) {
  7907. content = content.slice();
  7908. content.sort(function(item1, item2) {
  7909. return self.orderBy(item1, item2);
  7910. });
  7911. forEach(content, function(item) {
  7912. forEach(sortProperties, function(sortProperty) {
  7913. Ember.addObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange');
  7914. }, this);
  7915. }, this);
  7916. return Ember.A(content);
  7917. }
  7918. return content;
  7919. }).cacheable(),
  7920. _contentWillChange: Ember.beforeObserver(function() {
  7921. var content = get(this, 'content'),
  7922. sortProperties = get(this, 'sortProperties');
  7923. if (content && sortProperties) {
  7924. forEach(content, function(item) {
  7925. forEach(sortProperties, function(sortProperty) {
  7926. Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange');
  7927. }, this);
  7928. }, this);
  7929. }
  7930. this._super();
  7931. }, 'content'),
  7932. sortAscendingWillChange: Ember.beforeObserver(function() {
  7933. this._lastSortAscending = get(this, 'sortAscending');
  7934. }, 'sortAscending'),
  7935. sortAscendingDidChange: Ember.observer(function() {
  7936. if (get(this, 'sortAscending') !== this._lastSortAscending) {
  7937. var arrangedContent = get(this, 'arrangedContent');
  7938. arrangedContent.reverseObjects();
  7939. }
  7940. }, 'sortAscending'),
  7941. contentArrayWillChange: function(array, idx, removedCount, addedCount) {
  7942. var isSorted = get(this, 'isSorted');
  7943. if (isSorted) {
  7944. var arrangedContent = get(this, 'arrangedContent');
  7945. var removedObjects = array.slice(idx, idx+removedCount);
  7946. var sortProperties = get(this, 'sortProperties');
  7947. forEach(removedObjects, function(item) {
  7948. arrangedContent.removeObject(item);
  7949. forEach(sortProperties, function(sortProperty) {
  7950. Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange');
  7951. }, this);
  7952. });
  7953. }
  7954. return this._super(array, idx, removedCount, addedCount);
  7955. },
  7956. contentArrayDidChange: function(array, idx, removedCount, addedCount) {
  7957. var isSorted = get(this, 'isSorted'),
  7958. sortProperties = get(this, 'sortProperties');
  7959. if (isSorted) {
  7960. var addedObjects = array.slice(idx, idx+addedCount);
  7961. var arrangedContent = get(this, 'arrangedContent');
  7962. forEach(addedObjects, function(item) {
  7963. this.insertItemSorted(item);
  7964. forEach(sortProperties, function(sortProperty) {
  7965. Ember.addObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange');
  7966. }, this);
  7967. }, this);
  7968. }
  7969. return this._super(array, idx, removedCount, addedCount);
  7970. },
  7971. insertItemSorted: function(item) {
  7972. var arrangedContent = get(this, 'arrangedContent');
  7973. var length = get(arrangedContent, 'length');
  7974. var idx = this._binarySearch(item, 0, length);
  7975. arrangedContent.insertAt(idx, item);
  7976. },
  7977. contentItemSortPropertyDidChange: function(item) {
  7978. var arrangedContent = get(this, 'arrangedContent'),
  7979. index = arrangedContent.indexOf(item);
  7980. arrangedContent.removeObject(item);
  7981. this.insertItemSorted(item);
  7982. },
  7983. _binarySearch: function(item, low, high) {
  7984. var mid, midItem, res, arrangedContent;
  7985. if (low === high) {
  7986. return low;
  7987. }
  7988. arrangedContent = get(this, 'arrangedContent');
  7989. mid = low + Math.floor((high - low) / 2);
  7990. midItem = arrangedContent.objectAt(mid);
  7991. res = this.orderBy(midItem, item);
  7992. if (res < 0) {
  7993. return this._binarySearch(item, mid+1, high);
  7994. } else if (res > 0) {
  7995. return this._binarySearch(item, low, mid);
  7996. }
  7997. return mid;
  7998. }
  7999. });
  8000. })();
  8001. (function() {
  8002. // ==========================================================================
  8003. // Project: Ember Runtime
  8004. // Copyright: ©2011 Strobe Inc. and contributors.
  8005. // License: Licensed under MIT license (see license.js)
  8006. // ==========================================================================
  8007. var get = Ember.get, set = Ember.set;
  8008. /**
  8009. @class
  8010. Ember.ArrayController provides a way for you to publish a collection of objects
  8011. so that you can easily bind to the collection from a Handlebars #each helper,
  8012. an Ember.CollectionView, or other controllers.
  8013. The advantage of using an ArrayController is that you only have to set up
  8014. your view bindings once; to change what's displayed, simply swap out the
  8015. `content` property on the controller.
  8016. For example, imagine you wanted to display a list of items fetched via an XHR
  8017. request. Create an Ember.ArrayController and set its `content` property:
  8018. MyApp.listController = Ember.ArrayController.create();
  8019. $.get('people.json', function(data) {
  8020. MyApp.listController.set('content', data);
  8021. });
  8022. Then, create a view that binds to your new controller:
  8023. {{#each MyApp.listController}}
  8024. {{firstName}} {{lastName}}
  8025. {{/each}}
  8026. Although you are binding to the controller, the behavior of this controller
  8027. is to pass through any methods or properties to the underlying array. This
  8028. capability comes from `Ember.ArrayProxy`, which this class inherits from.
  8029. Note: As of this writing, `ArrayController` does not add any functionality
  8030. to its superclass, `ArrayProxy`. The Ember team plans to add additional
  8031. controller-specific functionality in the future, e.g. single or multiple
  8032. selection support. If you are creating something that is conceptually a
  8033. controller, use this class.
  8034. @extends Ember.ArrayProxy
  8035. */
  8036. Ember.ArrayController = Ember.ArrayProxy.extend(Ember.ControllerMixin,
  8037. Ember.SortableMixin);
  8038. })();
  8039. (function() {
  8040. Ember.ObjectController = Ember.ObjectProxy.extend(Ember.ControllerMixin);
  8041. })();
  8042. (function() {
  8043. })();
  8044. (function() {
  8045. // ==========================================================================
  8046. // Project: Ember Runtime
  8047. // Copyright: ©2011 Strobe Inc. and contributors.
  8048. // License: Licensed under MIT license (see license.js)
  8049. // ==========================================================================
  8050. })();
  8051. (function() {
  8052. // ==========================================================================
  8053. // Project: Ember - JavaScript Application Framework
  8054. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  8055. // Portions ©2008-2011 Apple Inc. All rights reserved.
  8056. // License: Licensed under MIT license (see license.js)
  8057. // ==========================================================================
  8058. var get = Ember.get, set = Ember.set;
  8059. /**
  8060. @class
  8061. An Ember.Application instance serves as the namespace in which you define your
  8062. application's classes. You can also override the configuration of your
  8063. application.
  8064. By default, Ember.Application will begin listening for events on the document.
  8065. If your application is embedded inside a page, instead of controlling the
  8066. entire document, you can specify which DOM element to attach to by setting
  8067. the `rootElement` property:
  8068. MyApp = Ember.Application.create({
  8069. rootElement: $('#my-app')
  8070. });
  8071. The root of an Ember.Application must not be removed during the course of the
  8072. page's lifetime. If you have only a single conceptual application for the
  8073. entire page, and are not embedding any third-party Ember applications
  8074. in your page, use the default document root for your application.
  8075. You only need to specify the root if your page contains multiple instances
  8076. of Ember.Application.
  8077. @extends Ember.Object
  8078. */
  8079. Ember.Application = Ember.Namespace.extend(
  8080. /** @scope Ember.Application.prototype */{
  8081. /**
  8082. The root DOM element of the Application.
  8083. Can be specified as DOMElement or a selector string.
  8084. @type DOMElement
  8085. @default 'body'
  8086. */
  8087. rootElement: 'body',
  8088. /**
  8089. @type Ember.EventDispatcher
  8090. @default null
  8091. */
  8092. eventDispatcher: null,
  8093. /**
  8094. @type Object
  8095. @default null
  8096. */
  8097. customEvents: null,
  8098. /** @private */
  8099. init: function() {
  8100. var eventDispatcher,
  8101. rootElement = get(this, 'rootElement');
  8102. this._super();
  8103. eventDispatcher = Ember.EventDispatcher.create({
  8104. rootElement: rootElement
  8105. });
  8106. set(this, 'eventDispatcher', eventDispatcher);
  8107. // jQuery 1.7 doesn't call the ready callback if already ready
  8108. if (Ember.$.isReady) {
  8109. Ember.run.once(this, this.didBecomeReady);
  8110. } else {
  8111. var self = this;
  8112. Ember.$(document).ready(function() {
  8113. Ember.run.once(self, self.didBecomeReady);
  8114. });
  8115. }
  8116. },
  8117. /**
  8118. Instantiate all controllers currently available on the namespace
  8119. and inject them onto a router.
  8120. Example:
  8121. App.PostsController = Ember.ArrayController.extend();
  8122. App.CommentsController = Ember.ArrayController.extend();
  8123. var router = Ember.Router.create({
  8124. ...
  8125. });
  8126. App.initialize(router);
  8127. router.get('postsController') // <App.PostsController:ember1234>
  8128. router.get('commentsController') // <App.CommentsController:ember1235>
  8129. router.get('postsController.router') // router
  8130. */
  8131. initialize: function(router) {
  8132. var properties = Ember.A(Ember.keys(this)),
  8133. injections = get(this.constructor, 'injections'),
  8134. namespace = this, controller, name;
  8135. if (!router && Ember.Router.detect(namespace['Router'])) {
  8136. router = namespace['Router'].create();
  8137. this._createdRouter = router;
  8138. }
  8139. if (router) {
  8140. set(this, 'router', router);
  8141. // By default, the router's namespace is the current application.
  8142. //
  8143. // This allows it to find model classes when a state has a
  8144. // route like `/posts/:post_id`. In that case, it would first
  8145. // convert `post_id` into `Post`, and then look it up on its
  8146. // namespace.
  8147. set(router, 'namespace', this);
  8148. }
  8149. Ember.runLoadHooks('application', this);
  8150. injections.forEach(function(injection) {
  8151. properties.forEach(function(property) {
  8152. injection[1](namespace, router, property);
  8153. });
  8154. });
  8155. if (router && router instanceof Ember.Router) {
  8156. this.startRouting(router);
  8157. }
  8158. },
  8159. /** @private */
  8160. didBecomeReady: function() {
  8161. var eventDispatcher = get(this, 'eventDispatcher'),
  8162. customEvents = get(this, 'customEvents');
  8163. eventDispatcher.setup(customEvents);
  8164. this.ready();
  8165. },
  8166. /**
  8167. @private
  8168. If the application has a router, use it to route to the current URL, and
  8169. trigger a new call to `route` whenever the URL changes.
  8170. */
  8171. startRouting: function(router) {
  8172. var location = get(router, 'location'),
  8173. rootElement = get(this, 'rootElement'),
  8174. applicationController = get(router, 'applicationController');
  8175. Ember.assert("ApplicationView and ApplicationController must be defined on your application", (this.ApplicationView && applicationController) );
  8176. var applicationView = this.ApplicationView.create({
  8177. controller: applicationController
  8178. });
  8179. this._createdApplicationView = applicationView;
  8180. applicationView.appendTo(rootElement);
  8181. router.route(location.getURL());
  8182. location.onUpdateURL(function(url) {
  8183. router.route(url);
  8184. });
  8185. },
  8186. /**
  8187. Called when the Application has become ready.
  8188. The call will be delayed until the DOM has become ready.
  8189. */
  8190. ready: Ember.K,
  8191. /** @private */
  8192. willDestroy: function() {
  8193. get(this, 'eventDispatcher').destroy();
  8194. if (this._createdRouter) { this._createdRouter.destroy(); }
  8195. if (this._createdApplicationView) { this._createdApplicationView.destroy(); }
  8196. },
  8197. registerInjection: function(options) {
  8198. this.constructor.registerInjection(options);
  8199. }
  8200. });
  8201. Ember.Application.reopenClass({
  8202. concatenatedProperties: ['injections'],
  8203. injections: Ember.A(),
  8204. registerInjection: function(options) {
  8205. var injections = get(this, 'injections'),
  8206. before = options.before,
  8207. name = options.name,
  8208. injection = options.injection,
  8209. location;
  8210. if (before) {
  8211. location = injections.find(function(item) {
  8212. if (item[0] === before) { return true; }
  8213. });
  8214. location = injections.indexOf(location);
  8215. } else {
  8216. location = get(injections, 'length');
  8217. }
  8218. injections.splice(location, 0, [name, injection]);
  8219. }
  8220. });
  8221. Ember.Application.registerInjection({
  8222. name: 'controllers',
  8223. injection: function(app, router, property) {
  8224. if (!/^[A-Z].*Controller$/.test(property)) { return; }
  8225. var name = property.charAt(0).toLowerCase() + property.substr(1),
  8226. controller = app[property].create();
  8227. router.set(name, controller);
  8228. controller.setProperties({
  8229. target: router,
  8230. controllers: router,
  8231. namespace: app
  8232. });
  8233. }
  8234. });
  8235. })();
  8236. (function() {
  8237. var get = Ember.get, set = Ember.set;
  8238. /**
  8239. This file implements the `location` API used by Ember's router.
  8240. That API is:
  8241. getURL: returns the current URL
  8242. setURL(path): sets the current URL
  8243. onUpdateURL(callback): triggers the callback when the URL changes
  8244. formatURL(url): formats `url` to be placed into `href` attribute
  8245. Calling setURL will not trigger onUpdateURL callbacks.
  8246. TODO: This, as well as the Ember.Location documentation below, should
  8247. perhaps be moved so that it's visible in the JsDoc output.
  8248. */
  8249. /**
  8250. @class
  8251. Ember.Location returns an instance of the correct implementation of
  8252. the `location` API.
  8253. You can pass it a `implementation` ('hash', 'history', 'none') to force a
  8254. particular implementation.
  8255. */
  8256. Ember.Location = {
  8257. create: function(options) {
  8258. var implementation = options && options.implementation;
  8259. Ember.assert("Ember.Location.create: you must specify a 'implementation' option", !!implementation);
  8260. var implementationClass = this.implementations[implementation];
  8261. Ember.assert("Ember.Location.create: " + implementation + " is not a valid implementation", !!implementationClass);
  8262. return implementationClass.create.apply(implementationClass, arguments);
  8263. },
  8264. registerImplementation: function(name, implementation) {
  8265. this.implementations[name] = implementation;
  8266. },
  8267. implementations: {}
  8268. };
  8269. })();
  8270. (function() {
  8271. var get = Ember.get, set = Ember.set;
  8272. /**
  8273. @class
  8274. Ember.HashLocation implements the location API using the browser's
  8275. hash. At present, it relies on a hashchange event existing in the
  8276. browser.
  8277. @extends Ember.Object
  8278. */
  8279. Ember.HashLocation = Ember.Object.extend(
  8280. /** @scope Ember.HashLocation.prototype */ {
  8281. /** @private */
  8282. init: function() {
  8283. set(this, 'location', get(this, 'location') || window.location);
  8284. },
  8285. /**
  8286. @private
  8287. Returns the current `location.hash`, minus the '#' at the front.
  8288. */
  8289. getURL: function() {
  8290. return get(this, 'location').hash.substr(1);
  8291. },
  8292. /**
  8293. @private
  8294. Set the `location.hash` and remembers what was set. This prevents
  8295. `onUpdateURL` callbacks from triggering when the hash was set by
  8296. `HashLocation`.
  8297. */
  8298. setURL: function(path) {
  8299. get(this, 'location').hash = path;
  8300. set(this, 'lastSetURL', path);
  8301. },
  8302. /**
  8303. @private
  8304. Register a callback to be invoked when the hash changes. These
  8305. callbacks will execute when the user presses the back or forward
  8306. button, but not after `setURL` is invoked.
  8307. */
  8308. onUpdateURL: function(callback) {
  8309. var self = this;
  8310. var guid = Ember.guidFor(this);
  8311. Ember.$(window).bind('hashchange.ember-location-'+guid, function() {
  8312. var path = location.hash.substr(1);
  8313. if (get(self, 'lastSetURL') === path) { return; }
  8314. set(self, 'lastSetURL', null);
  8315. callback(location.hash.substr(1));
  8316. });
  8317. },
  8318. /**
  8319. @private
  8320. Given a URL, formats it to be placed into the page as part
  8321. of an element's `href` attribute.
  8322. This is used, for example, when using the {{action}} helper
  8323. to generate a URL based on an event.
  8324. */
  8325. formatURL: function(url) {
  8326. return '#'+url;
  8327. },
  8328. /** @private */
  8329. willDestroy: function() {
  8330. var guid = Ember.guidFor(this);
  8331. Ember.$(window).unbind('hashchange.ember-location-'+guid);
  8332. }
  8333. });
  8334. Ember.Location.registerImplementation('hash', Ember.HashLocation);
  8335. })();
  8336. (function() {
  8337. var get = Ember.get, set = Ember.set;
  8338. /**
  8339. @class
  8340. Ember.HistoryLocation implements the location API using the browser's
  8341. history.pushState API.
  8342. @extends Ember.Object
  8343. */
  8344. Ember.HistoryLocation = Ember.Object.extend(
  8345. /** @scope Ember.HistoryLocation.prototype */ {
  8346. /** @private */
  8347. init: function() {
  8348. set(this, 'location', get(this, 'location') || window.location);
  8349. set(this, '_initialURL', get(this, 'location').pathname);
  8350. },
  8351. /**
  8352. Will be pre-pended to path upon state change
  8353. */
  8354. rootURL: '/',
  8355. /**
  8356. @private
  8357. Used to give history a starting reference
  8358. */
  8359. _initialURL: null,
  8360. /**
  8361. @private
  8362. Returns the current `location.pathname`.
  8363. */
  8364. getURL: function() {
  8365. return get(this, 'location').pathname;
  8366. },
  8367. /**
  8368. @private
  8369. Uses `history.pushState` to update the url without a page reload.
  8370. */
  8371. setURL: function(path) {
  8372. var state = window.history.state,
  8373. initialURL = get(this, '_initialURL');
  8374. path = this.formatPath(path);
  8375. if ((initialURL !== path && !state) || (state && state.path !== path)) {
  8376. window.history.pushState({ path: path }, null, path);
  8377. }
  8378. },
  8379. /**
  8380. @private
  8381. Register a callback to be invoked whenever the browser
  8382. history changes, including using forward and back buttons.
  8383. */
  8384. onUpdateURL: function(callback) {
  8385. var guid = Ember.guidFor(this);
  8386. Ember.$(window).bind('popstate.ember-location-'+guid, function(e) {
  8387. callback(location.pathname);
  8388. });
  8389. },
  8390. /**
  8391. @private
  8392. returns the given path appended to rootURL
  8393. */
  8394. formatPath: function(path) {
  8395. var rootURL = get(this, 'rootURL');
  8396. if (path !== '') {
  8397. rootURL = rootURL.replace(/\/$/, '');
  8398. }
  8399. return rootURL + path;
  8400. },
  8401. /**
  8402. @private
  8403. Used when using {{action}} helper. Since no formatting
  8404. is required we just return the url given.
  8405. */
  8406. formatURL: function(url) {
  8407. return url;
  8408. },
  8409. /** @private */
  8410. willDestroy: function() {
  8411. var guid = Ember.guidFor(this);
  8412. Ember.$(window).unbind('popstate.ember-location-'+guid);
  8413. }
  8414. });
  8415. Ember.Location.registerImplementation('history', Ember.HistoryLocation);
  8416. })();
  8417. (function() {
  8418. var get = Ember.get, set = Ember.set;
  8419. /**
  8420. @class
  8421. Ember.NoneLocation does not interact with the browser. It is useful for
  8422. testing, or when you need to manage state with your Router, but temporarily
  8423. don't want it to muck with the URL (for example when you embed your
  8424. application in a larger page).
  8425. @extends Ember.Object
  8426. */
  8427. Ember.NoneLocation = Ember.Object.extend(
  8428. /** @scope Ember.NoneLocation.prototype */ {
  8429. path: '',
  8430. getURL: function() {
  8431. return get(this, 'path');
  8432. },
  8433. setURL: function(path) {
  8434. set(this, 'path', path);
  8435. },
  8436. onUpdateURL: function(callback) {
  8437. // We are not wired up to the browser, so we'll never trigger the callback.
  8438. },
  8439. formatURL: function(url) {
  8440. // The return value is not overly meaningful, but we do not want to throw
  8441. // errors when test code renders templates containing {{action href=true}}
  8442. // helpers.
  8443. return url;
  8444. }
  8445. });
  8446. Ember.Location.registerImplementation('none', Ember.NoneLocation);
  8447. })();
  8448. (function() {
  8449. })();
  8450. (function() {
  8451. })();
  8452. (function() {
  8453. // ==========================================================================
  8454. // Project: Ember - JavaScript Application Framework
  8455. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  8456. // Portions ©2008-2011 Apple Inc. All rights reserved.
  8457. // License: Licensed under MIT license (see license.js)
  8458. // ==========================================================================
  8459. Ember.assert("Ember Views require jQuery 1.7", window.jQuery && (window.jQuery().jquery.match(/^1\.7(\.\d+)?(pre|rc\d?)?/) || Ember.ENV.FORCE_JQUERY));
  8460. Ember.$ = window.jQuery;
  8461. })();
  8462. (function() {
  8463. // ==========================================================================
  8464. // Project: Ember - JavaScript Application Framework
  8465. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  8466. // Portions ©2008-2011 Apple Inc. All rights reserved.
  8467. // License: Licensed under MIT license (see license.js)
  8468. // ==========================================================================
  8469. // http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#dndevents
  8470. var dragEvents = Ember.String.w('dragstart drag dragenter dragleave dragover drop dragend');
  8471. // Copies the `dataTransfer` property from a browser event object onto the
  8472. // jQuery event object for the specified events
  8473. Ember.EnumerableUtils.forEach(dragEvents, function(eventName) {
  8474. Ember.$.event.fixHooks[eventName] = { props: ['dataTransfer'] };
  8475. });
  8476. })();
  8477. (function() {
  8478. // ==========================================================================
  8479. // Project: Ember - JavaScript Application Framework
  8480. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  8481. // Portions ©2008-2011 Apple Inc. All rights reserved.
  8482. // License: Licensed under MIT license (see license.js)
  8483. // ==========================================================================
  8484. var get = Ember.get, set = Ember.set;
  8485. var indexOf = Ember.ArrayPolyfills.indexOf;
  8486. /** @private */
  8487. var ClassSet = function() {
  8488. this.seen = {};
  8489. this.list = [];
  8490. };
  8491. ClassSet.prototype = {
  8492. add: function(string) {
  8493. if (string in this.seen) { return; }
  8494. this.seen[string] = true;
  8495. this.list.push(string);
  8496. },
  8497. toDOM: function() {
  8498. return this.list.join(" ");
  8499. }
  8500. };
  8501. /**
  8502. @class
  8503. Ember.RenderBuffer gathers information regarding the a view and generates the
  8504. final representation. Ember.RenderBuffer will generate HTML which can be pushed
  8505. to the DOM.
  8506. @extends Ember.Object
  8507. */
  8508. Ember.RenderBuffer = function(tagName) {
  8509. return new Ember._RenderBuffer(tagName);
  8510. };
  8511. Ember._RenderBuffer = function(tagName) {
  8512. this.elementTag = tagName;
  8513. this.childBuffers = [];
  8514. };
  8515. Ember._RenderBuffer.prototype =
  8516. /** @scope Ember.RenderBuffer.prototype */ {
  8517. /**
  8518. Array of class-names which will be applied in the class="" attribute
  8519. You should not maintain this array yourself, rather, you should use
  8520. the addClass() method of Ember.RenderBuffer.
  8521. @type Array
  8522. @default []
  8523. */
  8524. elementClasses: null,
  8525. /**
  8526. The id in of the element, to be applied in the id="" attribute
  8527. You should not set this property yourself, rather, you should use
  8528. the id() method of Ember.RenderBuffer.
  8529. @type String
  8530. @default null
  8531. */
  8532. elementId: null,
  8533. /**
  8534. A hash keyed on the name of the attribute and whose value will be
  8535. applied to that attribute. For example, if you wanted to apply a
  8536. data-view="Foo.bar" property to an element, you would set the
  8537. elementAttributes hash to {'data-view':'Foo.bar'}
  8538. You should not maintain this hash yourself, rather, you should use
  8539. the attr() method of Ember.RenderBuffer.
  8540. @type Hash
  8541. @default {}
  8542. */
  8543. elementAttributes: null,
  8544. /**
  8545. The tagname of the element an instance of Ember.RenderBuffer represents.
  8546. Usually, this gets set as the first parameter to Ember.RenderBuffer. For
  8547. example, if you wanted to create a `p` tag, then you would call
  8548. Ember.RenderBuffer('p')
  8549. @type String
  8550. @default null
  8551. */
  8552. elementTag: null,
  8553. /**
  8554. A hash keyed on the name of the style attribute and whose value will
  8555. be applied to that attribute. For example, if you wanted to apply a
  8556. background-color:black;" style to an element, you would set the
  8557. elementStyle hash to {'background-color':'black'}
  8558. You should not maintain this hash yourself, rather, you should use
  8559. the style() method of Ember.RenderBuffer.
  8560. @type Hash
  8561. @default {}
  8562. */
  8563. elementStyle: null,
  8564. /**
  8565. Nested RenderBuffers will set this to their parent RenderBuffer
  8566. instance.
  8567. @type Ember._RenderBuffer
  8568. */
  8569. parentBuffer: null,
  8570. /**
  8571. Adds a string of HTML to the RenderBuffer.
  8572. @param {String} string HTML to push into the buffer
  8573. @returns {Ember.RenderBuffer} this
  8574. */
  8575. push: function(string) {
  8576. this.childBuffers.push(String(string));
  8577. return this;
  8578. },
  8579. /**
  8580. Adds a class to the buffer, which will be rendered to the class attribute.
  8581. @param {String} className Class name to add to the buffer
  8582. @returns {Ember.RenderBuffer} this
  8583. */
  8584. addClass: function(className) {
  8585. // lazily create elementClasses
  8586. var elementClasses = this.elementClasses = (this.elementClasses || new ClassSet());
  8587. this.elementClasses.add(className);
  8588. return this;
  8589. },
  8590. /**
  8591. Sets the elementID to be used for the element.
  8592. @param {String} id
  8593. @returns {Ember.RenderBuffer} this
  8594. */
  8595. id: function(id) {
  8596. this.elementId = id;
  8597. return this;
  8598. },
  8599. // duck type attribute functionality like jQuery so a render buffer
  8600. // can be used like a jQuery object in attribute binding scenarios.
  8601. /**
  8602. Adds an attribute which will be rendered to the element.
  8603. @param {String} name The name of the attribute
  8604. @param {String} value The value to add to the attribute
  8605. @returns {Ember.RenderBuffer|String} this or the current attribute value
  8606. */
  8607. attr: function(name, value) {
  8608. var attributes = this.elementAttributes = (this.elementAttributes || {});
  8609. if (arguments.length === 1) {
  8610. return attributes[name];
  8611. } else {
  8612. attributes[name] = value;
  8613. }
  8614. return this;
  8615. },
  8616. /**
  8617. Remove an attribute from the list of attributes to render.
  8618. @param {String} name The name of the attribute
  8619. @returns {Ember.RenderBuffer} this
  8620. */
  8621. removeAttr: function(name) {
  8622. var attributes = this.elementAttributes;
  8623. if (attributes) { delete attributes[name]; }
  8624. return this;
  8625. },
  8626. /**
  8627. Adds a style to the style attribute which will be rendered to the element.
  8628. @param {String} name Name of the style
  8629. @param {String} value
  8630. @returns {Ember.RenderBuffer} this
  8631. */
  8632. style: function(name, value) {
  8633. var style = this.elementStyle = (this.elementStyle || {});
  8634. this.elementStyle[name] = value;
  8635. return this;
  8636. },
  8637. /**
  8638. Create a new child render buffer from a parent buffer. Optionally set
  8639. additional properties on the buffer. Optionally invoke a callback
  8640. with the newly created buffer.
  8641. This is a primitive method used by other public methods: `begin`,
  8642. `prepend`, `replaceWith`, `insertAfter`.
  8643. @private
  8644. @param {String} tagName Tag name to use for the child buffer's element
  8645. @param {Ember._RenderBuffer} parent The parent render buffer that this
  8646. buffer should be appended to.
  8647. @param {Function} fn A callback to invoke with the newly created buffer.
  8648. @param {Object} other Additional properties to add to the newly created
  8649. buffer.
  8650. */
  8651. newBuffer: function(tagName, parent, fn, other) {
  8652. var buffer = new Ember._RenderBuffer(tagName);
  8653. buffer.parentBuffer = parent;
  8654. if (other) { Ember.$.extend(buffer, other); }
  8655. if (fn) { fn.call(this, buffer); }
  8656. return buffer;
  8657. },
  8658. /**
  8659. Replace the current buffer with a new buffer. This is a primitive
  8660. used by `remove`, which passes `null` for `newBuffer`, and `replaceWith`,
  8661. which passes the new buffer it created.
  8662. @private
  8663. @param {Ember._RenderBuffer} buffer The buffer to insert in place of
  8664. the existing buffer.
  8665. */
  8666. replaceWithBuffer: function(newBuffer) {
  8667. var parent = this.parentBuffer;
  8668. if (!parent) { return; }
  8669. var childBuffers = parent.childBuffers;
  8670. var index = indexOf.call(childBuffers, this);
  8671. if (newBuffer) {
  8672. childBuffers.splice(index, 1, newBuffer);
  8673. } else {
  8674. childBuffers.splice(index, 1);
  8675. }
  8676. },
  8677. /**
  8678. Creates a new Ember.RenderBuffer object with the provided tagName as
  8679. the element tag and with its parentBuffer property set to the current
  8680. Ember.RenderBuffer.
  8681. @param {String} tagName Tag name to use for the child buffer's element
  8682. @returns {Ember.RenderBuffer} A new RenderBuffer object
  8683. */
  8684. begin: function(tagName) {
  8685. return this.newBuffer(tagName, this, function(buffer) {
  8686. this.childBuffers.push(buffer);
  8687. });
  8688. },
  8689. /**
  8690. Prepend a new child buffer to the current render buffer.
  8691. @param {String} tagName Tag name to use for the child buffer's element
  8692. */
  8693. prepend: function(tagName) {
  8694. return this.newBuffer(tagName, this, function(buffer) {
  8695. this.childBuffers.splice(0, 0, buffer);
  8696. });
  8697. },
  8698. /**
  8699. Replace the current buffer with a new render buffer.
  8700. @param {String} tagName Tag name to use for the new buffer's element
  8701. */
  8702. replaceWith: function(tagName) {
  8703. var parentBuffer = this.parentBuffer;
  8704. return this.newBuffer(tagName, parentBuffer, function(buffer) {
  8705. this.replaceWithBuffer(buffer);
  8706. });
  8707. },
  8708. /**
  8709. Insert a new render buffer after the current render buffer.
  8710. @param {String} tagName Tag name to use for the new buffer's element
  8711. */
  8712. insertAfter: function(tagName) {
  8713. var parentBuffer = get(this, 'parentBuffer');
  8714. return this.newBuffer(tagName, parentBuffer, function(buffer) {
  8715. var siblings = parentBuffer.childBuffers;
  8716. var index = indexOf.call(siblings, this);
  8717. siblings.splice(index + 1, 0, buffer);
  8718. });
  8719. },
  8720. /**
  8721. Closes the current buffer and adds its content to the parentBuffer.
  8722. @returns {Ember.RenderBuffer} The parentBuffer, if one exists. Otherwise, this
  8723. */
  8724. end: function() {
  8725. var parent = this.parentBuffer;
  8726. return parent || this;
  8727. },
  8728. remove: function() {
  8729. this.replaceWithBuffer(null);
  8730. },
  8731. /**
  8732. @returns {DOMElement} The element corresponding to the generated HTML
  8733. of this buffer
  8734. */
  8735. element: function() {
  8736. return Ember.$(this.string())[0];
  8737. },
  8738. /**
  8739. Generates the HTML content for this buffer.
  8740. @returns {String} The generated HTMl
  8741. */
  8742. string: function() {
  8743. var content = '', tag = this.elementTag, openTag;
  8744. if (tag) {
  8745. var id = this.elementId,
  8746. classes = this.elementClasses,
  8747. attrs = this.elementAttributes,
  8748. style = this.elementStyle,
  8749. styleBuffer = '', prop;
  8750. openTag = ["<" + tag];
  8751. if (id) { openTag.push('id="' + this._escapeAttribute(id) + '"'); }
  8752. if (classes) { openTag.push('class="' + this._escapeAttribute(classes.toDOM()) + '"'); }
  8753. if (style) {
  8754. for (prop in style) {
  8755. if (style.hasOwnProperty(prop)) {
  8756. styleBuffer += (prop + ':' + this._escapeAttribute(style[prop]) + ';');
  8757. }
  8758. }
  8759. openTag.push('style="' + styleBuffer + '"');
  8760. }
  8761. if (attrs) {
  8762. for (prop in attrs) {
  8763. if (attrs.hasOwnProperty(prop)) {
  8764. openTag.push(prop + '="' + this._escapeAttribute(attrs[prop]) + '"');
  8765. }
  8766. }
  8767. }
  8768. openTag = openTag.join(" ") + '>';
  8769. }
  8770. var childBuffers = this.childBuffers;
  8771. Ember.ArrayPolyfills.forEach.call(childBuffers, function(buffer) {
  8772. var stringy = typeof buffer === 'string';
  8773. content += (stringy ? buffer : buffer.string());
  8774. });
  8775. if (tag) {
  8776. return openTag + content + "</" + tag + ">";
  8777. } else {
  8778. return content;
  8779. }
  8780. },
  8781. _escapeAttribute: function(value) {
  8782. // Stolen shamelessly from Handlebars
  8783. var escape = {
  8784. "<": "&lt;",
  8785. ">": "&gt;",
  8786. '"': "&quot;",
  8787. "'": "&#x27;",
  8788. "`": "&#x60;"
  8789. };
  8790. var badChars = /&(?!\w+;)|[<>"'`]/g;
  8791. var possible = /[&<>"'`]/;
  8792. var escapeChar = function(chr) {
  8793. return escape[chr] || "&amp;";
  8794. };
  8795. var string = value.toString();
  8796. if(!possible.test(string)) { return string; }
  8797. return string.replace(badChars, escapeChar);
  8798. }
  8799. };
  8800. })();
  8801. (function() {
  8802. // ==========================================================================
  8803. // Project: Ember - JavaScript Application Framework
  8804. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  8805. // Portions ©2008-2011 Apple Inc. All rights reserved.
  8806. // License: Licensed under MIT license (see license.js)
  8807. // ==========================================================================
  8808. var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt;
  8809. /**
  8810. @ignore
  8811. Ember.EventDispatcher handles delegating browser events to their corresponding
  8812. Ember.Views. For example, when you click on a view, Ember.EventDispatcher ensures
  8813. that that view's `mouseDown` method gets called.
  8814. */
  8815. Ember.EventDispatcher = Ember.Object.extend(
  8816. /** @scope Ember.EventDispatcher.prototype */{
  8817. /**
  8818. @private
  8819. The root DOM element to which event listeners should be attached. Event
  8820. listeners will be attached to the document unless this is overridden.
  8821. Can be specified as a DOMElement or a selector string.
  8822. The default body is a string since this may be evaluated before document.body
  8823. exists in the DOM.
  8824. @type DOMElement
  8825. @default 'body'
  8826. */
  8827. rootElement: 'body',
  8828. /**
  8829. @private
  8830. Sets up event listeners for standard browser events.
  8831. This will be called after the browser sends a DOMContentReady event. By
  8832. default, it will set up all of the listeners on the document body. If you
  8833. would like to register the listeners on a different element, set the event
  8834. dispatcher's `root` property.
  8835. */
  8836. setup: function(addedEvents) {
  8837. var event, events = {
  8838. touchstart : 'touchStart',
  8839. touchmove : 'touchMove',
  8840. touchend : 'touchEnd',
  8841. touchcancel : 'touchCancel',
  8842. keydown : 'keyDown',
  8843. keyup : 'keyUp',
  8844. keypress : 'keyPress',
  8845. mousedown : 'mouseDown',
  8846. mouseup : 'mouseUp',
  8847. contextmenu : 'contextMenu',
  8848. click : 'click',
  8849. dblclick : 'doubleClick',
  8850. mousemove : 'mouseMove',
  8851. focusin : 'focusIn',
  8852. focusout : 'focusOut',
  8853. mouseenter : 'mouseEnter',
  8854. mouseleave : 'mouseLeave',
  8855. submit : 'submit',
  8856. input : 'input',
  8857. change : 'change',
  8858. dragstart : 'dragStart',
  8859. drag : 'drag',
  8860. dragenter : 'dragEnter',
  8861. dragleave : 'dragLeave',
  8862. dragover : 'dragOver',
  8863. drop : 'drop',
  8864. dragend : 'dragEnd'
  8865. };
  8866. Ember.$.extend(events, addedEvents || {});
  8867. var rootElement = Ember.$(get(this, 'rootElement'));
  8868. Ember.assert(fmt('You cannot use the same root element (%@) multiple times in an Ember.Application', [rootElement.selector || rootElement[0].tagName]), !rootElement.is('.ember-application'));
  8869. Ember.assert('You cannot make a new Ember.Application using a root element that is a descendent of an existing Ember.Application', !rootElement.closest('.ember-application').length);
  8870. Ember.assert('You cannot make a new Ember.Application using a root element that is an ancestor of an existing Ember.Application', !rootElement.find('.ember-application').length);
  8871. rootElement.addClass('ember-application');
  8872. Ember.assert('Unable to add "ember-application" class to rootElement. Make sure you set rootElement to the body or an element in the body.', rootElement.is('.ember-application'));
  8873. for (event in events) {
  8874. if (events.hasOwnProperty(event)) {
  8875. this.setupHandler(rootElement, event, events[event]);
  8876. }
  8877. }
  8878. },
  8879. /**
  8880. @private
  8881. Registers an event listener on the document. If the given event is
  8882. triggered, the provided event handler will be triggered on the target
  8883. view.
  8884. If the target view does not implement the event handler, or if the handler
  8885. returns false, the parent view will be called. The event will continue to
  8886. bubble to each successive parent view until it reaches the top.
  8887. For example, to have the `mouseDown` method called on the target view when
  8888. a `mousedown` event is received from the browser, do the following:
  8889. setupHandler('mousedown', 'mouseDown');
  8890. @param {String} event the browser-originated event to listen to
  8891. @param {String} eventName the name of the method to call on the view
  8892. */
  8893. setupHandler: function(rootElement, event, eventName) {
  8894. var self = this;
  8895. rootElement.delegate('.ember-view', event + '.ember', function(evt, triggeringManager) {
  8896. var view = Ember.View.views[this.id],
  8897. result = true, manager = null;
  8898. manager = self._findNearestEventManager(view,eventName);
  8899. if (manager && manager !== triggeringManager) {
  8900. result = self._dispatchEvent(manager, evt, eventName, view);
  8901. } else if (view) {
  8902. result = self._bubbleEvent(view,evt,eventName);
  8903. } else {
  8904. evt.stopPropagation();
  8905. }
  8906. return result;
  8907. });
  8908. rootElement.delegate('[data-ember-action]', event + '.ember', function(evt) {
  8909. var actionId = Ember.$(evt.currentTarget).attr('data-ember-action'),
  8910. action = Ember.Handlebars.ActionHelper.registeredActions[actionId],
  8911. handler = action.handler;
  8912. if (action.eventName === eventName) {
  8913. return handler(evt);
  8914. }
  8915. });
  8916. },
  8917. /** @private */
  8918. _findNearestEventManager: function(view, eventName) {
  8919. var manager = null;
  8920. while (view) {
  8921. manager = get(view, 'eventManager');
  8922. if (manager && manager[eventName]) { break; }
  8923. view = get(view, 'parentView');
  8924. }
  8925. return manager;
  8926. },
  8927. /** @private */
  8928. _dispatchEvent: function(object, evt, eventName, view) {
  8929. var result = true;
  8930. var handler = object[eventName];
  8931. if (Ember.typeOf(handler) === 'function') {
  8932. result = handler.call(object, evt, view);
  8933. // Do not preventDefault in eventManagers.
  8934. evt.stopPropagation();
  8935. }
  8936. else {
  8937. result = this._bubbleEvent(view, evt, eventName);
  8938. }
  8939. return result;
  8940. },
  8941. /** @private */
  8942. _bubbleEvent: function(view, evt, eventName) {
  8943. return Ember.run(function() {
  8944. return view.handleEvent(eventName, evt);
  8945. });
  8946. },
  8947. /** @private */
  8948. destroy: function() {
  8949. var rootElement = get(this, 'rootElement');
  8950. Ember.$(rootElement).undelegate('.ember').removeClass('ember-application');
  8951. return this._super();
  8952. }
  8953. });
  8954. })();
  8955. (function() {
  8956. // ==========================================================================
  8957. // Project: Ember - JavaScript Application Framework
  8958. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  8959. // Portions ©2008-2011 Apple Inc. All rights reserved.
  8960. // License: Licensed under MIT license (see license.js)
  8961. // ==========================================================================
  8962. // Add a new named queue for rendering views that happens
  8963. // after bindings have synced.
  8964. var queues = Ember.run.queues;
  8965. queues.splice(Ember.$.inArray('actions', queues)+1, 0, 'render');
  8966. })();
  8967. (function() {
  8968. var get = Ember.get, set = Ember.set;
  8969. Ember.ControllerMixin.reopen({
  8970. target: null,
  8971. controllers: null,
  8972. namespace: null,
  8973. view: null,
  8974. /**
  8975. `connectOutlet` creates a new instance of a provided view
  8976. class, wires it up to its associated controller, and
  8977. assigns the new view to a property on the current controller.
  8978. The purpose of this method is to enable views that use
  8979. outlets to quickly assign new views for a given outlet.
  8980. For example, an application view's template may look like
  8981. this:
  8982. <h1>My Blog</h1>
  8983. {{outlet}}
  8984. The view for this outlet is specified by assigning a
  8985. `view` property to the application's controller. The
  8986. following code will assign a new `App.PostsView` to
  8987. that outlet:
  8988. applicationController.connectOutlet('posts');
  8989. In general, you will also want to assign a controller
  8990. to the newly created view. By convention, a controller
  8991. named `postsController` will be assigned as the view's
  8992. controller.
  8993. In an application initialized using `app.initialize(router)`,
  8994. `connectOutlet` will look for `postsController` on the
  8995. router. The initialization process will automatically
  8996. create an instance of `App.PostsController` called
  8997. `postsController`, so you don't need to do anything
  8998. beyond `connectOutlet` to assign your view and wire it
  8999. up to its associated controller.
  9000. You can supply a `content` for the controller by supplying
  9001. a final argument after the view class:
  9002. applicationController.connectOutlet('posts', App.Post.find());
  9003. You can specify a particular outlet to use. For example, if your main
  9004. template looks like:
  9005. <h1>My Blog</h1>
  9006. {{outlet master}}
  9007. {{outlet detail}}
  9008. You can assign an `App.PostsView` to the master outlet:
  9009. applicationController.connectOutlet({
  9010. name: 'posts',
  9011. outletName: 'master',
  9012. context: App.Post.find()
  9013. });
  9014. You can write this as:
  9015. applicationController.connectOutlet('master', 'posts', App.Post.find());
  9016. @param {String} outletName a name for the outlet to set
  9017. @param {String} name a view/controller pair name
  9018. @param {Object} context a context object to assign to the
  9019. controller's `content` property, if a controller can be
  9020. found (optional)
  9021. */
  9022. connectOutlet: function(name, context) {
  9023. // Normalize arguments. Supported arguments:
  9024. //
  9025. // name
  9026. // name, context
  9027. // outletName, name
  9028. // outletName, name, context
  9029. // options
  9030. //
  9031. // The options hash has the following keys:
  9032. //
  9033. // name: the name of the controller and view
  9034. // to use. If this is passed, the name
  9035. // determines the view and controller.
  9036. // outletName: the name of the outlet to
  9037. // fill in. default: 'view'
  9038. // viewClass: the class of the view to instantiate
  9039. // controller: the controller instance to pass
  9040. // to the view
  9041. // context: an object that should become the
  9042. // controller's `content` and thus the
  9043. // template's context.
  9044. var outletName, viewClass, view, controller, options;
  9045. if (Ember.typeOf(context) === 'string') {
  9046. outletName = name;
  9047. name = context;
  9048. context = arguments[2];
  9049. }
  9050. if (arguments.length === 1) {
  9051. if (Ember.typeOf(name) === 'object') {
  9052. options = name;
  9053. outletName = options.outletName;
  9054. name = options.name;
  9055. viewClass = options.viewClass;
  9056. controller = options.controller;
  9057. context = options.context;
  9058. }
  9059. } else {
  9060. options = {};
  9061. }
  9062. outletName = outletName || 'view';
  9063. Ember.assert("You must supply a name or a view class to connectOutlets, but not both", (!!name && !viewClass && !controller) || (!name && !!viewClass));
  9064. if (name) {
  9065. var namespace = get(this, 'namespace'),
  9066. controllers = get(this, 'controllers');
  9067. var viewClassName = name.charAt(0).toUpperCase() + name.substr(1) + "View";
  9068. viewClass = get(namespace, viewClassName);
  9069. controller = get(controllers, name + 'Controller');
  9070. Ember.assert("The name you supplied " + name + " did not resolve to a view " + viewClassName, !!viewClass);
  9071. Ember.assert("The name you supplied " + name + " did not resolve to a controller " + name + 'Controller', (!!controller && !!context) || !context);
  9072. }
  9073. if (controller && context) { controller.set('content', context); }
  9074. view = viewClass.create();
  9075. if (controller) { set(view, 'controller', controller); }
  9076. set(this, outletName, view);
  9077. return view;
  9078. },
  9079. /**
  9080. Convenience method to connect controllers. This method makes other controllers
  9081. available on the controller the method was invoked on.
  9082. For example, to make the `personController` and the `postController` available
  9083. on the `overviewController`, you would call:
  9084. overviewController.connectControllers('person', 'post');
  9085. @param {String...} controllerNames the controllers to make available
  9086. */
  9087. connectControllers: function() {
  9088. var controllers = get(this, 'controllers'),
  9089. controllerNames = Array.prototype.slice.apply(arguments),
  9090. controllerName;
  9091. for (var i=0, l=controllerNames.length; i<l; i++) {
  9092. controllerName = controllerNames[i] + 'Controller';
  9093. set(this, controllerName, get(controllers, controllerName));
  9094. }
  9095. }
  9096. });
  9097. })();
  9098. (function() {
  9099. // ==========================================================================
  9100. // Project: Ember - JavaScript Application Framework
  9101. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  9102. // Portions ©2008-2011 Apple Inc. All rights reserved.
  9103. // License: Licensed under MIT license (see license.js)
  9104. // ==========================================================================
  9105. })();
  9106. (function() {
  9107. // ==========================================================================
  9108. // Project: Ember - JavaScript Application Framework
  9109. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  9110. // Portions ©2008-2011 Apple Inc. All rights reserved.
  9111. // License: Licensed under MIT license (see license.js)
  9112. // ==========================================================================
  9113. var get = Ember.get, set = Ember.set, addObserver = Ember.addObserver;
  9114. var meta = Ember.meta, fmt = Ember.String.fmt;
  9115. var a_slice = [].slice;
  9116. var a_forEach = Ember.EnumerableUtils.forEach;
  9117. var childViewsProperty = Ember.computed(function() {
  9118. var childViews = this._childViews;
  9119. var ret = Ember.A();
  9120. a_forEach(childViews, function(view) {
  9121. if (view.isVirtual) {
  9122. ret.pushObjects(get(view, 'childViews'));
  9123. } else {
  9124. ret.push(view);
  9125. }
  9126. });
  9127. return ret;
  9128. }).property().cacheable();
  9129. var VIEW_PRESERVES_CONTEXT = Ember.VIEW_PRESERVES_CONTEXT;
  9130. Ember.warn("The way that the {{view}} helper affects templates is about to change. Previously, templates inside child views would use the new view as the context. Soon, views will preserve their parent context when rendering their template. You can opt-in early to the new behavior by setting `ENV.VIEW_PRESERVES_CONTEXT = true`. For more information, see https://gist.github.com/2494968. You should update your templates as soon as possible; this default will change soon, and the option will be eliminated entirely before the 1.0 release.", VIEW_PRESERVES_CONTEXT);
  9131. /**
  9132. @static
  9133. Global hash of shared templates. This will automatically be populated
  9134. by the build tools so that you can store your Handlebars templates in
  9135. separate files that get loaded into JavaScript at buildtime.
  9136. @type Hash
  9137. */
  9138. Ember.TEMPLATES = {};
  9139. var invokeForState = {
  9140. preRender: {},
  9141. inBuffer: {},
  9142. hasElement: {},
  9143. inDOM: {},
  9144. destroyed: {}
  9145. };
  9146. /**
  9147. @class
  9148. `Ember.View` is the class in Ember responsible for encapsulating templates of HTML
  9149. content, combining templates with data to render as sections of a page's DOM, and
  9150. registering and responding to user-initiated events.
  9151. ## HTML Tag
  9152. The default HTML tag name used for a view's DOM representation is `div`. This can be
  9153. customized by setting the `tagName` property. The following view class:
  9154. ParagraphView = Ember.View.extend({
  9155. tagName: 'em'
  9156. })
  9157. Would result in instances with the following HTML:
  9158. <em id="ember1" class="ember-view"></em>
  9159. ## HTML `class` Attribute
  9160. The HTML `class` attribute of a view's tag can be set by providing a `classNames` property
  9161. that is set to an array of strings:
  9162. MyView = Ember.View.extend({
  9163. classNames: ['my-class', 'my-other-class']
  9164. })
  9165. Will result in view instances with an HTML representation of:
  9166. <div id="ember1" class="ember-view my-class my-other-class"></div>
  9167. `class` attribute values can also be set by providing a `classNameBindings` property
  9168. set to an array of properties names for the view. The return value of these properties
  9169. will be added as part of the value for the view's `class` attribute. These properties
  9170. can be computed properties:
  9171. MyView = Ember.View.extend({
  9172. classNameBindings: ['propertyA', 'propertyB'],
  9173. propertyA: 'from-a',
  9174. propertyB: function(){
  9175. if(someLogic){ return 'from-b'; }
  9176. }.property()
  9177. })
  9178. Will result in view instances with an HTML representation of:
  9179. <div id="ember1" class="ember-view from-a from-b"></div>
  9180. If the value of a class name binding returns a boolean the property name itself
  9181. will be used as the class name if the property is true. The class name will
  9182. not be added if the value is `false` or `undefined`.
  9183. MyView = Ember.View.extend({
  9184. classNameBindings: ['hovered'],
  9185. hovered: true
  9186. })
  9187. Will result in view instances with an HTML representation of:
  9188. <div id="ember1" class="ember-view hovered"></div>
  9189. When using boolean class name bindings you can supply a string value other than the
  9190. property name for use as the `class` HTML attribute by appending the preferred value after
  9191. a ":" character when defining the binding:
  9192. MyView = Ember.View.extend({
  9193. classNameBindings: ['awesome:so-very-cool'],
  9194. awesome: true
  9195. })
  9196. Will result in view instances with an HTML representation of:
  9197. <div id="ember1" class="ember-view so-very-cool"></div>
  9198. Boolean value class name bindings whose property names are in a camelCase-style
  9199. format will be converted to a dasherized format:
  9200. MyView = Ember.View.extend({
  9201. classNameBindings: ['isUrgent'],
  9202. isUrgent: true
  9203. })
  9204. Will result in view instances with an HTML representation of:
  9205. <div id="ember1" class="ember-view is-urgent"></div>
  9206. Class name bindings can also refer to object values that are found by
  9207. traversing a path relative to the view itself:
  9208. MyView = Ember.View.extend({
  9209. classNameBindings: ['messages.empty']
  9210. messages: Ember.Object.create({
  9211. empty: true
  9212. })
  9213. })
  9214. Will result in view instances with an HTML representation of:
  9215. <div id="ember1" class="ember-view empty"></div>
  9216. If you want to add a class name for a property which evaluates to true and
  9217. and a different class name if it evaluates to false, you can pass a binding
  9218. like this:
  9219. // Applies 'enabled' class when isEnabled is true and 'disabled' when isEnabled is false
  9220. Ember.View.create({
  9221. classNameBindings: ['isEnabled:enabled:disabled']
  9222. isEnabled: true
  9223. });
  9224. Will result in view instances with an HTML representation of:
  9225. <div id="ember1" class="ember-view enabled"></div>
  9226. When isEnabled is `false`, the resulting HTML reprensentation looks like this:
  9227. <div id="ember1" class="ember-view disabled"></div>
  9228. This syntax offers the convenience to add a class if a property is `false`:
  9229. // Applies no class when isEnabled is true and class 'disabled' when isEnabled is false
  9230. Ember.View.create({
  9231. classNameBindings: ['isEnabled::disabled']
  9232. isEnabled: true
  9233. });
  9234. Will result in view instances with an HTML representation of:
  9235. <div id="ember1" class="ember-view"></div>
  9236. When the `isEnabled` property on the view is set to `false`, it will result
  9237. in view instances with an HTML representation of:
  9238. <div id="ember1" class="ember-view disabled"></div>
  9239. Updates to the the value of a class name binding will result in automatic update
  9240. of the HTML `class` attribute in the view's rendered HTML representation.
  9241. If the value becomes `false` or `undefined` the class name will be removed.
  9242. Both `classNames` and `classNameBindings` are concatenated properties.
  9243. See `Ember.Object` documentation for more information about concatenated properties.
  9244. ## HTML Attributes
  9245. The HTML attribute section of a view's tag can be set by providing an `attributeBindings`
  9246. property set to an array of property names on the view. The return value of these properties
  9247. will be used as the value of the view's HTML associated attribute:
  9248. AnchorView = Ember.View.extend({
  9249. tagName: 'a',
  9250. attributeBindings: ['href'],
  9251. href: 'http://google.com'
  9252. })
  9253. Will result in view instances with an HTML representation of:
  9254. <a id="ember1" class="ember-view" href="http://google.com"></a>
  9255. If the return value of an `attributeBindings` monitored property is a boolean
  9256. the property will follow HTML's pattern of repeating the attribute's name as
  9257. its value:
  9258. MyTextInput = Ember.View.extend({
  9259. tagName: 'input',
  9260. attributeBindings: ['disabled'],
  9261. disabled: true
  9262. })
  9263. Will result in view instances with an HTML representation of:
  9264. <input id="ember1" class="ember-view" disabled="disabled" />
  9265. `attributeBindings` can refer to computed properties:
  9266. MyTextInput = Ember.View.extend({
  9267. tagName: 'input',
  9268. attributeBindings: ['disabled'],
  9269. disabled: function(){
  9270. if (someLogic) {
  9271. return true;
  9272. } else {
  9273. return false;
  9274. }
  9275. }.property()
  9276. })
  9277. Updates to the the property of an attribute binding will result in automatic update
  9278. of the HTML attribute in the view's rendered HTML representation.
  9279. `attributeBindings` is a concatenated property. See `Ember.Object` documentation
  9280. for more information about concatenated properties.
  9281. ## Templates
  9282. The HTML contents of a view's rendered representation are determined by its template.
  9283. Templates can be any function that accepts an optional context parameter and returns
  9284. a string of HTML that will be inserted within the view's tag. Most
  9285. typically in Ember this function will be a compiled Ember.Handlebars template.
  9286. AView = Ember.View.extend({
  9287. template: Ember.Handlebars.compile('I am the template')
  9288. })
  9289. Will result in view instances with an HTML representation of:
  9290. <div id="ember1" class="ember-view">I am the template</div>
  9291. The default context of the compiled template will be the view instance itself:
  9292. AView = Ember.View.extend({
  9293. template: Ember.Handlebars.compile('Hello {{excitedGreeting}}')
  9294. })
  9295. aView = AView.create({
  9296. content: Ember.Object.create({
  9297. firstName: 'Barry'
  9298. })
  9299. excitedGreeting: function(){
  9300. return this.get("content.firstName") + "!!!"
  9301. }
  9302. })
  9303. Will result in an HTML representation of:
  9304. <div id="ember1" class="ember-view">Hello Barry!!!</div>
  9305. Within an Ember application is more common to define a Handlebars templates as
  9306. part of a page:
  9307. <script type='text/x-handlebars' data-template-name='some-template'>
  9308. Hello
  9309. </script>
  9310. And associate it by name using a view's `templateName` property:
  9311. AView = Ember.View.extend({
  9312. templateName: 'some-template'
  9313. })
  9314. Using a value for `templateName` that does not have a Handlebars template with a
  9315. matching `data-template-name` attribute will throw an error.
  9316. Assigning a value to both `template` and `templateName` properties will throw an error.
  9317. For views classes that may have a template later defined (e.g. as the block portion of a `{{view}}`
  9318. Handlebars helper call in another template or in a subclass), you can provide a `defaultTemplate`
  9319. property set to compiled template function. If a template is not later provided for the view
  9320. instance the `defaultTemplate` value will be used:
  9321. AView = Ember.View.extend({
  9322. defaultTemplate: Ember.Handlebars.compile('I was the default'),
  9323. template: null,
  9324. templateName: null
  9325. })
  9326. Will result in instances with an HTML representation of:
  9327. <div id="ember1" class="ember-view">I was the default</div>
  9328. If a `template` or `templateName` is provided it will take precedence over `defaultTemplate`:
  9329. AView = Ember.View.extend({
  9330. defaultTemplate: Ember.Handlebars.compile('I was the default')
  9331. })
  9332. aView = AView.create({
  9333. template: Ember.Handlebars.compile('I was the template, not default')
  9334. })
  9335. Will result in the following HTML representation when rendered:
  9336. <div id="ember1" class="ember-view">I was the template, not default</div>
  9337. ## Layouts
  9338. Views can have a secondary template that wraps their main template. Like
  9339. primary templates, layouts can be any function that accepts an optional context
  9340. parameter and returns a string of HTML that will be inserted inside view's tag. Views whose HTML
  9341. element is self closing (e.g. `<input />`) cannot have a layout and this property will be ignored.
  9342. Most typically in Ember a layout will be a compiled Ember.Handlebars template.
  9343. A view's layout can be set directly with the `layout` property or reference an
  9344. existing Handlebars template by name with the `layoutName` property.
  9345. A template used as a layout must contain a single use of the Handlebars `{{yield}}`
  9346. helper. The HTML contents of a view's rendered `template` will be inserted at this location:
  9347. AViewWithLayout = Ember.View.extend({
  9348. layout: Ember.Handlebars.compile("<div class='my-decorative-class'>{{yield}}</div>")
  9349. template: Ember.Handlebars.compile("I got wrapped"),
  9350. })
  9351. Will result in view instances with an HTML representation of:
  9352. <div id="ember1" class="ember-view">
  9353. <div class="my-decorative-class">
  9354. I got wrapped
  9355. </div>
  9356. </div>
  9357. See `Handlebars.helpers.yield` for more information.
  9358. ## Responding to Browser Events
  9359. Views can respond to user-initiated events in one of three ways: method implementation,
  9360. through an event manager, and through `{{action}}` helper use in their template or layout.
  9361. ### Method Implementation
  9362. Views can respond to user-initiated events by implementing a method that matches the
  9363. event name. A `jQuery.Event` object will be passed as the argument to this method.
  9364. AView = Ember.View.extend({
  9365. click: function(event){
  9366. // will be called when when an instance's
  9367. // rendered element is clicked
  9368. }
  9369. })
  9370. ### Event Managers
  9371. Views can define an object as their `eventManager` property. This object can then
  9372. implement methods that match the desired event names. Matching events that occur
  9373. on the view's rendered HTML or the rendered HTML of any of its DOM descendants
  9374. will trigger this method. A `jQuery.Event` object will be passed as the first
  9375. argument to the method and an `Ember.View` object as the second. The `Ember.View`
  9376. will be the view whose rendered HTML was interacted with. This may be the view with
  9377. the `eventManager` property or one of its descendent views.
  9378. AView = Ember.View.extend({
  9379. eventManager: Ember.Object.create({
  9380. doubleClick: function(event, view){
  9381. // will be called when when an instance's
  9382. // rendered element or any rendering
  9383. // of this views's descendent
  9384. // elements is clicked
  9385. }
  9386. })
  9387. })
  9388. An event defined for an event manager takes precedence over events of the same
  9389. name handled through methods on the view.
  9390. AView = Ember.View.extend({
  9391. mouseEnter: function(event){
  9392. // will never trigger.
  9393. },
  9394. eventManager: Ember.Object.create({
  9395. mouseEnter: function(event, view){
  9396. // takes presedence over AView#mouseEnter
  9397. }
  9398. })
  9399. })
  9400. Similarly a view's event manager will take precedence for events of any views
  9401. rendered as a descendent. A method name that matches an event name will not be called
  9402. if the view instance was rendered inside the HTML representation of a view that has
  9403. an `eventManager` property defined that handles events of the name. Events not handled
  9404. by the event manager will still trigger method calls on the descendent.
  9405. OuterView = Ember.View.extend({
  9406. template: Ember.Handlebars.compile("outer {{#view InnerView}}inner{{/view}} outer"),
  9407. eventManager: Ember.Object.create({
  9408. mouseEnter: function(event, view){
  9409. // view might be instance of either
  9410. // OutsideView or InnerView depending on
  9411. // where on the page the user interaction occured
  9412. }
  9413. })
  9414. })
  9415. InnerView = Ember.View.extend({
  9416. click: function(event){
  9417. // will be called if rendered inside
  9418. // an OuterView because OuterView's
  9419. // eventManager doesn't handle click events
  9420. },
  9421. mouseEnter: function(event){
  9422. // will never be called if rendered inside
  9423. // an OuterView.
  9424. }
  9425. })
  9426. ### Handlebars `{{action}}` Helper
  9427. See `Handlebars.helpers.action`.
  9428. ### Event Names
  9429. Possible events names for any of the responding approaches described above are:
  9430. Touch events: 'touchStart', 'touchMove', 'touchEnd', 'touchCancel'
  9431. Keyboard events: 'keyDown', 'keyUp', 'keyPress'
  9432. Mouse events: 'mouseDown', 'mouseUp', 'contextMenu', 'click', 'doubleClick', 'mouseMove',
  9433. 'focusIn', 'focusOut', 'mouseEnter', 'mouseLeave'
  9434. Form events: 'submit', 'change', 'focusIn', 'focusOut', 'input'
  9435. HTML5 drag and drop events: 'dragStart', 'drag', 'dragEnter', 'dragLeave', 'drop', 'dragEnd'
  9436. ## Handlebars `{{view}}` Helper
  9437. Other `Ember.View` instances can be included as part of a view's template by using the `{{view}}`
  9438. Handlebars helper. See `Handlebars.helpers.view` for additional information.
  9439. @extends Ember.Object
  9440. @extends Ember.Evented
  9441. */
  9442. Ember.View = Ember.Object.extend(Ember.Evented,
  9443. /** @scope Ember.View.prototype */ {
  9444. /** @private */
  9445. concatenatedProperties: ['classNames', 'classNameBindings', 'attributeBindings'],
  9446. /**
  9447. @type Boolean
  9448. @default true
  9449. @constant
  9450. */
  9451. isView: true,
  9452. // ..........................................................
  9453. // TEMPLATE SUPPORT
  9454. //
  9455. /**
  9456. The name of the template to lookup if no template is provided.
  9457. Ember.View will look for a template with this name in this view's
  9458. `templates` object. By default, this will be a global object
  9459. shared in `Ember.TEMPLATES`.
  9460. @type String
  9461. @default null
  9462. */
  9463. templateName: null,
  9464. /**
  9465. The name of the layout to lookup if no layout is provided.
  9466. Ember.View will look for a template with this name in this view's
  9467. `templates` object. By default, this will be a global object
  9468. shared in `Ember.TEMPLATES`.
  9469. @type String
  9470. @default null
  9471. */
  9472. layoutName: null,
  9473. /**
  9474. The hash in which to look for `templateName`.
  9475. @type Ember.Object
  9476. @default Ember.TEMPLATES
  9477. */
  9478. templates: Ember.TEMPLATES,
  9479. /**
  9480. The template used to render the view. This should be a function that
  9481. accepts an optional context parameter and returns a string of HTML that
  9482. will be inserted into the DOM relative to its parent view.
  9483. In general, you should set the `templateName` property instead of setting
  9484. the template yourself.
  9485. @field
  9486. @type Function
  9487. */
  9488. template: Ember.computed(function(key, value) {
  9489. if (value !== undefined) { return value; }
  9490. var templateName = get(this, 'templateName'),
  9491. template = this.templateForName(templateName, 'template');
  9492. return template || get(this, 'defaultTemplate');
  9493. }).property('templateName').cacheable(),
  9494. /**
  9495. The controller managing this view. If this property is set, it will be
  9496. made available for use by the template.
  9497. @type Object
  9498. */
  9499. controller: Ember.computed(function(key, value) {
  9500. var parentView;
  9501. if (arguments.length === 2) {
  9502. return value;
  9503. } else {
  9504. parentView = get(this, 'parentView');
  9505. return parentView ? get(parentView, 'controller') : null;
  9506. }
  9507. }).property().cacheable(),
  9508. /**
  9509. A view may contain a layout. A layout is a regular template but
  9510. supersedes the `template` property during rendering. It is the
  9511. responsibility of the layout template to retrieve the `template`
  9512. property from the view (or alternatively, call `Handlebars.helpers.yield`,
  9513. `{{yield}}`) to render it in the correct location.
  9514. This is useful for a view that has a shared wrapper, but which delegates
  9515. the rendering of the contents of the wrapper to the `template` property
  9516. on a subclass.
  9517. @field
  9518. @type Function
  9519. */
  9520. layout: Ember.computed(function(key, value) {
  9521. if (arguments.length === 2) { return value; }
  9522. var layoutName = get(this, 'layoutName'),
  9523. layout = this.templateForName(layoutName, 'layout');
  9524. return layout || get(this, 'defaultLayout');
  9525. }).property('layoutName').cacheable(),
  9526. templateForName: function(name, type) {
  9527. if (!name) { return; }
  9528. var templates = get(this, 'templates'),
  9529. template = get(templates, name);
  9530. if (!template) {
  9531. throw new Ember.Error(fmt('%@ - Unable to find %@ "%@".', [this, type, name]));
  9532. }
  9533. return template;
  9534. },
  9535. /**
  9536. The object from which templates should access properties.
  9537. This object will be passed to the template function each time the render
  9538. method is called, but it is up to the individual function to decide what
  9539. to do with it.
  9540. By default, this will be the view itself.
  9541. @type Object
  9542. */
  9543. context: Ember.computed(function(key, value) {
  9544. if (arguments.length === 2) {
  9545. set(this, '_context', value);
  9546. return value;
  9547. } else {
  9548. return get(this, '_context');
  9549. }
  9550. }).cacheable(),
  9551. /**
  9552. @private
  9553. Private copy of the view's template context. This can be set directly
  9554. by Handlebars without triggering the observer that causes the view
  9555. to be re-rendered.
  9556. The context of a view is looked up as follows:
  9557. 1. Specified controller
  9558. 2. Supplied context (usually by Handlebars)
  9559. 3. `parentView`'s context (for a child of a ContainerView)
  9560. The code in Handlebars that overrides the `_context` property first
  9561. checks to see whether the view has a specified controller. This is
  9562. something of a hack and should be revisited.
  9563. */
  9564. _context: Ember.computed(function(key, value) {
  9565. var parentView, controller, context;
  9566. if (arguments.length === 2) {
  9567. return value;
  9568. }
  9569. if (VIEW_PRESERVES_CONTEXT) {
  9570. if (controller = get(this, 'controller')) {
  9571. return controller;
  9572. }
  9573. parentView = get(this, '_parentView');
  9574. if (parentView) {
  9575. return get(parentView, '_context');
  9576. }
  9577. }
  9578. return this;
  9579. }).cacheable(),
  9580. /**
  9581. If a value that affects template rendering changes, the view should be
  9582. re-rendered to reflect the new value.
  9583. @private
  9584. */
  9585. _displayPropertyDidChange: Ember.observer(function() {
  9586. this.rerender();
  9587. }, 'context', 'controller'),
  9588. /**
  9589. If the view is currently inserted into the DOM of a parent view, this
  9590. property will point to the parent of the view.
  9591. @type Ember.View
  9592. @default null
  9593. */
  9594. parentView: Ember.computed(function() {
  9595. var parent = get(this, '_parentView');
  9596. if (parent && parent.isVirtual) {
  9597. return get(parent, 'parentView');
  9598. } else {
  9599. return parent;
  9600. }
  9601. }).property('_parentView').volatile(),
  9602. _parentView: null,
  9603. // return the current view, not including virtual views
  9604. concreteView: Ember.computed(function() {
  9605. if (!this.isVirtual) { return this; }
  9606. else { return get(this, 'parentView'); }
  9607. }).property('_parentView').volatile(),
  9608. /**
  9609. If false, the view will appear hidden in DOM.
  9610. @type Boolean
  9611. @default null
  9612. */
  9613. isVisible: true,
  9614. /**
  9615. Array of child views. You should never edit this array directly.
  9616. Instead, use appendChild and removeFromParent.
  9617. @private
  9618. @type Array
  9619. @default []
  9620. */
  9621. childViews: childViewsProperty,
  9622. _childViews: [],
  9623. /**
  9624. When it's a virtual view, we need to notify the parent that their
  9625. childViews will change.
  9626. */
  9627. _childViewsWillChange: Ember.beforeObserver(function() {
  9628. if (this.isVirtual) {
  9629. var parentView = get(this, 'parentView');
  9630. if (parentView) { Ember.propertyWillChange(parentView, 'childViews'); }
  9631. }
  9632. }, 'childViews'),
  9633. /**
  9634. When it's a virtual view, we need to notify the parent that their
  9635. childViews did change.
  9636. */
  9637. _childViewsDidChange: Ember.observer(function() {
  9638. if (this.isVirtual) {
  9639. var parentView = get(this, 'parentView');
  9640. if (parentView) { Ember.propertyDidChange(parentView, 'childViews'); }
  9641. }
  9642. }, 'childViews'),
  9643. /**
  9644. Return the nearest ancestor that is an instance of the provided
  9645. class.
  9646. @param {Class} klass Subclass of Ember.View (or Ember.View itself)
  9647. @returns Ember.View
  9648. */
  9649. nearestInstanceOf: function(klass) {
  9650. var view = get(this, 'parentView');
  9651. while (view) {
  9652. if(view instanceof klass) { return view; }
  9653. view = get(view, 'parentView');
  9654. }
  9655. },
  9656. /**
  9657. Return the nearest ancestor that has a given property.
  9658. @param {String} property A property name
  9659. @returns Ember.View
  9660. */
  9661. nearestWithProperty: function(property) {
  9662. var view = get(this, 'parentView');
  9663. while (view) {
  9664. if (property in view) { return view; }
  9665. view = get(view, 'parentView');
  9666. }
  9667. },
  9668. /**
  9669. Return the nearest ancestor whose parent is an instance of
  9670. `klass`.
  9671. @param {Class} klass Subclass of Ember.View (or Ember.View itself)
  9672. @returns Ember.View
  9673. */
  9674. nearestChildOf: function(klass) {
  9675. var view = get(this, 'parentView');
  9676. while (view) {
  9677. if(get(view, 'parentView') instanceof klass) { return view; }
  9678. view = get(view, 'parentView');
  9679. }
  9680. },
  9681. /**
  9682. Return the nearest ancestor that is an Ember.CollectionView
  9683. @returns Ember.CollectionView
  9684. */
  9685. collectionView: Ember.computed(function() {
  9686. return this.nearestInstanceOf(Ember.CollectionView);
  9687. }).cacheable(),
  9688. /**
  9689. Return the nearest ancestor that is a direct child of
  9690. an Ember.CollectionView
  9691. @returns Ember.View
  9692. */
  9693. itemView: Ember.computed(function() {
  9694. return this.nearestChildOf(Ember.CollectionView);
  9695. }).cacheable(),
  9696. /**
  9697. Return the nearest ancestor that has the property
  9698. `content`.
  9699. @returns Ember.View
  9700. */
  9701. contentView: Ember.computed(function() {
  9702. return this.nearestWithProperty('content');
  9703. }).cacheable(),
  9704. /**
  9705. @private
  9706. When the parent view changes, recursively invalidate
  9707. collectionView, itemView, and contentView
  9708. */
  9709. _parentViewDidChange: Ember.observer(function() {
  9710. if (this.isDestroying) { return; }
  9711. this.invokeRecursively(function(view) {
  9712. view.propertyDidChange('collectionView');
  9713. view.propertyDidChange('itemView');
  9714. view.propertyDidChange('contentView');
  9715. });
  9716. if (get(this, 'parentView.controller') && !get(this, 'controller')) {
  9717. this.notifyPropertyChange('controller');
  9718. }
  9719. }, '_parentView'),
  9720. _controllerDidChange: Ember.observer(function() {
  9721. if (this.isDestroying) { return; }
  9722. this.forEachChildView(function(view) {
  9723. view.propertyDidChange('controller');
  9724. });
  9725. }, 'controller'),
  9726. cloneKeywords: function() {
  9727. var templateData = get(this, 'templateData');
  9728. var keywords = templateData ? Ember.copy(templateData.keywords) : {};
  9729. set(keywords, 'view', get(this, 'concreteView'));
  9730. set(keywords, 'controller', get(this, 'controller'));
  9731. return keywords;
  9732. },
  9733. /**
  9734. Called on your view when it should push strings of HTML into a
  9735. Ember.RenderBuffer. Most users will want to override the `template`
  9736. or `templateName` properties instead of this method.
  9737. By default, Ember.View will look for a function in the `template`
  9738. property and invoke it with the value of `context`. The value of
  9739. `context` will be the view's controller unless you override it.
  9740. @param {Ember.RenderBuffer} buffer The render buffer
  9741. */
  9742. render: function(buffer) {
  9743. // If this view has a layout, it is the responsibility of the
  9744. // the layout to render the view's template. Otherwise, render the template
  9745. // directly.
  9746. var template = get(this, 'layout') || get(this, 'template');
  9747. if (template) {
  9748. var context = get(this, '_context');
  9749. var keywords = this.cloneKeywords();
  9750. var data = {
  9751. view: this,
  9752. buffer: buffer,
  9753. isRenderData: true,
  9754. keywords: keywords
  9755. };
  9756. // Invoke the template with the provided template context, which
  9757. // is the view by default. A hash of data is also passed that provides
  9758. // the template with access to the view and render buffer.
  9759. Ember.assert('template must be a function. Did you mean to call Ember.Handlebars.compile("...") or specify templateName instead?', typeof template === 'function');
  9760. // The template should write directly to the render buffer instead
  9761. // of returning a string.
  9762. var output = template(context, { data: data });
  9763. // If the template returned a string instead of writing to the buffer,
  9764. // push the string onto the buffer.
  9765. if (output !== undefined) { buffer.push(output); }
  9766. }
  9767. },
  9768. invokeForState: function(name) {
  9769. var stateName = this.state, args, fn;
  9770. // try to find the function for the state in the cache
  9771. if (fn = invokeForState[stateName][name]) {
  9772. args = a_slice.call(arguments);
  9773. args[0] = this;
  9774. return fn.apply(this, args);
  9775. }
  9776. // otherwise, find and cache the function for this state
  9777. var parent = this, states = parent.states, state;
  9778. while (states) {
  9779. state = states[stateName];
  9780. while (state) {
  9781. fn = state[name];
  9782. if (fn) {
  9783. invokeForState[stateName][name] = fn;
  9784. args = a_slice.call(arguments, 1);
  9785. args.unshift(this);
  9786. return fn.apply(this, args);
  9787. }
  9788. state = state.parentState;
  9789. }
  9790. states = states.parent;
  9791. }
  9792. },
  9793. /**
  9794. Renders the view again. This will work regardless of whether the
  9795. view is already in the DOM or not. If the view is in the DOM, the
  9796. rendering process will be deferred to give bindings a chance
  9797. to synchronize.
  9798. If children were added during the rendering process using `appendChild`,
  9799. `rerender` will remove them, because they will be added again
  9800. if needed by the next `render`.
  9801. In general, if the display of your view changes, you should modify
  9802. the DOM element directly instead of manually calling `rerender`, which can
  9803. be slow.
  9804. */
  9805. rerender: function() {
  9806. return this.invokeForState('rerender');
  9807. },
  9808. clearRenderedChildren: function() {
  9809. var lengthBefore = this.lengthBeforeRender,
  9810. lengthAfter = this.lengthAfterRender;
  9811. // If there were child views created during the last call to render(),
  9812. // remove them under the assumption that they will be re-created when
  9813. // we re-render.
  9814. // VIEW-TODO: Unit test this path.
  9815. var childViews = this._childViews;
  9816. for (var i=lengthAfter-1; i>=lengthBefore; i--) {
  9817. if (childViews[i]) { childViews[i].destroy(); }
  9818. }
  9819. },
  9820. /**
  9821. @private
  9822. Iterates over the view's `classNameBindings` array, inserts the value
  9823. of the specified property into the `classNames` array, then creates an
  9824. observer to update the view's element if the bound property ever changes
  9825. in the future.
  9826. */
  9827. _applyClassNameBindings: function() {
  9828. var classBindings = get(this, 'classNameBindings'),
  9829. classNames = get(this, 'classNames'),
  9830. elem, newClass, dasherizedClass;
  9831. if (!classBindings) { return; }
  9832. // Loop through all of the configured bindings. These will be either
  9833. // property names ('isUrgent') or property paths relative to the view
  9834. // ('content.isUrgent')
  9835. a_forEach(classBindings, function(binding) {
  9836. // Variable in which the old class value is saved. The observer function
  9837. // closes over this variable, so it knows which string to remove when
  9838. // the property changes.
  9839. var oldClass;
  9840. // Set up an observer on the context. If the property changes, toggle the
  9841. // class name.
  9842. var observer = function() {
  9843. // Get the current value of the property
  9844. newClass = this._classStringForProperty(binding);
  9845. elem = this.$();
  9846. // If we had previously added a class to the element, remove it.
  9847. if (oldClass) {
  9848. elem.removeClass(oldClass);
  9849. // Also remove from classNames so that if the view gets rerendered,
  9850. // the class doesn't get added back to the DOM.
  9851. classNames.removeObject(oldClass);
  9852. }
  9853. // If necessary, add a new class. Make sure we keep track of it so
  9854. // it can be removed in the future.
  9855. if (newClass) {
  9856. elem.addClass(newClass);
  9857. oldClass = newClass;
  9858. } else {
  9859. oldClass = null;
  9860. }
  9861. };
  9862. // Get the class name for the property at its current value
  9863. dasherizedClass = this._classStringForProperty(binding);
  9864. if (dasherizedClass) {
  9865. // Ensure that it gets into the classNames array
  9866. // so it is displayed when we render.
  9867. classNames.push(dasherizedClass);
  9868. // Save a reference to the class name so we can remove it
  9869. // if the observer fires. Remember that this variable has
  9870. // been closed over by the observer.
  9871. oldClass = dasherizedClass;
  9872. }
  9873. // Extract just the property name from bindings like 'foo:bar'
  9874. var parsedPath = Ember.View._parsePropertyPath(binding);
  9875. addObserver(this, parsedPath.path, observer);
  9876. }, this);
  9877. },
  9878. /**
  9879. Iterates through the view's attribute bindings, sets up observers for each,
  9880. then applies the current value of the attributes to the passed render buffer.
  9881. @param {Ember.RenderBuffer} buffer
  9882. */
  9883. _applyAttributeBindings: function(buffer) {
  9884. var attributeBindings = get(this, 'attributeBindings'),
  9885. attributeValue, elem, type;
  9886. if (!attributeBindings) { return; }
  9887. a_forEach(attributeBindings, function(binding) {
  9888. var split = binding.split(':'),
  9889. property = split[0],
  9890. attributeName = split[1] || property;
  9891. // Create an observer to add/remove/change the attribute if the
  9892. // JavaScript property changes.
  9893. var observer = function() {
  9894. elem = this.$();
  9895. if (!elem) { return; }
  9896. attributeValue = get(this, property);
  9897. Ember.View.applyAttributeBindings(elem, attributeName, attributeValue);
  9898. };
  9899. addObserver(this, property, observer);
  9900. // Determine the current value and add it to the render buffer
  9901. // if necessary.
  9902. attributeValue = get(this, property);
  9903. Ember.View.applyAttributeBindings(buffer, attributeName, attributeValue);
  9904. }, this);
  9905. },
  9906. /**
  9907. @private
  9908. Given a property name, returns a dasherized version of that
  9909. property name if the property evaluates to a non-falsy value.
  9910. For example, if the view has property `isUrgent` that evaluates to true,
  9911. passing `isUrgent` to this method will return `"is-urgent"`.
  9912. */
  9913. _classStringForProperty: function(property) {
  9914. var parsedPath = Ember.View._parsePropertyPath(property);
  9915. var path = parsedPath.path;
  9916. var val = get(this, path);
  9917. if (val === undefined && Ember.isGlobalPath(path)) {
  9918. val = get(window, path);
  9919. }
  9920. return Ember.View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName);
  9921. },
  9922. // ..........................................................
  9923. // ELEMENT SUPPORT
  9924. //
  9925. /**
  9926. Returns the current DOM element for the view.
  9927. @field
  9928. @type DOMElement
  9929. */
  9930. element: Ember.computed(function(key, value) {
  9931. if (value !== undefined) {
  9932. return this.invokeForState('setElement', value);
  9933. } else {
  9934. return this.invokeForState('getElement');
  9935. }
  9936. }).property('_parentView').cacheable(),
  9937. /**
  9938. Returns a jQuery object for this view's element. If you pass in a selector
  9939. string, this method will return a jQuery object, using the current element
  9940. as its buffer.
  9941. For example, calling `view.$('li')` will return a jQuery object containing
  9942. all of the `li` elements inside the DOM element of this view.
  9943. @param {String} [selector] a jQuery-compatible selector string
  9944. @returns {Ember.CoreQuery} the CoreQuery object for the DOM node
  9945. */
  9946. $: function(sel) {
  9947. return this.invokeForState('$', sel);
  9948. },
  9949. /** @private */
  9950. mutateChildViews: function(callback) {
  9951. var childViews = this._childViews,
  9952. idx = childViews.length,
  9953. view;
  9954. while(--idx >= 0) {
  9955. view = childViews[idx];
  9956. callback.call(this, view, idx);
  9957. }
  9958. return this;
  9959. },
  9960. /** @private */
  9961. forEachChildView: function(callback) {
  9962. var childViews = this._childViews;
  9963. if (!childViews) { return this; }
  9964. var len = childViews.length,
  9965. view, idx;
  9966. for(idx = 0; idx < len; idx++) {
  9967. view = childViews[idx];
  9968. callback.call(this, view);
  9969. }
  9970. return this;
  9971. },
  9972. /**
  9973. Appends the view's element to the specified parent element.
  9974. If the view does not have an HTML representation yet, `createElement()`
  9975. will be called automatically.
  9976. Note that this method just schedules the view to be appended; the DOM
  9977. element will not be appended to the given element until all bindings have
  9978. finished synchronizing.
  9979. This is not typically a function that you will need to call directly
  9980. when building your application. You might consider using Ember.ContainerView
  9981. instead. If you do need to use appendTo, be sure that the target element you
  9982. are providing is associated with an Ember.Application and does not have an
  9983. ancestor element that is associated with an Ember view.
  9984. @param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object
  9985. @returns {Ember.View} receiver
  9986. */
  9987. appendTo: function(target) {
  9988. // Schedule the DOM element to be created and appended to the given
  9989. // element after bindings have synchronized.
  9990. this._insertElementLater(function() {
  9991. Ember.assert("You cannot append to an existing Ember.View. Consider using Ember.ContainerView instead.", !Ember.$(target).is('.ember-view') && !Ember.$(target).parents().is('.ember-view'));
  9992. this.$().appendTo(target);
  9993. });
  9994. return this;
  9995. },
  9996. /**
  9997. Replaces the content of the specified parent element with this view's element.
  9998. If the view does not have an HTML representation yet, `createElement()`
  9999. will be called automatically.
  10000. Note that this method just schedules the view to be appended; the DOM
  10001. element will not be appended to the given element until all bindings have
  10002. finished synchronizing
  10003. @param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object
  10004. @returns {Ember.View} received
  10005. */
  10006. replaceIn: function(target) {
  10007. Ember.assert("You cannot replace an existing Ember.View. Consider using Ember.ContainerView instead.", !Ember.$(target).is('.ember-view') && !Ember.$(target).parents().is('.ember-view'));
  10008. this._insertElementLater(function() {
  10009. Ember.$(target).empty();
  10010. this.$().appendTo(target);
  10011. });
  10012. return this;
  10013. },
  10014. /**
  10015. @private
  10016. Schedules a DOM operation to occur during the next render phase. This
  10017. ensures that all bindings have finished synchronizing before the view is
  10018. rendered.
  10019. To use, pass a function that performs a DOM operation..
  10020. Before your function is called, this view and all child views will receive
  10021. the `willInsertElement` event. After your function is invoked, this view
  10022. and all of its child views will receive the `didInsertElement` event.
  10023. view._insertElementLater(function() {
  10024. this.createElement();
  10025. this.$().appendTo('body');
  10026. });
  10027. @param {Function} fn the function that inserts the element into the DOM
  10028. */
  10029. _insertElementLater: function(fn) {
  10030. this._lastInsert = Ember.guidFor(fn);
  10031. Ember.run.schedule('render', this, this.invokeForState, 'insertElement', fn);
  10032. },
  10033. /**
  10034. Appends the view's element to the document body. If the view does
  10035. not have an HTML representation yet, `createElement()` will be called
  10036. automatically.
  10037. Note that this method just schedules the view to be appended; the DOM
  10038. element will not be appended to the document body until all bindings have
  10039. finished synchronizing.
  10040. @returns {Ember.View} receiver
  10041. */
  10042. append: function() {
  10043. return this.appendTo(document.body);
  10044. },
  10045. /**
  10046. Removes the view's element from the element to which it is attached.
  10047. @returns {Ember.View} receiver
  10048. */
  10049. remove: function() {
  10050. // What we should really do here is wait until the end of the run loop
  10051. // to determine if the element has been re-appended to a different
  10052. // element.
  10053. // In the interim, we will just re-render if that happens. It is more
  10054. // important than elements get garbage collected.
  10055. this.destroyElement();
  10056. this.invokeRecursively(function(view) {
  10057. view.clearRenderedChildren();
  10058. });
  10059. },
  10060. /**
  10061. The ID to use when trying to locate the element in the DOM. If you do not
  10062. set the elementId explicitly, then the view's GUID will be used instead.
  10063. This ID must be set at the time the view is created.
  10064. @type String
  10065. @readOnly
  10066. */
  10067. elementId: Ember.computed(function(key, value) {
  10068. return value !== undefined ? value : Ember.guidFor(this);
  10069. }).cacheable(),
  10070. /**
  10071. @private
  10072. TODO: Perhaps this should be removed from the production build somehow.
  10073. */
  10074. _elementIdDidChange: Ember.beforeObserver(function() {
  10075. throw "Changing a view's elementId after creation is not allowed.";
  10076. }, 'elementId'),
  10077. /**
  10078. Attempts to discover the element in the parent element. The default
  10079. implementation looks for an element with an ID of elementId (or the view's
  10080. guid if elementId is null). You can override this method to provide your
  10081. own form of lookup. For example, if you want to discover your element
  10082. using a CSS class name instead of an ID.
  10083. @param {DOMElement} parentElement The parent's DOM element
  10084. @returns {DOMElement} The discovered element
  10085. */
  10086. findElementInParentElement: function(parentElem) {
  10087. var id = "#" + get(this, 'elementId');
  10088. return Ember.$(id)[0] || Ember.$(id, parentElem)[0];
  10089. },
  10090. /**
  10091. Creates a new renderBuffer with the passed tagName. You can override this
  10092. method to provide further customization to the buffer if needed. Normally
  10093. you will not need to call or override this method.
  10094. @returns {Ember.RenderBuffer}
  10095. */
  10096. renderBuffer: function(tagName) {
  10097. tagName = tagName || get(this, 'tagName');
  10098. // Explicitly check for null or undefined, as tagName
  10099. // may be an empty string, which would evaluate to false.
  10100. if (tagName === null || tagName === undefined) {
  10101. tagName = 'div';
  10102. }
  10103. return Ember.RenderBuffer(tagName);
  10104. },
  10105. /**
  10106. Creates a DOM representation of the view and all of its
  10107. child views by recursively calling the `render()` method.
  10108. After the element has been created, `didInsertElement` will
  10109. be called on this view and all of its child views.
  10110. @returns {Ember.View} receiver
  10111. */
  10112. createElement: function() {
  10113. if (get(this, 'element')) { return this; }
  10114. var buffer = this.renderToBuffer();
  10115. set(this, 'element', buffer.element());
  10116. return this;
  10117. },
  10118. /**
  10119. Called when a view is going to insert an element into the DOM.
  10120. */
  10121. willInsertElement: Ember.K,
  10122. /**
  10123. Called when the element of the view has been inserted into the DOM.
  10124. Override this function to do any set up that requires an element in the
  10125. document body.
  10126. */
  10127. didInsertElement: Ember.K,
  10128. /**
  10129. Called when the view is about to rerender, but before anything has
  10130. been torn down. This is a good opportunity to tear down any manual
  10131. observers you have installed based on the DOM state
  10132. */
  10133. willRerender: Ember.K,
  10134. /**
  10135. Run this callback on the current view and recursively on child views.
  10136. @private
  10137. */
  10138. invokeRecursively: function(fn) {
  10139. fn.call(this, this);
  10140. this.forEachChildView(function(view) {
  10141. view.invokeRecursively(fn);
  10142. });
  10143. },
  10144. /**
  10145. Invalidates the cache for a property on all child views.
  10146. */
  10147. invalidateRecursively: function(key) {
  10148. this.forEachChildView(function(view) {
  10149. view.propertyDidChange(key);
  10150. });
  10151. },
  10152. /**
  10153. @private
  10154. Invokes the receiver's willInsertElement() method if it exists and then
  10155. invokes the same on all child views.
  10156. NOTE: In some cases this was called when the element existed. This no longer
  10157. works so we let people know. We can remove this warning code later.
  10158. */
  10159. _notifyWillInsertElement: function() {
  10160. this.invokeRecursively(function(view) {
  10161. view.trigger('willInsertElement');
  10162. });
  10163. },
  10164. /**
  10165. @private
  10166. Invokes the receiver's didInsertElement() method if it exists and then
  10167. invokes the same on all child views.
  10168. */
  10169. _notifyDidInsertElement: function() {
  10170. this.invokeRecursively(function(view) {
  10171. view.trigger('didInsertElement');
  10172. });
  10173. },
  10174. /**
  10175. @private
  10176. Invokes the receiver's willRerender() method if it exists and then
  10177. invokes the same on all child views.
  10178. */
  10179. _notifyWillRerender: function() {
  10180. this.invokeRecursively(function(view) {
  10181. view.trigger('willRerender');
  10182. });
  10183. },
  10184. /**
  10185. Destroys any existing element along with the element for any child views
  10186. as well. If the view does not currently have a element, then this method
  10187. will do nothing.
  10188. If you implement willDestroyElement() on your view, then this method will
  10189. be invoked on your view before your element is destroyed to give you a
  10190. chance to clean up any event handlers, etc.
  10191. If you write a willDestroyElement() handler, you can assume that your
  10192. didInsertElement() handler was called earlier for the same element.
  10193. Normally you will not call or override this method yourself, but you may
  10194. want to implement the above callbacks when it is run.
  10195. @returns {Ember.View} receiver
  10196. */
  10197. destroyElement: function() {
  10198. return this.invokeForState('destroyElement');
  10199. },
  10200. /**
  10201. Called when the element of the view is going to be destroyed. Override
  10202. this function to do any teardown that requires an element, like removing
  10203. event listeners.
  10204. */
  10205. willDestroyElement: function() {},
  10206. /**
  10207. @private
  10208. Invokes the `willDestroyElement` callback on the view and child views.
  10209. */
  10210. _notifyWillDestroyElement: function() {
  10211. this.invokeRecursively(function(view) {
  10212. view.trigger('willDestroyElement');
  10213. });
  10214. },
  10215. /** @private (nodoc) */
  10216. _elementWillChange: Ember.beforeObserver(function() {
  10217. this.forEachChildView(function(view) {
  10218. Ember.propertyWillChange(view, 'element');
  10219. });
  10220. }, 'element'),
  10221. /**
  10222. @private
  10223. If this view's element changes, we need to invalidate the caches of our
  10224. child views so that we do not retain references to DOM elements that are
  10225. no longer needed.
  10226. @observes element
  10227. */
  10228. _elementDidChange: Ember.observer(function() {
  10229. this.forEachChildView(function(view) {
  10230. Ember.propertyDidChange(view, 'element');
  10231. });
  10232. }, 'element'),
  10233. /**
  10234. Called when the parentView property has changed.
  10235. @function
  10236. */
  10237. parentViewDidChange: Ember.K,
  10238. /**
  10239. @private
  10240. Invoked by the view system when this view needs to produce an HTML
  10241. representation. This method will create a new render buffer, if needed,
  10242. then apply any default attributes, such as class names and visibility.
  10243. Finally, the `render()` method is invoked, which is responsible for
  10244. doing the bulk of the rendering.
  10245. You should not need to override this method; instead, implement the
  10246. `template` property, or if you need more control, override the `render`
  10247. method.
  10248. @param {Ember.RenderBuffer} buffer the render buffer. If no buffer is
  10249. passed, a default buffer, using the current view's `tagName`, will
  10250. be used.
  10251. */
  10252. renderToBuffer: function(parentBuffer, bufferOperation) {
  10253. var buffer;
  10254. Ember.run.sync();
  10255. // Determine where in the parent buffer to start the new buffer.
  10256. // By default, a new buffer will be appended to the parent buffer.
  10257. // The buffer operation may be changed if the child views array is
  10258. // mutated by Ember.ContainerView.
  10259. bufferOperation = bufferOperation || 'begin';
  10260. // If this is the top-most view, start a new buffer. Otherwise,
  10261. // create a new buffer relative to the original using the
  10262. // provided buffer operation (for example, `insertAfter` will
  10263. // insert a new buffer after the "parent buffer").
  10264. if (parentBuffer) {
  10265. var tagName = get(this, 'tagName');
  10266. if (tagName === null || tagName === undefined) {
  10267. tagName = 'div';
  10268. }
  10269. buffer = parentBuffer[bufferOperation](tagName);
  10270. } else {
  10271. buffer = this.renderBuffer();
  10272. }
  10273. this.buffer = buffer;
  10274. this.transitionTo('inBuffer', false);
  10275. this.lengthBeforeRender = this._childViews.length;
  10276. this.beforeRender(buffer);
  10277. this.render(buffer);
  10278. this.afterRender(buffer);
  10279. this.lengthAfterRender = this._childViews.length;
  10280. return buffer;
  10281. },
  10282. beforeRender: function(buffer) {
  10283. this.applyAttributesToBuffer(buffer);
  10284. },
  10285. afterRender: Ember.K,
  10286. /**
  10287. @private
  10288. */
  10289. applyAttributesToBuffer: function(buffer) {
  10290. // Creates observers for all registered class name and attribute bindings,
  10291. // then adds them to the element.
  10292. this._applyClassNameBindings();
  10293. // Pass the render buffer so the method can apply attributes directly.
  10294. // This isn't needed for class name bindings because they use the
  10295. // existing classNames infrastructure.
  10296. this._applyAttributeBindings(buffer);
  10297. a_forEach(get(this, 'classNames'), function(name){ buffer.addClass(name); });
  10298. buffer.id(get(this, 'elementId'));
  10299. var role = get(this, 'ariaRole');
  10300. if (role) {
  10301. buffer.attr('role', role);
  10302. }
  10303. if (get(this, 'isVisible') === false) {
  10304. buffer.style('display', 'none');
  10305. }
  10306. },
  10307. // ..........................................................
  10308. // STANDARD RENDER PROPERTIES
  10309. //
  10310. /**
  10311. Tag name for the view's outer element. The tag name is only used when
  10312. an element is first created. If you change the tagName for an element, you
  10313. must destroy and recreate the view element.
  10314. By default, the render buffer will use a `<div>` tag for views.
  10315. @type String
  10316. @default null
  10317. */
  10318. // We leave this null by default so we can tell the difference between
  10319. // the default case and a user-specified tag.
  10320. tagName: null,
  10321. /**
  10322. The WAI-ARIA role of the control represented by this view. For example, a
  10323. button may have a role of type 'button', or a pane may have a role of
  10324. type 'alertdialog'. This property is used by assistive software to help
  10325. visually challenged users navigate rich web applications.
  10326. The full list of valid WAI-ARIA roles is available at:
  10327. http://www.w3.org/TR/wai-aria/roles#roles_categorization
  10328. @type String
  10329. @default null
  10330. */
  10331. ariaRole: null,
  10332. /**
  10333. Standard CSS class names to apply to the view's outer element. This
  10334. property automatically inherits any class names defined by the view's
  10335. superclasses as well.
  10336. @type Array
  10337. @default ['ember-view']
  10338. */
  10339. classNames: ['ember-view'],
  10340. /**
  10341. A list of properties of the view to apply as class names. If the property
  10342. is a string value, the value of that string will be applied as a class
  10343. name.
  10344. // Applies the 'high' class to the view element
  10345. Ember.View.create({
  10346. classNameBindings: ['priority']
  10347. priority: 'high'
  10348. });
  10349. If the value of the property is a Boolean, the name of that property is
  10350. added as a dasherized class name.
  10351. // Applies the 'is-urgent' class to the view element
  10352. Ember.View.create({
  10353. classNameBindings: ['isUrgent']
  10354. isUrgent: true
  10355. });
  10356. If you would prefer to use a custom value instead of the dasherized
  10357. property name, you can pass a binding like this:
  10358. // Applies the 'urgent' class to the view element
  10359. Ember.View.create({
  10360. classNameBindings: ['isUrgent:urgent']
  10361. isUrgent: true
  10362. });
  10363. This list of properties is inherited from the view's superclasses as well.
  10364. @type Array
  10365. @default []
  10366. */
  10367. classNameBindings: [],
  10368. /**
  10369. A list of properties of the view to apply as attributes. If the property is
  10370. a string value, the value of that string will be applied as the attribute.
  10371. // Applies the type attribute to the element
  10372. // with the value "button", like <div type="button">
  10373. Ember.View.create({
  10374. attributeBindings: ['type'],
  10375. type: 'button'
  10376. });
  10377. If the value of the property is a Boolean, the name of that property is
  10378. added as an attribute.
  10379. // Renders something like <div enabled="enabled">
  10380. Ember.View.create({
  10381. attributeBindings: ['enabled'],
  10382. enabled: true
  10383. });
  10384. */
  10385. attributeBindings: [],
  10386. state: 'preRender',
  10387. // .......................................................
  10388. // CORE DISPLAY METHODS
  10389. //
  10390. /**
  10391. @private
  10392. Setup a view, but do not finish waking it up.
  10393. - configure childViews
  10394. - register the view with the global views hash, which is used for event
  10395. dispatch
  10396. */
  10397. init: function() {
  10398. this._super();
  10399. // Register the view for event handling. This hash is used by
  10400. // Ember.EventDispatcher to dispatch incoming events.
  10401. if (!this.isVirtual) Ember.View.views[get(this, 'elementId')] = this;
  10402. // setup child views. be sure to clone the child views array first
  10403. this._childViews = this._childViews.slice();
  10404. Ember.assert("Only arrays are allowed for 'classNameBindings'", Ember.typeOf(this.classNameBindings) === 'array');
  10405. this.classNameBindings = Ember.A(this.classNameBindings.slice());
  10406. Ember.assert("Only arrays are allowed for 'classNames'", Ember.typeOf(this.classNames) === 'array');
  10407. this.classNames = Ember.A(this.classNames.slice());
  10408. var viewController = get(this, 'viewController');
  10409. if (viewController) {
  10410. viewController = get(viewController);
  10411. if (viewController) {
  10412. set(viewController, 'view', this);
  10413. }
  10414. }
  10415. },
  10416. appendChild: function(view, options) {
  10417. return this.invokeForState('appendChild', view, options);
  10418. },
  10419. /**
  10420. Removes the child view from the parent view.
  10421. @param {Ember.View} view
  10422. @returns {Ember.View} receiver
  10423. */
  10424. removeChild: function(view) {
  10425. // If we're destroying, the entire subtree will be
  10426. // freed, and the DOM will be handled separately,
  10427. // so no need to mess with childViews.
  10428. if (this.isDestroying) { return; }
  10429. // update parent node
  10430. set(view, '_parentView', null);
  10431. // remove view from childViews array.
  10432. var childViews = this._childViews;
  10433. Ember.EnumerableUtils.removeObject(childViews, view);
  10434. this.propertyDidChange('childViews'); // HUH?! what happened to will change?
  10435. return this;
  10436. },
  10437. /**
  10438. Removes all children from the parentView.
  10439. @returns {Ember.View} receiver
  10440. */
  10441. removeAllChildren: function() {
  10442. return this.mutateChildViews(function(view) {
  10443. this.removeChild(view);
  10444. });
  10445. },
  10446. destroyAllChildren: function() {
  10447. return this.mutateChildViews(function(view) {
  10448. view.destroy();
  10449. });
  10450. },
  10451. /**
  10452. Removes the view from its parentView, if one is found. Otherwise
  10453. does nothing.
  10454. @returns {Ember.View} receiver
  10455. */
  10456. removeFromParent: function() {
  10457. var parent = get(this, '_parentView');
  10458. // Remove DOM element from parent
  10459. this.remove();
  10460. if (parent) { parent.removeChild(this); }
  10461. return this;
  10462. },
  10463. /**
  10464. You must call `destroy` on a view to destroy the view (and all of its
  10465. child views). This will remove the view from any parent node, then make
  10466. sure that the DOM element managed by the view can be released by the
  10467. memory manager.
  10468. */
  10469. willDestroy: function() {
  10470. // calling this._super() will nuke computed properties and observers,
  10471. // so collect any information we need before calling super.
  10472. var childViews = this._childViews,
  10473. parent = get(this, '_parentView'),
  10474. childLen;
  10475. // destroy the element -- this will avoid each child view destroying
  10476. // the element over and over again...
  10477. if (!this.removedFromDOM) { this.destroyElement(); }
  10478. // remove from non-virtual parent view if viewName was specified
  10479. if (this.viewName) {
  10480. var nonVirtualParentView = get(this, 'parentView');
  10481. if (nonVirtualParentView) {
  10482. set(nonVirtualParentView, this.viewName, null);
  10483. }
  10484. }
  10485. // remove from parent if found. Don't call removeFromParent,
  10486. // as removeFromParent will try to remove the element from
  10487. // the DOM again.
  10488. if (parent) { parent.removeChild(this); }
  10489. this.state = 'destroyed';
  10490. childLen = childViews.length;
  10491. for (var i=childLen-1; i>=0; i--) {
  10492. childViews[i].removedFromDOM = true;
  10493. childViews[i].destroy();
  10494. }
  10495. // next remove view from global hash
  10496. if (!this.isVirtual) delete Ember.View.views[get(this, 'elementId')];
  10497. },
  10498. /**
  10499. Instantiates a view to be added to the childViews array during view
  10500. initialization. You generally will not call this method directly unless
  10501. you are overriding createChildViews(). Note that this method will
  10502. automatically configure the correct settings on the new view instance to
  10503. act as a child of the parent.
  10504. @param {Class} viewClass
  10505. @param {Hash} [attrs] Attributes to add
  10506. @returns {Ember.View} new instance
  10507. @test in createChildViews
  10508. */
  10509. createChildView: function(view, attrs) {
  10510. if (Ember.View.detect(view)) {
  10511. attrs = attrs || {};
  10512. attrs._parentView = this;
  10513. attrs.templateData = attrs.templateData || get(this, 'templateData');
  10514. view = view.create(attrs);
  10515. // don't set the property on a virtual view, as they are invisible to
  10516. // consumers of the view API
  10517. if (view.viewName) { set(get(this, 'concreteView'), view.viewName, view); }
  10518. } else {
  10519. Ember.assert('You must pass instance or subclass of View', view instanceof Ember.View);
  10520. Ember.assert("You can only pass attributes when a class is provided", !attrs);
  10521. if (!get(view, 'templateData')) {
  10522. set(view, 'templateData', get(this, 'templateData'));
  10523. }
  10524. set(view, '_parentView', this);
  10525. }
  10526. return view;
  10527. },
  10528. becameVisible: Ember.K,
  10529. becameHidden: Ember.K,
  10530. /**
  10531. @private
  10532. When the view's `isVisible` property changes, toggle the visibility
  10533. element of the actual DOM element.
  10534. */
  10535. _isVisibleDidChange: Ember.observer(function() {
  10536. var $el = this.$();
  10537. if (!$el) { return; }
  10538. var isVisible = get(this, 'isVisible');
  10539. $el.toggle(isVisible);
  10540. if (this._isAncestorHidden()) { return; }
  10541. if (isVisible) {
  10542. this._notifyBecameVisible();
  10543. } else {
  10544. this._notifyBecameHidden();
  10545. }
  10546. }, 'isVisible'),
  10547. _notifyBecameVisible: function() {
  10548. this.trigger('becameVisible');
  10549. this.forEachChildView(function(view) {
  10550. var isVisible = get(view, 'isVisible');
  10551. if (isVisible || isVisible === null) {
  10552. view._notifyBecameVisible();
  10553. }
  10554. });
  10555. },
  10556. _notifyBecameHidden: function() {
  10557. this.trigger('becameHidden');
  10558. this.forEachChildView(function(view) {
  10559. var isVisible = get(view, 'isVisible');
  10560. if (isVisible || isVisible === null) {
  10561. view._notifyBecameHidden();
  10562. }
  10563. });
  10564. },
  10565. _isAncestorHidden: function() {
  10566. var parent = get(this, 'parentView');
  10567. while (parent) {
  10568. if (get(parent, 'isVisible') === false) { return true; }
  10569. parent = get(parent, 'parentView');
  10570. }
  10571. return false;
  10572. },
  10573. clearBuffer: function() {
  10574. this.invokeRecursively(function(view) {
  10575. this.buffer = null;
  10576. });
  10577. },
  10578. transitionTo: function(state, children) {
  10579. this.state = state;
  10580. if (children !== false) {
  10581. this.forEachChildView(function(view) {
  10582. view.transitionTo(state);
  10583. });
  10584. }
  10585. },
  10586. /**
  10587. @private
  10588. Override the default event firing from Ember.Evented to
  10589. also call methods with the given name.
  10590. */
  10591. trigger: function(name) {
  10592. this._super.apply(this, arguments);
  10593. var method = this[name];
  10594. if (method) {
  10595. var args = [], i, l;
  10596. for (i = 1, l = arguments.length; i < l; i++) {
  10597. args.push(arguments[i]);
  10598. }
  10599. return method.apply(this, args);
  10600. }
  10601. },
  10602. has: function(name) {
  10603. return Ember.typeOf(this[name]) === 'function' || this._super(name);
  10604. },
  10605. // .......................................................
  10606. // EVENT HANDLING
  10607. //
  10608. /**
  10609. @private
  10610. Handle events from `Ember.EventDispatcher`
  10611. */
  10612. handleEvent: function(eventName, evt) {
  10613. return this.invokeForState('handleEvent', eventName, evt);
  10614. }
  10615. });
  10616. /**
  10617. Describe how the specified actions should behave in the various
  10618. states that a view can exist in. Possible states:
  10619. * preRender: when a view is first instantiated, and after its
  10620. element was destroyed, it is in the preRender state
  10621. * inBuffer: once a view has been rendered, but before it has
  10622. been inserted into the DOM, it is in the inBuffer state
  10623. * inDOM: once a view has been inserted into the DOM it is in
  10624. the inDOM state. A view spends the vast majority of its
  10625. existence in this state.
  10626. * destroyed: once a view has been destroyed (using the destroy
  10627. method), it is in this state. No further actions can be invoked
  10628. on a destroyed view.
  10629. */
  10630. // in the destroyed state, everything is illegal
  10631. // before rendering has begun, all legal manipulations are noops.
  10632. // inside the buffer, legal manipulations are done on the buffer
  10633. // once the view has been inserted into the DOM, legal manipulations
  10634. // are done on the DOM element.
  10635. /** @private */
  10636. var DOMManager = {
  10637. prepend: function(view, childView) {
  10638. childView._insertElementLater(function() {
  10639. var element = view.$();
  10640. element.prepend(childView.$());
  10641. });
  10642. },
  10643. after: function(view, nextView) {
  10644. nextView._insertElementLater(function() {
  10645. var element = view.$();
  10646. element.after(nextView.$());
  10647. });
  10648. },
  10649. replace: function(view) {
  10650. var element = get(view, 'element');
  10651. set(view, 'element', null);
  10652. view._insertElementLater(function() {
  10653. Ember.$(element).replaceWith(get(view, 'element'));
  10654. });
  10655. },
  10656. remove: function(view) {
  10657. var elem = get(view, 'element');
  10658. set(view, 'element', null);
  10659. view._lastInsert = null;
  10660. Ember.$(elem).remove();
  10661. },
  10662. empty: function(view) {
  10663. view.$().empty();
  10664. }
  10665. };
  10666. Ember.View.reopen({
  10667. states: Ember.View.states,
  10668. domManager: DOMManager
  10669. });
  10670. Ember.View.reopenClass({
  10671. /**
  10672. @private
  10673. Parse a path and return an object which holds the parsed properties.
  10674. For example a path like "content.isEnabled:enabled:disabled" wil return the
  10675. following object:
  10676. {
  10677. path: "content.isEnabled",
  10678. className: "enabled",
  10679. falsyClassName: "disabled",
  10680. classNames: ":enabled:disabled"
  10681. }
  10682. */
  10683. _parsePropertyPath: function(path) {
  10684. var split = path.split(/:/),
  10685. propertyPath = split[0],
  10686. classNames = "",
  10687. className,
  10688. falsyClassName;
  10689. // check if the property is defined as prop:class or prop:trueClass:falseClass
  10690. if (split.length > 1) {
  10691. className = split[1];
  10692. if (split.length === 3) { falsyClassName = split[2]; }
  10693. classNames = ':' + className;
  10694. if (falsyClassName) { classNames += ":" + falsyClassName; }
  10695. }
  10696. return {
  10697. path: propertyPath,
  10698. classNames: classNames,
  10699. className: (className === '') ? undefined : className,
  10700. falsyClassName: falsyClassName
  10701. };
  10702. },
  10703. /**
  10704. @private
  10705. Get the class name for a given value, based on the path, optional className
  10706. and optional falsyClassName.
  10707. - if the value is truthy and a className is defined, the className is returned
  10708. - if the value is true, the dasherized last part of the supplied path is returned
  10709. - if the value is false and a falsyClassName is supplied, the falsyClassName is returned
  10710. - if the value is truthy, the value is returned
  10711. - if none of the above rules apply, null is returned
  10712. */
  10713. _classStringForValue: function(path, val, className, falsyClassName) {
  10714. // If the value is truthy and we're using the colon syntax,
  10715. // we should return the className directly
  10716. if (!!val && className) {
  10717. return className;
  10718. // If value is a Boolean and true, return the dasherized property
  10719. // name.
  10720. } else if (val === true) {
  10721. // catch syntax like isEnabled::not-enabled
  10722. if (val === true && !className && falsyClassName) { return null; }
  10723. // Normalize property path to be suitable for use
  10724. // as a class name. For exaple, content.foo.barBaz
  10725. // becomes bar-baz.
  10726. var parts = path.split('.');
  10727. return Ember.String.dasherize(parts[parts.length-1]);
  10728. // If the value is false and a falsyClassName is specified, return it
  10729. } else if (val === false && falsyClassName) {
  10730. return falsyClassName;
  10731. // If the value is not false, undefined, or null, return the current
  10732. // value of the property.
  10733. } else if (val !== false && val !== undefined && val !== null) {
  10734. return val;
  10735. // Nothing to display. Return null so that the old class is removed
  10736. // but no new class is added.
  10737. } else {
  10738. return null;
  10739. }
  10740. }
  10741. });
  10742. // Create a global view hash.
  10743. Ember.View.views = {};
  10744. // If someone overrides the child views computed property when
  10745. // defining their class, we want to be able to process the user's
  10746. // supplied childViews and then restore the original computed property
  10747. // at view initialization time. This happens in Ember.ContainerView's init
  10748. // method.
  10749. Ember.View.childViewsProperty = childViewsProperty;
  10750. Ember.View.applyAttributeBindings = function(elem, name, value) {
  10751. var type = Ember.typeOf(value);
  10752. var currentValue = elem.attr(name);
  10753. // if this changes, also change the logic in ember-handlebars/lib/helpers/binding.js
  10754. if ((type === 'string' || (type === 'number' && !isNaN(value))) && value !== currentValue) {
  10755. elem.attr(name, value);
  10756. } else if (value && type === 'boolean') {
  10757. elem.attr(name, name);
  10758. } else if (!value) {
  10759. elem.removeAttr(name);
  10760. }
  10761. };
  10762. })();
  10763. (function() {
  10764. // ==========================================================================
  10765. // Project: Ember - JavaScript Application Framework
  10766. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  10767. // Portions ©2008-2011 Apple Inc. All rights reserved.
  10768. // License: Licensed under MIT license (see license.js)
  10769. // ==========================================================================
  10770. var get = Ember.get, set = Ember.set;
  10771. Ember.View.states = {
  10772. _default: {
  10773. // appendChild is only legal while rendering the buffer.
  10774. appendChild: function() {
  10775. throw "You can't use appendChild outside of the rendering process";
  10776. },
  10777. $: function() {
  10778. return undefined;
  10779. },
  10780. getElement: function() {
  10781. return null;
  10782. },
  10783. // Handle events from `Ember.EventDispatcher`
  10784. handleEvent: function() {
  10785. return true; // continue event propagation
  10786. },
  10787. destroyElement: function(view) {
  10788. set(view, 'element', null);
  10789. view._lastInsert = null;
  10790. return view;
  10791. }
  10792. }
  10793. };
  10794. Ember.View.reopen({
  10795. states: Ember.View.states
  10796. });
  10797. })();
  10798. (function() {
  10799. // ==========================================================================
  10800. // Project: Ember - JavaScript Application Framework
  10801. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  10802. // Portions ©2008-2011 Apple Inc. All rights reserved.
  10803. // License: Licensed under MIT license (see license.js)
  10804. // ==========================================================================
  10805. Ember.View.states.preRender = {
  10806. parentState: Ember.View.states._default,
  10807. // a view leaves the preRender state once its element has been
  10808. // created (createElement).
  10809. insertElement: function(view, fn) {
  10810. if (view._lastInsert !== Ember.guidFor(fn)){
  10811. return;
  10812. }
  10813. view.createElement();
  10814. view._notifyWillInsertElement();
  10815. // after createElement, the view will be in the hasElement state.
  10816. fn.call(view);
  10817. view.transitionTo('inDOM');
  10818. view._notifyDidInsertElement();
  10819. },
  10820. empty: Ember.K,
  10821. setElement: function(view, value) {
  10822. if (value !== null) {
  10823. view.transitionTo('hasElement');
  10824. }
  10825. return value;
  10826. }
  10827. };
  10828. })();
  10829. (function() {
  10830. // ==========================================================================
  10831. // Project: Ember - JavaScript Application Framework
  10832. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  10833. // Portions ©2008-2011 Apple Inc. All rights reserved.
  10834. // License: Licensed under MIT license (see license.js)
  10835. // ==========================================================================
  10836. var get = Ember.get, set = Ember.set, meta = Ember.meta;
  10837. Ember.View.states.inBuffer = {
  10838. parentState: Ember.View.states._default,
  10839. $: function(view, sel) {
  10840. // if we don't have an element yet, someone calling this.$() is
  10841. // trying to update an element that isn't in the DOM. Instead,
  10842. // rerender the view to allow the render method to reflect the
  10843. // changes.
  10844. view.rerender();
  10845. return Ember.$();
  10846. },
  10847. // when a view is rendered in a buffer, rerendering it simply
  10848. // replaces the existing buffer with a new one
  10849. rerender: function(view) {
  10850. Ember.deprecate("Something you did caused a view to re-render after it rendered but before it was inserted into the DOM. Because this is avoidable and the cause of significant performance issues in applications, this behavior is deprecated. If you want to use the debugger to find out what caused this, you can set ENV.RAISE_ON_DEPRECATION to true.");
  10851. view._notifyWillRerender();
  10852. view.clearRenderedChildren();
  10853. view.renderToBuffer(view.buffer, 'replaceWith');
  10854. },
  10855. // when a view is rendered in a buffer, appending a child
  10856. // view will render that view and append the resulting
  10857. // buffer into its buffer.
  10858. appendChild: function(view, childView, options) {
  10859. var buffer = view.buffer;
  10860. childView = this.createChildView(childView, options);
  10861. view._childViews.push(childView);
  10862. childView.renderToBuffer(buffer);
  10863. view.propertyDidChange('childViews');
  10864. return childView;
  10865. },
  10866. // when a view is rendered in a buffer, destroying the
  10867. // element will simply destroy the buffer and put the
  10868. // state back into the preRender state.
  10869. destroyElement: function(view) {
  10870. view.clearBuffer();
  10871. view._notifyWillDestroyElement();
  10872. view.transitionTo('preRender');
  10873. return view;
  10874. },
  10875. empty: function() {
  10876. Ember.assert("Emptying a view in the inBuffer state is not allowed and should not happen under normal circumstances. Most likely there is a bug in your application. This may be due to excessive property change notifications.");
  10877. },
  10878. // It should be impossible for a rendered view to be scheduled for
  10879. // insertion.
  10880. insertElement: function() {
  10881. throw "You can't insert an element that has already been rendered";
  10882. },
  10883. setElement: function(view, value) {
  10884. if (value === null) {
  10885. view.transitionTo('preRender');
  10886. } else {
  10887. view.clearBuffer();
  10888. view.transitionTo('hasElement');
  10889. }
  10890. return value;
  10891. }
  10892. };
  10893. })();
  10894. (function() {
  10895. // ==========================================================================
  10896. // Project: Ember - JavaScript Application Framework
  10897. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  10898. // Portions ©2008-2011 Apple Inc. All rights reserved.
  10899. // License: Licensed under MIT license (see license.js)
  10900. // ==========================================================================
  10901. var get = Ember.get, set = Ember.set, meta = Ember.meta;
  10902. Ember.View.states.hasElement = {
  10903. parentState: Ember.View.states._default,
  10904. $: function(view, sel) {
  10905. var elem = get(view, 'element');
  10906. return sel ? Ember.$(sel, elem) : Ember.$(elem);
  10907. },
  10908. getElement: function(view) {
  10909. var parent = get(view, 'parentView');
  10910. if (parent) { parent = get(parent, 'element'); }
  10911. if (parent) { return view.findElementInParentElement(parent); }
  10912. return Ember.$("#" + get(view, 'elementId'))[0];
  10913. },
  10914. setElement: function(view, value) {
  10915. if (value === null) {
  10916. view.transitionTo('preRender');
  10917. } else {
  10918. throw "You cannot set an element to a non-null value when the element is already in the DOM.";
  10919. }
  10920. return value;
  10921. },
  10922. // once the view has been inserted into the DOM, rerendering is
  10923. // deferred to allow bindings to synchronize.
  10924. rerender: function(view) {
  10925. view._notifyWillRerender();
  10926. view.clearRenderedChildren();
  10927. view.domManager.replace(view);
  10928. return view;
  10929. },
  10930. // once the view is already in the DOM, destroying it removes it
  10931. // from the DOM, nukes its element, and puts it back into the
  10932. // preRender state if inDOM.
  10933. destroyElement: function(view) {
  10934. view._notifyWillDestroyElement();
  10935. view.domManager.remove(view);
  10936. return view;
  10937. },
  10938. empty: function(view) {
  10939. var _childViews = view._childViews, len, idx;
  10940. if (_childViews) {
  10941. len = _childViews.length;
  10942. for (idx = 0; idx < len; idx++) {
  10943. _childViews[idx]._notifyWillDestroyElement();
  10944. }
  10945. }
  10946. view.domManager.empty(view);
  10947. },
  10948. // Handle events from `Ember.EventDispatcher`
  10949. handleEvent: function(view, eventName, evt) {
  10950. if (view.has(eventName)) {
  10951. // Handler should be able to re-dispatch events, so we don't
  10952. // preventDefault or stopPropagation.
  10953. return view.trigger(eventName, evt);
  10954. } else {
  10955. return true; // continue event propagation
  10956. }
  10957. }
  10958. };
  10959. Ember.View.states.inDOM = {
  10960. parentState: Ember.View.states.hasElement,
  10961. insertElement: function(view, fn) {
  10962. if (view._lastInsert !== Ember.guidFor(fn)){
  10963. return;
  10964. }
  10965. throw "You can't insert an element into the DOM that has already been inserted";
  10966. }
  10967. };
  10968. })();
  10969. (function() {
  10970. // ==========================================================================
  10971. // Project: Ember - JavaScript Application Framework
  10972. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  10973. // Portions ©2008-2011 Apple Inc. All rights reserved.
  10974. // License: Licensed under MIT license (see license.js)
  10975. // ==========================================================================
  10976. var destroyedError = "You can't call %@ on a destroyed view", fmt = Ember.String.fmt;
  10977. Ember.View.states.destroyed = {
  10978. parentState: Ember.View.states._default,
  10979. appendChild: function() {
  10980. throw fmt(destroyedError, ['appendChild']);
  10981. },
  10982. rerender: function() {
  10983. throw fmt(destroyedError, ['rerender']);
  10984. },
  10985. destroyElement: function() {
  10986. throw fmt(destroyedError, ['destroyElement']);
  10987. },
  10988. empty: function() {
  10989. throw fmt(destroyedError, ['empty']);
  10990. },
  10991. setElement: function() {
  10992. throw fmt(destroyedError, ["set('element', ...)"]);
  10993. },
  10994. // Since element insertion is scheduled, don't do anything if
  10995. // the view has been destroyed between scheduling and execution
  10996. insertElement: Ember.K
  10997. };
  10998. })();
  10999. (function() {
  11000. // ==========================================================================
  11001. // Project: Ember - JavaScript Application Framework
  11002. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  11003. // Portions ©2008-2011 Apple Inc. All rights reserved.
  11004. // License: Licensed under MIT license (see license.js)
  11005. // ==========================================================================
  11006. })();
  11007. (function() {
  11008. // ==========================================================================
  11009. // Project: Ember - JavaScript Application Framework
  11010. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  11011. // Portions ©2008-2011 Apple Inc. All rights reserved.
  11012. // License: Licensed under MIT license (see license.js)
  11013. // ==========================================================================
  11014. var get = Ember.get, set = Ember.set, meta = Ember.meta;
  11015. var forEach = Ember.EnumerableUtils.forEach;
  11016. var childViewsProperty = Ember.computed(function() {
  11017. return get(this, '_childViews');
  11018. }).property('_childViews').cacheable();
  11019. /**
  11020. @class
  11021. A `ContainerView` is an `Ember.View` subclass that allows for manual or programatic
  11022. management of a view's `childViews` array that will correctly update the `ContainerView`
  11023. instance's rendered DOM representation.
  11024. ## Setting Initial Child Views
  11025. The initial array of child views can be set in one of two ways. You can provide
  11026. a `childViews` property at creation time that contains instance of `Ember.View`:
  11027. aContainer = Ember.ContainerView.create({
  11028. childViews: [Ember.View.create(), Ember.View.create()]
  11029. })
  11030. You can also provide a list of property names whose values are instances of `Ember.View`:
  11031. aContainer = Ember.ContainerView.create({
  11032. childViews: ['aView', 'bView', 'cView'],
  11033. aView: Ember.View.create(),
  11034. bView: Ember.View.create()
  11035. cView: Ember.View.create()
  11036. })
  11037. The two strategies can be combined:
  11038. aContainer = Ember.ContainerView.create({
  11039. childViews: ['aView', Ember.View.create()],
  11040. aView: Ember.View.create()
  11041. })
  11042. Each child view's rendering will be inserted into the container's rendered HTML in the same
  11043. order as its position in the `childViews` property.
  11044. ## Adding and Removing Child Views
  11045. The views in a container's `childViews` array should be added and removed by manipulating
  11046. the `childViews` property directly.
  11047. To remove a view pass that view into a `removeObject` call on the container's `childViews` property.
  11048. Given an empty `<body>` the following code
  11049. aContainer = Ember.ContainerView.create({
  11050. classNames: ['the-container'],
  11051. childViews: ['aView', 'bView'],
  11052. aView: Ember.View.create({
  11053. template: Ember.Handlebars.compile("A")
  11054. }),
  11055. bView: Ember.View.create({
  11056. template: Ember.Handlebars.compile("B")
  11057. })
  11058. })
  11059. aContainer.appendTo('body')
  11060. Results in the HTML
  11061. <div class="ember-view the-container">
  11062. <div class="ember-view">A</div>
  11063. <div class="ember-view">B</div>
  11064. </div>
  11065. Removing a view
  11066. aContainer.get('childViews') // [aContainer.aView, aContainer.bView]
  11067. aContainer.get('childViews').removeObject(aContainer.get('bView'))
  11068. aContainer.get('childViews') // [aContainer.aView]
  11069. Will result in the following HTML
  11070. <div class="ember-view the-container">
  11071. <div class="ember-view">A</div>
  11072. </div>
  11073. Similarly, adding a child view is accomplished by adding `Ember.View` instances to the
  11074. container's `childViews` property.
  11075. Given an empty `<body>` the following code
  11076. aContainer = Ember.ContainerView.create({
  11077. classNames: ['the-container'],
  11078. childViews: ['aView', 'bView'],
  11079. aView: Ember.View.create({
  11080. template: Ember.Handlebars.compile("A")
  11081. }),
  11082. bView: Ember.View.create({
  11083. template: Ember.Handlebars.compile("B")
  11084. })
  11085. })
  11086. aContainer.appendTo('body')
  11087. Results in the HTML
  11088. <div class="ember-view the-container">
  11089. <div class="ember-view">A</div>
  11090. <div class="ember-view">B</div>
  11091. </div>
  11092. Adding a view
  11093. AnotherViewClass = Ember.View.extend({
  11094. template: Ember.Handlebars.compile("Another view")
  11095. })
  11096. aContainer.get('childViews') // [aContainer.aView, aContainer.bView]
  11097. aContainer.get('childViews').pushObject(AnotherViewClass.create())
  11098. aContainer.get('childViews') // [aContainer.aView, aContainer.bView, <AnotherViewClass instance>]
  11099. Will result in the following HTML
  11100. <div class="ember-view the-container">
  11101. <div class="ember-view">A</div>
  11102. <div class="ember-view">B</div>
  11103. <div class="ember-view">Another view</div>
  11104. </div>
  11105. Direct manipulation of childViews presence or absence in the DOM via calls to
  11106. `remove` or `removeFromParent` or calls to a container's `removeChild` may not behave
  11107. correctly.
  11108. Calling `remove()` on a child view will remove the view's HTML, but it will remain as part of its
  11109. container's `childView`s property.
  11110. Calling `removeChild()` on the container will remove the passed view instance from the container's
  11111. `childView`s but keep its HTML within the container's rendered view.
  11112. Calling `removeFromParent()` behaves as expected but should be avoided in favor of direct
  11113. manipulation of a container's `childViews` property.
  11114. aContainer = Ember.ContainerView.create({
  11115. classNames: ['the-container'],
  11116. childViews: ['aView', 'bView'],
  11117. aView: Ember.View.create({
  11118. template: Ember.Handlebars.compile("A")
  11119. }),
  11120. bView: Ember.View.create({
  11121. template: Ember.Handlebars.compile("B")
  11122. })
  11123. })
  11124. aContainer.appendTo('body')
  11125. Results in the HTML
  11126. <div class="ember-view the-container">
  11127. <div class="ember-view">A</div>
  11128. <div class="ember-view">B</div>
  11129. </div>
  11130. Calling `aContainer.get('aView').removeFromParent()` will result in the following HTML
  11131. <div class="ember-view the-container">
  11132. <div class="ember-view">B</div>
  11133. </div>
  11134. And the `Ember.View` instance stored in `aContainer.aView` will be removed from `aContainer`'s
  11135. `childViews` array.
  11136. ## Templates and Layout
  11137. A `template`, `templateName`, `defaultTemplate`, `layout`, `layoutName` or `defaultLayout`
  11138. property on a container view will not result in the template or layout being rendered.
  11139. The HTML contents of a `Ember.ContainerView`'s DOM representation will only be the rendered HTML
  11140. of its child views.
  11141. ## Binding a View to Display
  11142. If you would like to display a single view in your ContainerView, you can set its `currentView`
  11143. property. When the `currentView` property is set to a view instance, it will be added to the
  11144. ContainerView's `childViews` array. If the `currentView` property is later changed to a
  11145. different view, the new view will replace the old view. If `currentView` is set to `null`, the
  11146. last `currentView` will be removed.
  11147. This functionality is useful for cases where you want to bind the display of a ContainerView to
  11148. a controller or state manager. For example, you can bind the `currentView` of a container to
  11149. a controller like this:
  11150. // Controller
  11151. App.appController = Ember.Object.create({
  11152. view: Ember.View.create({
  11153. templateName: 'person_template'
  11154. })
  11155. });
  11156. // Handlebars template
  11157. {{view Ember.ContainerView currentViewBinding="App.appController.view"}}
  11158. @extends Ember.View
  11159. */
  11160. Ember.ContainerView = Ember.View.extend({
  11161. init: function() {
  11162. this._super();
  11163. var childViews = get(this, 'childViews');
  11164. Ember.defineProperty(this, 'childViews', childViewsProperty);
  11165. var _childViews = this._childViews;
  11166. forEach(childViews, function(viewName, idx) {
  11167. var view;
  11168. if ('string' === typeof viewName) {
  11169. view = get(this, viewName);
  11170. view = this.createChildView(view);
  11171. set(this, viewName, view);
  11172. } else {
  11173. view = this.createChildView(viewName);
  11174. }
  11175. _childViews[idx] = view;
  11176. }, this);
  11177. var currentView = get(this, 'currentView');
  11178. if (currentView) _childViews.push(this.createChildView(currentView));
  11179. // Make the _childViews array observable
  11180. Ember.A(_childViews);
  11181. // Sets up an array observer on the child views array. This
  11182. // observer will detect when child views are added or removed
  11183. // and update the DOM to reflect the mutation.
  11184. get(this, 'childViews').addArrayObserver(this, {
  11185. willChange: 'childViewsWillChange',
  11186. didChange: 'childViewsDidChange'
  11187. });
  11188. },
  11189. /**
  11190. Instructs each child view to render to the passed render buffer.
  11191. @param {Ember.RenderBuffer} buffer the buffer to render to
  11192. @private
  11193. */
  11194. render: function(buffer) {
  11195. this.forEachChildView(function(view) {
  11196. view.renderToBuffer(buffer);
  11197. });
  11198. },
  11199. /**
  11200. When the container view is destroyed, tear down the child views
  11201. array observer.
  11202. @private
  11203. */
  11204. willDestroy: function() {
  11205. get(this, 'childViews').removeArrayObserver(this, {
  11206. willChange: 'childViewsWillChange',
  11207. didChange: 'childViewsDidChange'
  11208. });
  11209. this._super();
  11210. },
  11211. /**
  11212. When a child view is removed, destroy its element so that
  11213. it is removed from the DOM.
  11214. The array observer that triggers this action is set up in the
  11215. `renderToBuffer` method.
  11216. @private
  11217. @param {Ember.Array} views the child views array before mutation
  11218. @param {Number} start the start position of the mutation
  11219. @param {Number} removed the number of child views removed
  11220. **/
  11221. childViewsWillChange: function(views, start, removed) {
  11222. if (removed === 0) { return; }
  11223. var changedViews = views.slice(start, start+removed);
  11224. this.initializeViews(changedViews, null, null);
  11225. this.invokeForState('childViewsWillChange', views, start, removed);
  11226. },
  11227. /**
  11228. When a child view is added, make sure the DOM gets updated appropriately.
  11229. If the view has already rendered an element, we tell the child view to
  11230. create an element and insert it into the DOM. If the enclosing container view
  11231. has already written to a buffer, but not yet converted that buffer into an
  11232. element, we insert the string representation of the child into the appropriate
  11233. place in the buffer.
  11234. @private
  11235. @param {Ember.Array} views the array of child views afte the mutation has occurred
  11236. @param {Number} start the start position of the mutation
  11237. @param {Number} removed the number of child views removed
  11238. @param {Number} the number of child views added
  11239. */
  11240. childViewsDidChange: function(views, start, removed, added) {
  11241. var len = get(views, 'length');
  11242. // No new child views were added; bail out.
  11243. if (added === 0) return;
  11244. var changedViews = views.slice(start, start+added);
  11245. this.initializeViews(changedViews, this, get(this, 'templateData'));
  11246. // Let the current state handle the changes
  11247. this.invokeForState('childViewsDidChange', views, start, added);
  11248. },
  11249. initializeViews: function(views, parentView, templateData) {
  11250. forEach(views, function(view) {
  11251. set(view, '_parentView', parentView);
  11252. if (!get(view, 'templateData')) {
  11253. set(view, 'templateData', templateData);
  11254. }
  11255. });
  11256. },
  11257. /**
  11258. Schedules a child view to be inserted into the DOM after bindings have
  11259. finished syncing for this run loop.
  11260. @param {Ember.View} view the child view to insert
  11261. @param {Ember.View} prev the child view after which the specified view should
  11262. be inserted
  11263. @private
  11264. */
  11265. _scheduleInsertion: function(view, prev) {
  11266. if (prev) {
  11267. prev.domManager.after(prev, view);
  11268. } else {
  11269. this.domManager.prepend(this, view);
  11270. }
  11271. },
  11272. currentView: null,
  11273. _currentViewWillChange: Ember.beforeObserver(function() {
  11274. var childViews = get(this, 'childViews'),
  11275. currentView = get(this, 'currentView');
  11276. if (currentView) {
  11277. childViews.removeObject(currentView);
  11278. currentView.destroy();
  11279. }
  11280. }, 'currentView'),
  11281. _currentViewDidChange: Ember.observer(function() {
  11282. var childViews = get(this, 'childViews'),
  11283. currentView = get(this, 'currentView');
  11284. if (currentView) {
  11285. childViews.pushObject(currentView);
  11286. }
  11287. }, 'currentView')
  11288. });
  11289. // Ember.ContainerView extends the default view states to provide different
  11290. // behavior for childViewsWillChange and childViewsDidChange.
  11291. Ember.ContainerView.states = {
  11292. parent: Ember.View.states,
  11293. inBuffer: {
  11294. childViewsDidChange: function(parentView, views, start, added) {
  11295. var buffer = parentView.buffer,
  11296. startWith, prev, prevBuffer, view;
  11297. // Determine where to begin inserting the child view(s) in the
  11298. // render buffer.
  11299. if (start === 0) {
  11300. // If views were inserted at the beginning, prepend the first
  11301. // view to the render buffer, then begin inserting any
  11302. // additional views at the beginning.
  11303. view = views[start];
  11304. startWith = start + 1;
  11305. view.renderToBuffer(buffer, 'prepend');
  11306. } else {
  11307. // Otherwise, just insert them at the same place as the child
  11308. // views mutation.
  11309. view = views[start - 1];
  11310. startWith = start;
  11311. }
  11312. for (var i=startWith; i<start+added; i++) {
  11313. prev = view;
  11314. view = views[i];
  11315. prevBuffer = prev.buffer;
  11316. view.renderToBuffer(prevBuffer, 'insertAfter');
  11317. }
  11318. }
  11319. },
  11320. hasElement: {
  11321. childViewsWillChange: function(view, views, start, removed) {
  11322. for (var i=start; i<start+removed; i++) {
  11323. views[i].remove();
  11324. }
  11325. },
  11326. childViewsDidChange: function(view, views, start, added) {
  11327. // If the DOM element for this container view already exists,
  11328. // schedule each child view to insert its DOM representation after
  11329. // bindings have finished syncing.
  11330. var prev = start === 0 ? null : views[start-1];
  11331. for (var i=start; i<start+added; i++) {
  11332. view = views[i];
  11333. this._scheduleInsertion(view, prev);
  11334. prev = view;
  11335. }
  11336. }
  11337. }
  11338. };
  11339. Ember.ContainerView.states.inDOM = {
  11340. parentState: Ember.ContainerView.states.hasElement
  11341. };
  11342. Ember.ContainerView.reopen({
  11343. states: Ember.ContainerView.states
  11344. });
  11345. })();
  11346. (function() {
  11347. // ==========================================================================
  11348. // Project: Ember - JavaScript Application Framework
  11349. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  11350. // Portions ©2008-2011 Apple Inc. All rights reserved.
  11351. // License: Licensed under MIT license (see license.js)
  11352. // ==========================================================================
  11353. var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt;
  11354. /**
  11355. @class
  11356. `Ember.CollectionView` is an `Ember.View` descendent responsible for managing a
  11357. collection (an array or array-like object) by maintaing a child view object and
  11358. associated DOM representation for each item in the array and ensuring that child
  11359. views and their associated rendered HTML are updated when items in the array
  11360. are added, removed, or replaced.
  11361. ## Setting content
  11362. The managed collection of objects is referenced as the `Ember.CollectionView` instance's
  11363. `content` property.
  11364. someItemsView = Ember.CollectionView.create({
  11365. content: ['A', 'B','C']
  11366. })
  11367. The view for each item in the collection will have its `content` property set
  11368. to the item.
  11369. ## Specifying itemViewClass
  11370. By default the view class for each item in the managed collection will be an instance
  11371. of `Ember.View`. You can supply a different class by setting the `CollectionView`'s
  11372. `itemViewClass` property.
  11373. Given an empty `<body>` and the following code:
  11374. someItemsView = Ember.CollectionView.create({
  11375. classNames: ['a-collection'],
  11376. content: ['A','B','C'],
  11377. itemViewClass: Ember.View.extend({
  11378. template: Ember.Handlebars.compile("the letter: {{view.content}}")
  11379. })
  11380. })
  11381. someItemsView.appendTo('body')
  11382. Will result in the following HTML structure
  11383. <div class="ember-view a-collection">
  11384. <div class="ember-view">the letter: A</div>
  11385. <div class="ember-view">the letter: B</div>
  11386. <div class="ember-view">the letter: C</div>
  11387. </div>
  11388. ## Automatic matching of parent/child tagNames
  11389. Setting the `tagName` property of a `CollectionView` to any of
  11390. "ul", "ol", "table", "thead", "tbody", "tfoot", "tr", or "select" will result
  11391. in the item views receiving an appropriately matched `tagName` property.
  11392. Given an empty `<body>` and the following code:
  11393. anUndorderedListView = Ember.CollectionView.create({
  11394. tagName: 'ul',
  11395. content: ['A','B','C'],
  11396. itemViewClass: Ember.View.extend({
  11397. template: Ember.Handlebars.compile("the letter: {{view.content}}")
  11398. })
  11399. })
  11400. anUndorderedListView.appendTo('body')
  11401. Will result in the following HTML structure
  11402. <ul class="ember-view a-collection">
  11403. <li class="ember-view">the letter: A</li>
  11404. <li class="ember-view">the letter: B</li>
  11405. <li class="ember-view">the letter: C</li>
  11406. </ul>
  11407. Additional tagName pairs can be provided by adding to `Ember.CollectionView.CONTAINER_MAP `
  11408. Ember.CollectionView.CONTAINER_MAP['article'] = 'section'
  11409. ## Empty View
  11410. You can provide an `Ember.View` subclass to the `Ember.CollectionView` instance as its
  11411. `emptyView` property. If the `content` property of a `CollectionView` is set to `null`
  11412. or an empty array, an instance of this view will be the `CollectionView`s only child.
  11413. aListWithNothing = Ember.CollectionView.create({
  11414. classNames: ['nothing']
  11415. content: null,
  11416. emptyView: Ember.View.extend({
  11417. template: Ember.Handlebars.compile("The collection is empty")
  11418. })
  11419. })
  11420. aListWithNothing.appendTo('body')
  11421. Will result in the following HTML structure
  11422. <div class="ember-view nothing">
  11423. <div class="ember-view">
  11424. The collection is empty
  11425. </div>
  11426. </div>
  11427. ## Adding and Removing items
  11428. The `childViews` property of a `CollectionView` should not be directly manipulated. Instead,
  11429. add, remove, replace items from its `content` property. This will trigger
  11430. appropriate changes to its rendered HTML.
  11431. ## Use in templates via the `{{collection}}` Ember.Handlebars helper
  11432. Ember.Handlebars provides a helper specifically for adding `CollectionView`s to templates.
  11433. See `Ember.Handlebars.collection` for more details
  11434. @since Ember 0.9
  11435. @extends Ember.ContainerView
  11436. */
  11437. Ember.CollectionView = Ember.ContainerView.extend(
  11438. /** @scope Ember.CollectionView.prototype */ {
  11439. /**
  11440. A list of items to be displayed by the Ember.CollectionView.
  11441. @type Ember.Array
  11442. @default null
  11443. */
  11444. content: null,
  11445. /**
  11446. @private
  11447. This provides metadata about what kind of empty view class this
  11448. collection would like if it is being instantiated from another
  11449. system (like Handlebars)
  11450. */
  11451. emptyViewClass: Ember.View,
  11452. /**
  11453. An optional view to display if content is set to an empty array.
  11454. @type Ember.View
  11455. @default null
  11456. */
  11457. emptyView: null,
  11458. /**
  11459. @type Ember.View
  11460. @default Ember.View
  11461. */
  11462. itemViewClass: Ember.View,
  11463. /** @private */
  11464. init: function() {
  11465. var ret = this._super();
  11466. this._contentDidChange();
  11467. return ret;
  11468. },
  11469. _contentWillChange: Ember.beforeObserver(function() {
  11470. var content = this.get('content');
  11471. if (content) { content.removeArrayObserver(this); }
  11472. var len = content ? get(content, 'length') : 0;
  11473. this.arrayWillChange(content, 0, len);
  11474. }, 'content'),
  11475. /**
  11476. @private
  11477. Check to make sure that the content has changed, and if so,
  11478. update the children directly. This is always scheduled
  11479. asynchronously, to allow the element to be created before
  11480. bindings have synchronized and vice versa.
  11481. */
  11482. _contentDidChange: Ember.observer(function() {
  11483. var content = get(this, 'content');
  11484. if (content) {
  11485. Ember.assert(fmt("an Ember.CollectionView's content must implement Ember.Array. You passed %@", [content]), Ember.Array.detect(content));
  11486. content.addArrayObserver(this);
  11487. }
  11488. var len = content ? get(content, 'length') : 0;
  11489. this.arrayDidChange(content, 0, null, len);
  11490. }, 'content'),
  11491. willDestroy: function() {
  11492. var content = get(this, 'content');
  11493. if (content) { content.removeArrayObserver(this); }
  11494. this._super();
  11495. },
  11496. arrayWillChange: function(content, start, removedCount) {
  11497. // If the contents were empty before and this template collection has an
  11498. // empty view remove it now.
  11499. var emptyView = get(this, 'emptyView');
  11500. if (emptyView && emptyView instanceof Ember.View) {
  11501. emptyView.removeFromParent();
  11502. }
  11503. // Loop through child views that correspond with the removed items.
  11504. // Note that we loop from the end of the array to the beginning because
  11505. // we are mutating it as we go.
  11506. var childViews = get(this, 'childViews'), childView, idx, len;
  11507. len = get(childViews, 'length');
  11508. var removingAll = removedCount === len;
  11509. if (removingAll) {
  11510. this.invokeForState('empty');
  11511. }
  11512. for (idx = start + removedCount - 1; idx >= start; idx--) {
  11513. childView = childViews[idx];
  11514. if (removingAll) { childView.removedFromDOM = true; }
  11515. childView.destroy();
  11516. }
  11517. },
  11518. /**
  11519. Called when a mutation to the underlying content array occurs.
  11520. This method will replay that mutation against the views that compose the
  11521. Ember.CollectionView, ensuring that the view reflects the model.
  11522. This array observer is added in contentDidChange.
  11523. @param {Array} addedObjects
  11524. the objects that were added to the content
  11525. @param {Array} removedObjects
  11526. the objects that were removed from the content
  11527. @param {Number} changeIndex
  11528. the index at which the changes occurred
  11529. */
  11530. arrayDidChange: function(content, start, removed, added) {
  11531. var itemViewClass = get(this, 'itemViewClass'),
  11532. childViews = get(this, 'childViews'),
  11533. addedViews = [], view, item, idx, len, itemTagName;
  11534. if ('string' === typeof itemViewClass) {
  11535. itemViewClass = get(itemViewClass);
  11536. }
  11537. Ember.assert(fmt("itemViewClass must be a subclass of Ember.View, not %@", [itemViewClass]), Ember.View.detect(itemViewClass));
  11538. len = content ? get(content, 'length') : 0;
  11539. if (len) {
  11540. for (idx = start; idx < start+added; idx++) {
  11541. item = content.objectAt(idx);
  11542. view = this.createChildView(itemViewClass, {
  11543. content: item,
  11544. contentIndex: idx
  11545. });
  11546. addedViews.push(view);
  11547. }
  11548. } else {
  11549. var emptyView = get(this, 'emptyView');
  11550. if (!emptyView) { return; }
  11551. emptyView = this.createChildView(emptyView);
  11552. addedViews.push(emptyView);
  11553. set(this, 'emptyView', emptyView);
  11554. }
  11555. childViews.replace(start, 0, addedViews);
  11556. },
  11557. createChildView: function(view, attrs) {
  11558. view = this._super(view, attrs);
  11559. var itemTagName = get(view, 'tagName');
  11560. var tagName = (itemTagName === null || itemTagName === undefined) ? Ember.CollectionView.CONTAINER_MAP[get(this, 'tagName')] : itemTagName;
  11561. set(view, 'tagName', tagName);
  11562. return view;
  11563. }
  11564. });
  11565. /**
  11566. @static
  11567. A map of parent tags to their default child tags. You can add
  11568. additional parent tags if you want collection views that use
  11569. a particular parent tag to default to a child tag.
  11570. @type Hash
  11571. @constant
  11572. */
  11573. Ember.CollectionView.CONTAINER_MAP = {
  11574. ul: 'li',
  11575. ol: 'li',
  11576. table: 'tr',
  11577. thead: 'tr',
  11578. tbody: 'tr',
  11579. tfoot: 'tr',
  11580. tr: 'td',
  11581. select: 'option'
  11582. };
  11583. })();
  11584. (function() {
  11585. // ==========================================================================
  11586. // Project: Ember - JavaScript Application Framework
  11587. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  11588. // Portions ©2008-2011 Apple Inc. All rights reserved.
  11589. // License: Licensed under MIT license (see license.js)
  11590. // ==========================================================================
  11591. })();
  11592. (function() {
  11593. // ==========================================================================
  11594. // Project: Ember - JavaScript Application Framework
  11595. // Copyright: ©2006-2011 Strobe Inc. and contributors.
  11596. // Portions ©2008-2011 Apple Inc. All rights reserved.
  11597. // License: Licensed under MIT license (see license.js)
  11598. // ==========================================================================
  11599. /*globals jQuery*/
  11600. })();
  11601. (function() {
  11602. var get = Ember.get, set = Ember.set;
  11603. /**
  11604. @class
  11605. @extends Ember.Object
  11606. */
  11607. Ember.State = Ember.Object.extend(Ember.Evented,
  11608. /** @scope Ember.State.prototype */{
  11609. isState: true,
  11610. /**
  11611. A reference to the parent state.
  11612. @type Ember.State
  11613. */
  11614. parentState: null,
  11615. start: null,
  11616. /**
  11617. The name of this state.
  11618. @type String
  11619. */
  11620. name: null,
  11621. /**
  11622. The full path to this state.
  11623. @type String
  11624. @readOnly
  11625. */
  11626. path: Ember.computed(function() {
  11627. var parentPath = get(this, 'parentState.path'),
  11628. path = get(this, 'name');
  11629. if (parentPath) {
  11630. path = parentPath + '.' + path;
  11631. }
  11632. return path;
  11633. }).property().cacheable(),
  11634. /**
  11635. @private
  11636. Override the default event firing from Ember.Evented to
  11637. also call methods with the given name.
  11638. */
  11639. trigger: function(name) {
  11640. if (this[name]) {
  11641. this[name].apply(this, [].slice.call(arguments, 1));
  11642. }
  11643. this._super.apply(this, arguments);
  11644. },
  11645. /** @private */
  11646. init: function() {
  11647. var states = get(this, 'states'), foundStates;
  11648. set(this, 'childStates', Ember.A());
  11649. set(this, 'eventTransitions', get(this, 'eventTransitions') || {});
  11650. var name, value, transitionTarget;
  11651. // As a convenience, loop over the properties
  11652. // of this state and look for any that are other
  11653. // Ember.State instances or classes, and move them
  11654. // to the `states` hash. This avoids having to
  11655. // create an explicit separate hash.
  11656. if (!states) {
  11657. states = {};
  11658. for (name in this) {
  11659. if (name === "constructor") { continue; }
  11660. if (value = this[name]) {
  11661. if (transitionTarget = value.transitionTarget) {
  11662. this.eventTransitions[name] = transitionTarget;
  11663. }
  11664. this.setupChild(states, name, value);
  11665. }
  11666. }
  11667. set(this, 'states', states);
  11668. } else {
  11669. for (name in states) {
  11670. this.setupChild(states, name, states[name]);
  11671. }
  11672. }
  11673. set(this, 'pathsCache', {});
  11674. set(this, 'pathsCacheNoContext', {});
  11675. },
  11676. /** @private */
  11677. setupChild: function(states, name, value) {
  11678. if (!value) { return false; }
  11679. if (value.isState) {
  11680. set(value, 'name', name);
  11681. } else if (Ember.State.detect(value)) {
  11682. value = value.create({
  11683. name: name
  11684. });
  11685. }
  11686. if (value.isState) {
  11687. set(value, 'parentState', this);
  11688. get(this, 'childStates').pushObject(value);
  11689. states[name] = value;
  11690. }
  11691. },
  11692. lookupEventTransition: function(name) {
  11693. var path, state = this;
  11694. while(state && !path) {
  11695. path = state.eventTransitions[name];
  11696. state = state.get('parentState');
  11697. }
  11698. return path;
  11699. },
  11700. /**
  11701. A Boolean value indicating whether the state is a leaf state
  11702. in the state hierarchy. This is false if the state has child
  11703. states; otherwise it is true.
  11704. @type Boolean
  11705. */
  11706. isLeaf: Ember.computed(function() {
  11707. return !get(this, 'childStates').length;
  11708. }).cacheable(),
  11709. /**
  11710. A boolean value indicating whether the state takes a context.
  11711. By default we assume all states take contexts.
  11712. */
  11713. hasContext: true,
  11714. /**
  11715. This is the default transition event.
  11716. @event
  11717. @param {Ember.StateManager} manager
  11718. @param context
  11719. @see Ember.StateManager#transitionEvent
  11720. */
  11721. setup: Ember.K,
  11722. /**
  11723. This event fires when the state is entered.
  11724. @event
  11725. @param {Ember.StateManager} manager
  11726. */
  11727. enter: Ember.K,
  11728. /**
  11729. This event fires when the state is exited.
  11730. @event
  11731. @param {Ember.StateManager} manager
  11732. */
  11733. exit: Ember.K
  11734. });
  11735. var Event = Ember.$ && Ember.$.Event;
  11736. Ember.State.reopenClass(
  11737. /** @scope Ember.State */{
  11738. /**
  11739. @static
  11740. Creates an action function for transitioning to the named state while preserving context.
  11741. The following example StateManagers are equivalent:
  11742. aManager = Ember.StateManager.create({
  11743. stateOne: Ember.State.create({
  11744. changeToStateTwo: Ember.State.transitionTo('stateTwo')
  11745. }),
  11746. stateTwo: Ember.State.create({})
  11747. })
  11748. bManager = Ember.StateManager.create({
  11749. stateOne: Ember.State.create({
  11750. changeToStateTwo: function(manager, context){
  11751. manager.transitionTo('stateTwo', context)
  11752. }
  11753. }),
  11754. stateTwo: Ember.State.create({})
  11755. })
  11756. @param {String} target
  11757. */
  11758. transitionTo: function(target) {
  11759. var event = function(stateManager, context) {
  11760. if (Event && context instanceof Event) {
  11761. if (context.hasOwnProperty('context')) {
  11762. context = context.context;
  11763. } else {
  11764. // If we received an event and it doesn't contain
  11765. // a context, don't pass along a superfluous
  11766. // context to the target of the event.
  11767. return stateManager.transitionTo(target);
  11768. }
  11769. }
  11770. stateManager.transitionTo(target, context);
  11771. };
  11772. event.transitionTarget = target;
  11773. return event;
  11774. }
  11775. });
  11776. })();
  11777. (function() {
  11778. var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt;
  11779. var arrayForEach = Ember.ArrayPolyfills.forEach;
  11780. /**
  11781. @private
  11782. A Transition takes the enter, exit and resolve states and normalizes
  11783. them:
  11784. * takes any passed in contexts into consideration
  11785. * adds in `initialState`s
  11786. */
  11787. var Transition = function(raw) {
  11788. this.enterStates = raw.enterStates.slice();
  11789. this.exitStates = raw.exitStates.slice();
  11790. this.resolveState = raw.resolveState;
  11791. this.finalState = raw.enterStates[raw.enterStates.length - 1] || raw.resolveState;
  11792. };
  11793. Transition.prototype = {
  11794. /**
  11795. @private
  11796. Normalize the passed in enter, exit and resolve states.
  11797. This process also adds `finalState` and `contexts` to the Transition object.
  11798. @param {Ember.StateManager} manager the state manager running the transition
  11799. @param {Array} contexts a list of contexts passed into `transitionTo`
  11800. */
  11801. normalize: function(manager, contexts) {
  11802. this.matchContextsToStates(contexts);
  11803. this.addInitialStates();
  11804. this.removeUnchangedContexts(manager);
  11805. return this;
  11806. },
  11807. /**
  11808. @private
  11809. Match each of the contexts passed to `transitionTo` to a state.
  11810. This process may also require adding additional enter and exit
  11811. states if there are more contexts than enter states.
  11812. @param {Array} contexts a list of contexts passed into `transitionTo`
  11813. */
  11814. matchContextsToStates: function(contexts) {
  11815. var stateIdx = this.enterStates.length - 1,
  11816. matchedContexts = [],
  11817. state,
  11818. context;
  11819. // Next, we will match the passed in contexts to the states they
  11820. // represent.
  11821. //
  11822. // First, assign a context to each enter state in reverse order. If
  11823. // any contexts are left, add a parent state to the list of states
  11824. // to enter and exit, and assign a context to the parent state.
  11825. //
  11826. // If there are still contexts left when the state manager is
  11827. // reached, raise an exception.
  11828. //
  11829. // This allows the following:
  11830. //
  11831. // |- root
  11832. // | |- post
  11833. // | | |- comments
  11834. // | |- about (* current state)
  11835. //
  11836. // For `transitionTo('post.comments', post, post.get('comments')`,
  11837. // the first context (`post`) will be assigned to `root.post`, and
  11838. // the second context (`post.get('comments')`) will be assigned
  11839. // to `root.post.comments`.
  11840. //
  11841. // For the following:
  11842. //
  11843. // |- root
  11844. // | |- post
  11845. // | | |- index (* current state)
  11846. // | | |- comments
  11847. //
  11848. // For `transitionTo('post.comments', otherPost, otherPost.get('comments')`,
  11849. // the `<root.post>` state will be added to the list of enter and exit
  11850. // states because its context has changed.
  11851. while (contexts.length > 0) {
  11852. if (stateIdx >= 0) {
  11853. state = this.enterStates[stateIdx--];
  11854. } else {
  11855. if (this.enterStates.length) {
  11856. state = get(this.enterStates[0], 'parentState');
  11857. if (!state) { throw "Cannot match all contexts to states"; }
  11858. } else {
  11859. // If re-entering the current state with a context, the resolve
  11860. // state will be the current state.
  11861. state = this.resolveState;
  11862. }
  11863. this.enterStates.unshift(state);
  11864. this.exitStates.unshift(state);
  11865. }
  11866. // in routers, only states with dynamic segments have a context
  11867. if (get(state, 'hasContext')) {
  11868. context = contexts.pop();
  11869. } else {
  11870. context = null;
  11871. }
  11872. matchedContexts.unshift(context);
  11873. }
  11874. this.contexts = matchedContexts;
  11875. },
  11876. /**
  11877. @private
  11878. Add any `initialState`s to the list of enter states.
  11879. */
  11880. addInitialStates: function() {
  11881. var finalState = this.finalState, initialState;
  11882. while(true) {
  11883. initialState = get(finalState, 'initialState') || 'start';
  11884. finalState = get(finalState, 'states.' + initialState);
  11885. if (!finalState) { break; }
  11886. this.finalState = finalState;
  11887. this.enterStates.push(finalState);
  11888. this.contexts.push(undefined);
  11889. }
  11890. },
  11891. /**
  11892. @private
  11893. Remove any states that were added because the number of contexts
  11894. exceeded the number of explicit enter states, but the context has
  11895. not changed since the last time the state was entered.
  11896. @param {Ember.StateManager} manager passed in to look up the last
  11897. context for a states
  11898. */
  11899. removeUnchangedContexts: function(manager) {
  11900. // Start from the beginning of the enter states. If the state was added
  11901. // to the list during the context matching phase, make sure the context
  11902. // has actually changed since the last time the state was entered.
  11903. while (this.enterStates.length > 0) {
  11904. if (this.enterStates[0] !== this.exitStates[0]) { break; }
  11905. if (this.enterStates.length === this.contexts.length) {
  11906. if (manager.getStateMeta(this.enterStates[0], 'context') !== this.contexts[0]) { break; }
  11907. this.contexts.shift();
  11908. }
  11909. this.resolveState = this.enterStates.shift();
  11910. this.exitStates.shift();
  11911. }
  11912. }
  11913. };
  11914. /**
  11915. @class
  11916. StateManager is part of Ember's implementation of a finite state machine. A StateManager
  11917. instance manages a number of properties that are instances of `Ember.State`,
  11918. tracks the current active state, and triggers callbacks when states have changed.
  11919. ## Defining States
  11920. The states of StateManager can be declared in one of two ways. First, you can define
  11921. a `states` property that contains all the states:
  11922. managerA = Ember.StateManager.create({
  11923. states: {
  11924. stateOne: Ember.State.create(),
  11925. stateTwo: Ember.State.create()
  11926. }
  11927. })
  11928. managerA.get('states')
  11929. // {
  11930. // stateOne: Ember.State.create(),
  11931. // stateTwo: Ember.State.create()
  11932. // }
  11933. You can also add instances of `Ember.State` (or an `Ember.State` subclass) directly as properties
  11934. of a StateManager. These states will be collected into the `states` property for you.
  11935. managerA = Ember.StateManager.create({
  11936. stateOne: Ember.State.create(),
  11937. stateTwo: Ember.State.create()
  11938. })
  11939. managerA.get('states')
  11940. // {
  11941. // stateOne: Ember.State.create(),
  11942. // stateTwo: Ember.State.create()
  11943. // }
  11944. ## The Initial State
  11945. When created a StateManager instance will immediately enter into the state
  11946. defined as its `start` property or the state referenced by name in its
  11947. `initialState` property:
  11948. managerA = Ember.StateManager.create({
  11949. start: Ember.State.create({})
  11950. })
  11951. managerA.get('currentState.name') // 'start'
  11952. managerB = Ember.StateManager.create({
  11953. initialState: 'beginHere',
  11954. beginHere: Ember.State.create({})
  11955. })
  11956. managerB.get('currentState.name') // 'beginHere'
  11957. Because it is a property you may also provide a computed function if you wish to derive
  11958. an `initialState` programmatically:
  11959. managerC = Ember.StateManager.create({
  11960. initialState: function(){
  11961. if (someLogic) {
  11962. return 'active';
  11963. } else {
  11964. return 'passive';
  11965. }
  11966. }.property(),
  11967. active: Ember.State.create({}),
  11968. passive: Ember.State.create({})
  11969. })
  11970. ## Moving Between States
  11971. A StateManager can have any number of Ember.State objects as properties
  11972. and can have a single one of these states as its current state.
  11973. Calling `transitionTo` transitions between states:
  11974. robotManager = Ember.StateManager.create({
  11975. initialState: 'poweredDown',
  11976. poweredDown: Ember.State.create({}),
  11977. poweredUp: Ember.State.create({})
  11978. })
  11979. robotManager.get('currentState.name') // 'poweredDown'
  11980. robotManager.transitionTo('poweredUp')
  11981. robotManager.get('currentState.name') // 'poweredUp'
  11982. Before transitioning into a new state the existing `currentState` will have its
  11983. `exit` method called with the StateManager instance as its first argument and
  11984. an object representing the transition as its second argument.
  11985. After transitioning into a new state the new `currentState` will have its
  11986. `enter` method called with the StateManager instance as its first argument and
  11987. an object representing the transition as its second argument.
  11988. robotManager = Ember.StateManager.create({
  11989. initialState: 'poweredDown',
  11990. poweredDown: Ember.State.create({
  11991. exit: function(stateManager){
  11992. console.log("exiting the poweredDown state")
  11993. }
  11994. }),
  11995. poweredUp: Ember.State.create({
  11996. enter: function(stateManager){
  11997. console.log("entering the poweredUp state. Destroy all humans.")
  11998. }
  11999. })
  12000. })
  12001. robotManager.get('currentState.name') // 'poweredDown'
  12002. robotManager.transitionTo('poweredUp')
  12003. // will log
  12004. // 'exiting the poweredDown state'
  12005. // 'entering the poweredUp state. Destroy all humans.'
  12006. Once a StateManager is already in a state, subsequent attempts to enter that state will
  12007. not trigger enter or exit method calls. Attempts to transition into a state that the
  12008. manager does not have will result in no changes in the StateManager's current state:
  12009. robotManager = Ember.StateManager.create({
  12010. initialState: 'poweredDown',
  12011. poweredDown: Ember.State.create({
  12012. exit: function(stateManager){
  12013. console.log("exiting the poweredDown state")
  12014. }
  12015. }),
  12016. poweredUp: Ember.State.create({
  12017. enter: function(stateManager){
  12018. console.log("entering the poweredUp state. Destroy all humans.")
  12019. }
  12020. })
  12021. })
  12022. robotManager.get('currentState.name') // 'poweredDown'
  12023. robotManager.transitionTo('poweredUp')
  12024. // will log
  12025. // 'exiting the poweredDown state'
  12026. // 'entering the poweredUp state. Destroy all humans.'
  12027. robotManager.transitionTo('poweredUp') // no logging, no state change
  12028. robotManager.transitionTo('someUnknownState') // silently fails
  12029. robotManager.get('currentState.name') // 'poweredUp'
  12030. Each state property may itself contain properties that are instances of Ember.State.
  12031. The StateManager can transition to specific sub-states in a series of transitionTo method calls or
  12032. via a single transitionTo with the full path to the specific state. The StateManager will also
  12033. keep track of the full path to its currentState
  12034. robotManager = Ember.StateManager.create({
  12035. initialState: 'poweredDown',
  12036. poweredDown: Ember.State.create({
  12037. charging: Ember.State.create(),
  12038. charged: Ember.State.create()
  12039. }),
  12040. poweredUp: Ember.State.create({
  12041. mobile: Ember.State.create(),
  12042. stationary: Ember.State.create()
  12043. })
  12044. })
  12045. robotManager.get('currentState.name') // 'poweredDown'
  12046. robotManager.transitionTo('poweredUp')
  12047. robotManager.get('currentState.name') // 'poweredUp'
  12048. robotManager.transitionTo('mobile')
  12049. robotManager.get('currentState.name') // 'mobile'
  12050. // transition via a state path
  12051. robotManager.transitionTo('poweredDown.charging')
  12052. robotManager.get('currentState.name') // 'charging'
  12053. robotManager.get('currentState.path') // 'poweredDown.charging'
  12054. Enter transition methods will be called for each state and nested child state in their
  12055. hierarchical order. Exit methods will be called for each state and its nested states in
  12056. reverse hierarchical order.
  12057. Exit transitions for a parent state are not called when entering into one of its child states,
  12058. only when transitioning to a new section of possible states in the hierarchy.
  12059. robotManager = Ember.StateManager.create({
  12060. initialState: 'poweredDown',
  12061. poweredDown: Ember.State.create({
  12062. enter: function(){},
  12063. exit: function(){
  12064. console.log("exited poweredDown state")
  12065. },
  12066. charging: Ember.State.create({
  12067. enter: function(){},
  12068. exit: function(){}
  12069. }),
  12070. charged: Ember.State.create({
  12071. enter: function(){
  12072. console.log("entered charged state")
  12073. },
  12074. exit: function(){
  12075. console.log("exited charged state")
  12076. }
  12077. })
  12078. }),
  12079. poweredUp: Ember.State.create({
  12080. enter: function(){
  12081. console.log("entered poweredUp state")
  12082. },
  12083. exit: function(){},
  12084. mobile: Ember.State.create({
  12085. enter: function(){
  12086. console.log("entered mobile state")
  12087. },
  12088. exit: function(){}
  12089. }),
  12090. stationary: Ember.State.create({
  12091. enter: function(){},
  12092. exit: function(){}
  12093. })
  12094. })
  12095. })
  12096. robotManager.get('currentState.path') // 'poweredDown'
  12097. robotManager.transitionTo('charged')
  12098. // logs 'entered charged state'
  12099. // but does *not* log 'exited poweredDown state'
  12100. robotManager.get('currentState.name') // 'charged
  12101. robotManager.transitionTo('poweredUp.mobile')
  12102. // logs
  12103. // 'exited charged state'
  12104. // 'exited poweredDown state'
  12105. // 'entered poweredUp state'
  12106. // 'entered mobile state'
  12107. During development you can set a StateManager's `enableLogging` property to `true` to
  12108. receive console messages of state transitions.
  12109. robotManager = Ember.StateManager.create({
  12110. enableLogging: true
  12111. })
  12112. ## Managing currentState with Actions
  12113. To control which transitions between states are possible for a given state, StateManager
  12114. can receive and route action messages to its states via the `send` method. Calling to `send` with
  12115. an action name will begin searching for a method with the same name starting at the current state
  12116. and moving up through the parent states in a state hierarchy until an appropriate method is found
  12117. or the StateManager instance itself is reached.
  12118. If an appropriately named method is found it will be called with the state manager as the first
  12119. argument and an optional `context` object as the second argument.
  12120. managerA = Ember.StateManager.create({
  12121. initialState: 'stateOne.substateOne.subsubstateOne',
  12122. stateOne: Ember.State.create({
  12123. substateOne: Ember.State.create({
  12124. anAction: function(manager, context){
  12125. console.log("an action was called")
  12126. },
  12127. subsubstateOne: Ember.State.create({})
  12128. })
  12129. })
  12130. })
  12131. managerA.get('currentState.name') // 'subsubstateOne'
  12132. managerA.send('anAction')
  12133. // 'stateOne.substateOne.subsubstateOne' has no anAction method
  12134. // so the 'anAction' method of 'stateOne.substateOne' is called
  12135. // and logs "an action was called"
  12136. // with managerA as the first argument
  12137. // and no second argument
  12138. someObject = {}
  12139. managerA.send('anAction', someObject)
  12140. // the 'anAction' method of 'stateOne.substateOne' is called again
  12141. // with managerA as the first argument and
  12142. // someObject as the second argument.
  12143. If the StateManager attempts to send an action but does not find an appropriately named
  12144. method in the current state or while moving upwards through the state hierarchy
  12145. it will throw a new Ember.Error. Action detection only moves upwards through the state hierarchy
  12146. from the current state. It does not search in other portions of the hierarchy.
  12147. managerB = Ember.StateManager.create({
  12148. initialState: 'stateOne.substateOne.subsubstateOne',
  12149. stateOne: Ember.State.create({
  12150. substateOne: Ember.State.create({
  12151. subsubstateOne: Ember.State.create({})
  12152. })
  12153. }),
  12154. stateTwo: Ember.State.create({
  12155. anAction: function(manager, context){
  12156. // will not be called below because it is
  12157. // not a parent of the current state
  12158. }
  12159. })
  12160. })
  12161. managerB.get('currentState.name') // 'subsubstateOne'
  12162. managerB.send('anAction')
  12163. // Error: <Ember.StateManager:ember132> could not
  12164. // respond to event anAction in state stateOne.substateOne.subsubstateOne.
  12165. Inside of an action method the given state should delegate `transitionTo` calls on its
  12166. StateManager.
  12167. robotManager = Ember.StateManager.create({
  12168. initialState: 'poweredDown.charging',
  12169. poweredDown: Ember.State.create({
  12170. charging: Ember.State.create({
  12171. chargeComplete: function(manager, context){
  12172. manager.transitionTo('charged')
  12173. }
  12174. }),
  12175. charged: Ember.State.create({
  12176. boot: function(manager, context){
  12177. manager.transitionTo('poweredUp')
  12178. }
  12179. })
  12180. }),
  12181. poweredUp: Ember.State.create({
  12182. beginExtermination: function(manager, context){
  12183. manager.transitionTo('rampaging')
  12184. },
  12185. rampaging: Ember.State.create()
  12186. })
  12187. })
  12188. robotManager.get('currentState.name') // 'charging'
  12189. robotManager.send('boot') // throws error, no boot action
  12190. // in current hierarchy
  12191. robotManager.get('currentState.name') // remains 'charging'
  12192. robotManager.send('beginExtermination') // throws error, no beginExtermination
  12193. // action in current hierarchy
  12194. robotManager.get('currentState.name') // remains 'charging'
  12195. robotManager.send('chargeComplete')
  12196. robotManager.get('currentState.name') // 'charged'
  12197. robotManager.send('boot')
  12198. robotManager.get('currentState.name') // 'poweredUp'
  12199. robotManager.send('beginExtermination', allHumans)
  12200. robotManager.get('currentState.name') // 'rampaging'
  12201. Transition actions can also be created using the `transitionTo` method of the Ember.State class. The
  12202. following example StateManagers are equivalent:
  12203. aManager = Ember.StateManager.create({
  12204. stateOne: Ember.State.create({
  12205. changeToStateTwo: Ember.State.transitionTo('stateTwo')
  12206. }),
  12207. stateTwo: Ember.State.create({})
  12208. })
  12209. bManager = Ember.StateManager.create({
  12210. stateOne: Ember.State.create({
  12211. changeToStateTwo: function(manager, context){
  12212. manager.transitionTo('stateTwo', context)
  12213. }
  12214. }),
  12215. stateTwo: Ember.State.create({})
  12216. })
  12217. **/
  12218. Ember.StateManager = Ember.State.extend(
  12219. /** @scope Ember.StateManager.prototype */ {
  12220. /**
  12221. When creating a new statemanager, look for a default state to transition
  12222. into. This state can either be named `start`, or can be specified using the
  12223. `initialState` property.
  12224. */
  12225. init: function() {
  12226. this._super();
  12227. set(this, 'stateMeta', Ember.Map.create());
  12228. var initialState = get(this, 'initialState');
  12229. if (!initialState && get(this, 'states.start')) {
  12230. initialState = 'start';
  12231. }
  12232. if (initialState) {
  12233. this.transitionTo(initialState);
  12234. Ember.assert('Failed to transition to initial state "' + initialState + '"', !!get(this, 'currentState'));
  12235. }
  12236. },
  12237. stateMetaFor: function(state) {
  12238. var meta = get(this, 'stateMeta'),
  12239. stateMeta = meta.get(state);
  12240. if (!stateMeta) {
  12241. stateMeta = {};
  12242. meta.set(state, stateMeta);
  12243. }
  12244. return stateMeta;
  12245. },
  12246. setStateMeta: function(state, key, value) {
  12247. return set(this.stateMetaFor(state), key, value);
  12248. },
  12249. getStateMeta: function(state, key) {
  12250. return get(this.stateMetaFor(state), key);
  12251. },
  12252. /**
  12253. The current state from among the manager's possible states. This property should
  12254. not be set directly. Use `transitionTo` to move between states by name.
  12255. @type Ember.State
  12256. @readOnly
  12257. */
  12258. currentState: null,
  12259. /**
  12260. The name of transitionEvent that this stateManager will dispatch
  12261. @property {String}
  12262. @default 'setup'
  12263. */
  12264. transitionEvent: 'setup',
  12265. /**
  12266. If set to true, `errorOnUnhandledEvents` will cause an exception to be
  12267. raised if you attempt to send an event to a state manager that is not
  12268. handled by the current state or any of its parent states.
  12269. @type Boolean
  12270. @default true
  12271. */
  12272. errorOnUnhandledEvent: true,
  12273. send: function(event, context) {
  12274. Ember.assert('Cannot send event "' + event + '" while currentState is ' + get(this, 'currentState'), get(this, 'currentState'));
  12275. return this.sendRecursively(event, get(this, 'currentState'), context);
  12276. },
  12277. sendRecursively: function(event, currentState, context) {
  12278. var log = this.enableLogging,
  12279. action = currentState[event];
  12280. // Test to see if the action is a method that
  12281. // can be invoked. Don't blindly check just for
  12282. // existence, because it is possible the state
  12283. // manager has a child state of the given name,
  12284. // and we should still raise an exception in that
  12285. // case.
  12286. if (typeof action === 'function') {
  12287. if (log) { Ember.Logger.log(fmt("STATEMANAGER: Sending event '%@' to state %@.", [event, get(currentState, 'path')])); }
  12288. return action.call(currentState, this, context);
  12289. } else {
  12290. var parentState = get(currentState, 'parentState');
  12291. if (parentState) {
  12292. return this.sendRecursively(event, parentState, context);
  12293. } else if (get(this, 'errorOnUnhandledEvent')) {
  12294. throw new Ember.Error(this.toString() + " could not respond to event " + event + " in state " + get(this, 'currentState.path') + ".");
  12295. }
  12296. }
  12297. },
  12298. /**
  12299. Finds a state by its state path.
  12300. Example:
  12301. manager = Ember.StateManager.create({
  12302. root: Ember.State.create({
  12303. dashboard: Ember.State.create()
  12304. })
  12305. });
  12306. manager.getStateByPath(manager, "root.dashboard")
  12307. // returns the dashboard state
  12308. @param {Ember.State} root the state to start searching from
  12309. @param {String} path the state path to follow
  12310. @returns {Ember.State} the state at the end of the path
  12311. */
  12312. getStateByPath: function(root, path) {
  12313. var parts = path.split('.'),
  12314. state = root;
  12315. for (var i=0, l=parts.length; i<l; i++) {
  12316. state = get(get(state, 'states'), parts[i]);
  12317. if (!state) { break; }
  12318. }
  12319. return state;
  12320. },
  12321. findStateByPath: function(state, path) {
  12322. var possible;
  12323. while (!possible && state) {
  12324. possible = this.getStateByPath(state, path);
  12325. state = get(state, 'parentState');
  12326. }
  12327. return possible;
  12328. },
  12329. /**
  12330. @private
  12331. A state stores its child states in its `states` hash.
  12332. This code takes a path like `posts.show` and looks
  12333. up `origin.states.posts.states.show`.
  12334. It returns a list of all of the states from the
  12335. origin, which is the list of states to call `enter`
  12336. on.
  12337. */
  12338. findStatesByPath: function(origin, path) {
  12339. if (!path || path === "") { return undefined; }
  12340. var r = path.split('.'),
  12341. ret = [];
  12342. for (var i=0, len = r.length; i < len; i++) {
  12343. var states = get(origin, 'states');
  12344. if (!states) { return undefined; }
  12345. var s = get(states, r[i]);
  12346. if (s) { origin = s; ret.push(s); }
  12347. else { return undefined; }
  12348. }
  12349. return ret;
  12350. },
  12351. goToState: function() {
  12352. // not deprecating this yet so people don't constantly need to
  12353. // make trivial changes for little reason.
  12354. return this.transitionTo.apply(this, arguments);
  12355. },
  12356. transitionTo: function(path, context) {
  12357. // XXX When is transitionTo called with no path
  12358. if (Ember.empty(path)) { return; }
  12359. // The ES6 signature of this function is `path, ...contexts`
  12360. var contexts = context ? Array.prototype.slice.call(arguments, 1) : [],
  12361. currentState = get(this, 'currentState') || this;
  12362. // First, get the enter, exit and resolve states for the current state
  12363. // and specified path. If possible, use an existing cache.
  12364. var hash = this.contextFreeTransition(currentState, path);
  12365. // Next, process the raw state information for the contexts passed in.
  12366. var transition = new Transition(hash).normalize(this, contexts);
  12367. this.enterState(transition);
  12368. this.triggerSetupContext(transition);
  12369. },
  12370. contextFreeTransition: function(currentState, path) {
  12371. var cache = currentState.pathsCache[path];
  12372. if (cache) { return cache; }
  12373. var enterStates = this.findStatesByPath(currentState, path),
  12374. exitStates = [],
  12375. resolveState = currentState;
  12376. // Walk up the states. For each state, check whether a state matching
  12377. // the `path` is nested underneath. This will find the closest
  12378. // parent state containing `path`.
  12379. //
  12380. // This allows the user to pass in a relative path. For example, for
  12381. // the following state hierarchy:
  12382. //
  12383. // | |root
  12384. // | |- posts
  12385. // | | |- show (* current)
  12386. // | |- comments
  12387. // | | |- show
  12388. //
  12389. // If the current state is `<root.posts.show>`, an attempt to
  12390. // transition to `comments.show` will match `<root.comments.show>`.
  12391. //
  12392. // First, this code will look for root.posts.show.comments.show.
  12393. // Next, it will look for root.posts.comments.show. Finally,
  12394. // it will look for `root.comments.show`, and find the state.
  12395. //
  12396. // After this process, the following variables will exist:
  12397. //
  12398. // * resolveState: a common parent state between the current
  12399. // and target state. In the above example, `<root>` is the
  12400. // `resolveState`.
  12401. // * enterStates: a list of all of the states represented
  12402. // by the path from the `resolveState`. For example, for
  12403. // the path `root.comments.show`, `enterStates` would have
  12404. // `[<root.comments>, <root.comments.show>]`
  12405. // * exitStates: a list of all of the states from the
  12406. // `resolveState` to the `currentState`. In the above
  12407. // example, `exitStates` would have
  12408. // `[<root.posts>`, `<root.posts.show>]`.
  12409. while (resolveState && !enterStates) {
  12410. exitStates.unshift(resolveState);
  12411. resolveState = get(resolveState, 'parentState');
  12412. if (!resolveState) {
  12413. enterStates = this.findStatesByPath(this, path);
  12414. if (!enterStates) {
  12415. Ember.assert('Could not find state for path: "'+path+'"');
  12416. return;
  12417. }
  12418. }
  12419. enterStates = this.findStatesByPath(resolveState, path);
  12420. }
  12421. // If the path contains some states that are parents of both the
  12422. // current state and the target state, remove them.
  12423. //
  12424. // For example, in the following hierarchy:
  12425. //
  12426. // |- root
  12427. // | |- post
  12428. // | | |- index (* current)
  12429. // | | |- show
  12430. //
  12431. // If the `path` is `root.post.show`, the three variables will
  12432. // be:
  12433. //
  12434. // * resolveState: `<state manager>`
  12435. // * enterStates: `[<root>, <root.post>, <root.post.show>]`
  12436. // * exitStates: `[<root>, <root.post>, <root.post.index>]`
  12437. //
  12438. // The goal of this code is to remove the common states, so we
  12439. // have:
  12440. //
  12441. // * resolveState: `<root.post>`
  12442. // * enterStates: `[<root.post.show>]`
  12443. // * exitStates: `[<root.post.index>]`
  12444. //
  12445. // This avoid unnecessary calls to the enter and exit transitions.
  12446. while (enterStates.length > 0 && enterStates[0] === exitStates[0]) {
  12447. resolveState = enterStates.shift();
  12448. exitStates.shift();
  12449. }
  12450. // Cache the enterStates, exitStates, and resolveState for the
  12451. // current state and the `path`.
  12452. var transitions = currentState.pathsCache[path] = {
  12453. exitStates: exitStates,
  12454. enterStates: enterStates,
  12455. resolveState: resolveState
  12456. };
  12457. return transitions;
  12458. },
  12459. triggerSetupContext: function(transitions) {
  12460. var contexts = transitions.contexts,
  12461. offset = transitions.enterStates.length - contexts.length,
  12462. enterStates = transitions.enterStates,
  12463. transitionEvent = get(this, 'transitionEvent');
  12464. Ember.assert("More contexts provided than states", offset >= 0);
  12465. arrayForEach.call(enterStates, function(state, idx) {
  12466. state.trigger(transitionEvent, this, contexts[idx-offset]);
  12467. }, this);
  12468. },
  12469. getState: function(name) {
  12470. var state = get(this, name),
  12471. parentState = get(this, 'parentState');
  12472. if (state) {
  12473. return state;
  12474. } else if (parentState) {
  12475. return parentState.getState(name);
  12476. }
  12477. },
  12478. enterState: function(transition) {
  12479. var log = this.enableLogging;
  12480. var exitStates = transition.exitStates.slice(0).reverse();
  12481. arrayForEach.call(exitStates, function(state) {
  12482. state.trigger('exit', this);
  12483. }, this);
  12484. arrayForEach.call(transition.enterStates, function(state) {
  12485. if (log) { Ember.Logger.log("STATEMANAGER: Entering " + get(state, 'path')); }
  12486. state.trigger('enter', this);
  12487. }, this);
  12488. set(this, 'currentState', transition.finalState);
  12489. }
  12490. });
  12491. })();
  12492. (function() {
  12493. // ==========================================================================
  12494. // Project: Ember Statecharts
  12495. // Copyright: ©2011 Living Social Inc. and contributors.
  12496. // License: Licensed under MIT license (see license.js)
  12497. // ==========================================================================
  12498. })();
  12499. (function() {
  12500. var get = Ember.get;
  12501. Ember._ResolvedState = Ember.Object.extend({
  12502. manager: null,
  12503. state: null,
  12504. match: null,
  12505. object: Ember.computed(function(key, value) {
  12506. if (arguments.length === 2) {
  12507. this._object = value;
  12508. return value;
  12509. } else {
  12510. if (this._object) {
  12511. return this._object;
  12512. } else {
  12513. var state = get(this, 'state'),
  12514. match = get(this, 'match'),
  12515. manager = get(this, 'manager');
  12516. return state.deserialize(manager, match.hash);
  12517. }
  12518. }
  12519. }).property(),
  12520. hasPromise: Ember.computed(function() {
  12521. return Ember.canInvoke(get(this, 'object'), 'then');
  12522. }).property('object'),
  12523. promise: Ember.computed(function() {
  12524. var object = get(this, 'object');
  12525. if (Ember.canInvoke(object, 'then')) {
  12526. return object;
  12527. } else {
  12528. return {
  12529. then: function(success) { success(object); }
  12530. };
  12531. }
  12532. }).property('object'),
  12533. transition: function() {
  12534. var manager = get(this, 'manager'),
  12535. path = get(this, 'state.path'),
  12536. object = get(this, 'object');
  12537. manager.transitionTo(path, object);
  12538. }
  12539. });
  12540. })();
  12541. (function() {
  12542. var get = Ember.get;
  12543. // The Ember Routable mixin assumes the existance of a simple
  12544. // routing shim that supports the following three behaviors:
  12545. //
  12546. // * .getURL() - this is called when the page loads
  12547. // * .setURL(newURL) - this is called from within the state
  12548. // manager when the state changes to a routable state
  12549. // * .onURLChange(callback) - this happens when the user presses
  12550. // the back or forward button
  12551. var paramForClass = function(classObject) {
  12552. var className = classObject.toString(),
  12553. parts = className.split("."),
  12554. last = parts[parts.length - 1];
  12555. return Ember.String.underscore(last) + "_id";
  12556. };
  12557. var merge = function(original, hash) {
  12558. for (var prop in hash) {
  12559. if (!hash.hasOwnProperty(prop)) { continue; }
  12560. if (original.hasOwnProperty(prop)) { continue; }
  12561. original[prop] = hash[prop];
  12562. }
  12563. };
  12564. /**
  12565. @class
  12566. @extends Ember.Mixin
  12567. */
  12568. Ember.Routable = Ember.Mixin.create({
  12569. init: function() {
  12570. var redirection;
  12571. this.on('connectOutlets', this, this.stashContext);
  12572. if (redirection = get(this, 'redirectsTo')) {
  12573. Ember.assert("You cannot use `redirectsTo` if you already have a `connectOutlets` method", this.connectOutlets === Ember.K);
  12574. this.connectOutlets = function(router) {
  12575. router.transitionTo(redirection);
  12576. };
  12577. }
  12578. // normalize empty route to '/'
  12579. var route = get(this, 'route');
  12580. if (route === '') {
  12581. route = '/';
  12582. }
  12583. this._super();
  12584. Ember.assert("You cannot use `redirectsTo` on a state that has child states", !redirection || (!!redirection && !!get(this, 'isLeaf')));
  12585. },
  12586. /**
  12587. @private
  12588. Whenever a routable state is entered, the context it was entered with
  12589. is stashed so that we can regenerate the state's `absoluteURL` on
  12590. demand.
  12591. */
  12592. stashContext: function(manager, context) {
  12593. var serialized = this.serialize(manager, context);
  12594. Ember.assert('serialize must return a hash', !serialized || typeof serialized === 'object');
  12595. manager.setStateMeta(this, 'context', context);
  12596. manager.setStateMeta(this, 'serialized', serialized);
  12597. if (get(this, 'isRoutable') && !get(manager, 'isRouting')) {
  12598. this.updateRoute(manager, get(manager, 'location'));
  12599. }
  12600. },
  12601. /**
  12602. @private
  12603. Whenever a routable state is entered, the router's location object
  12604. is notified to set the URL to the current absolute path.
  12605. In general, this will update the browser's URL.
  12606. */
  12607. updateRoute: function(manager, location) {
  12608. if (get(this, 'isLeafRoute')) {
  12609. var path = this.absoluteRoute(manager);
  12610. location.setURL(path);
  12611. }
  12612. },
  12613. /**
  12614. @private
  12615. Get the absolute route for the current state and a given
  12616. hash.
  12617. This method is private, as it expects a serialized hash,
  12618. not the original context object.
  12619. */
  12620. absoluteRoute: function(manager, hash) {
  12621. var parentState = get(this, 'parentState');
  12622. var path = '', generated;
  12623. // If the parent state is routable, use its current path
  12624. // as this route's prefix.
  12625. if (get(parentState, 'isRoutable')) {
  12626. path = parentState.absoluteRoute(manager, hash);
  12627. }
  12628. var matcher = get(this, 'routeMatcher'),
  12629. serialized = manager.getStateMeta(this, 'serialized');
  12630. // merge the existing serialized object in with the passed
  12631. // in hash.
  12632. hash = hash || {};
  12633. merge(hash, serialized);
  12634. generated = matcher && matcher.generate(hash);
  12635. if (generated) {
  12636. path = path + '/' + generated;
  12637. }
  12638. return path;
  12639. },
  12640. /**
  12641. @private
  12642. At the moment, a state is routable if it has a string `route`
  12643. property. This heuristic may change.
  12644. */
  12645. isRoutable: Ember.computed(function() {
  12646. return typeof get(this, 'route') === 'string';
  12647. }).cacheable(),
  12648. /**
  12649. @private
  12650. Determine if this is the last routeable state
  12651. */
  12652. isLeafRoute: Ember.computed(function() {
  12653. if (get(this, 'isLeaf')) { return true; }
  12654. return !get(this, 'childStates').findProperty('isRoutable');
  12655. }).cacheable(),
  12656. /**
  12657. @private
  12658. A _RouteMatcher object generated from the current route's `route`
  12659. string property.
  12660. */
  12661. routeMatcher: Ember.computed(function() {
  12662. var route = get(this, 'route');
  12663. if (route) {
  12664. return Ember._RouteMatcher.create({ route: route });
  12665. }
  12666. }).cacheable(),
  12667. /**
  12668. @private
  12669. Check whether the route has dynamic segments and therefore takes
  12670. a context.
  12671. */
  12672. hasContext: Ember.computed(function() {
  12673. var routeMatcher = get(this, 'routeMatcher');
  12674. if (routeMatcher) {
  12675. return routeMatcher.identifiers.length > 0;
  12676. }
  12677. }).cacheable(),
  12678. /**
  12679. @private
  12680. The model class associated with the current state. This property
  12681. uses the `modelType` property, in order to allow it to be
  12682. specified as a String.
  12683. */
  12684. modelClass: Ember.computed(function() {
  12685. var modelType = get(this, 'modelType');
  12686. if (typeof modelType === 'string') {
  12687. return Ember.get(window, modelType);
  12688. } else {
  12689. return modelType;
  12690. }
  12691. }).cacheable(),
  12692. /**
  12693. @private
  12694. Get the model class for the state. The heuristic is:
  12695. * The state must have a single dynamic segment
  12696. * The dynamic segment must end in `_id`
  12697. * A dynamic segment like `blog_post_id` is converted into `BlogPost`
  12698. * The name is then looked up on the passed in namespace
  12699. The process of initializing an application with a router will
  12700. pass the application's namespace into the router, which will be
  12701. used here.
  12702. */
  12703. modelClassFor: function(namespace) {
  12704. var modelClass, routeMatcher, identifiers, match, className;
  12705. // if an explicit modelType was specified, use that
  12706. if (modelClass = get(this, 'modelClass')) { return modelClass; }
  12707. // if the router has no lookup namespace, we won't be able to guess
  12708. // the modelType
  12709. if (!namespace) { return; }
  12710. // make sure this state is actually a routable state
  12711. routeMatcher = get(this, 'routeMatcher');
  12712. if (!routeMatcher) { return; }
  12713. // only guess modelType for states with a single dynamic segment
  12714. // (no more, no fewer)
  12715. identifiers = routeMatcher.identifiers;
  12716. if (identifiers.length !== 2) { return; }
  12717. // extract the `_id` from the end of the dynamic segment; if the
  12718. // dynamic segment does not end in `_id`, we can't guess the
  12719. // modelType
  12720. match = identifiers[1].match(/^(.*)_id$/);
  12721. if (!match) { return; }
  12722. // convert the underscored type into a class form and look it up
  12723. // on the router's namespace
  12724. className = Ember.String.classify(match[1]);
  12725. return get(namespace, className);
  12726. },
  12727. /**
  12728. The default method that takes a `params` object and converts
  12729. it into an object.
  12730. By default, a params hash that looks like `{ post_id: 1 }`
  12731. will be looked up as `namespace.Post.find(1)`. This is
  12732. designed to work seamlessly with Ember Data, but will work
  12733. fine with any class that has a `find` method.
  12734. */
  12735. deserialize: function(manager, params) {
  12736. var modelClass, routeMatcher, param;
  12737. if (modelClass = this.modelClassFor(get(manager, 'namespace'))) {
  12738. Ember.assert("Expected "+modelClass.toString()+" to implement `find` for use in '"+this.get('path')+"' `deserialize`. Please implement the `find` method or overwrite `deserialize`.", modelClass.find);
  12739. return modelClass.find(params[paramForClass(modelClass)]);
  12740. }
  12741. return params;
  12742. },
  12743. /**
  12744. The default method that takes an object and converts it into
  12745. a params hash.
  12746. By default, if there is a single dynamic segment named
  12747. `blog_post_id` and the object is a `BlogPost` with an
  12748. `id` of `12`, the serialize method will produce:
  12749. { blog_post_id: 12 }
  12750. */
  12751. serialize: function(manager, context) {
  12752. var modelClass, routeMatcher, namespace, param, id;
  12753. if (Ember.empty(context)) { return ''; }
  12754. if (modelClass = this.modelClassFor(get(manager, 'namespace'))) {
  12755. param = paramForClass(modelClass);
  12756. id = get(context, 'id');
  12757. context = {};
  12758. context[param] = id;
  12759. }
  12760. return context;
  12761. },
  12762. /**
  12763. @private
  12764. */
  12765. resolvePath: function(manager, path) {
  12766. if (get(this, 'isLeafRoute')) { return Ember.A(); }
  12767. var childStates = get(this, 'childStates'), match;
  12768. childStates = Ember.A(childStates.filterProperty('isRoutable'));
  12769. childStates = childStates.sort(function(a, b) {
  12770. var aDynamicSegments = get(a, 'routeMatcher.identifiers.length'),
  12771. bDynamicSegments = get(b, 'routeMatcher.identifiers.length'),
  12772. aRoute = get(a, 'route'),
  12773. bRoute = get(b, 'route');
  12774. if (aRoute.indexOf(bRoute) === 0) {
  12775. return -1;
  12776. } else if (bRoute.indexOf(aRoute) === 0) {
  12777. return 1;
  12778. }
  12779. if (aDynamicSegments !== bDynamicSegments) {
  12780. return aDynamicSegments - bDynamicSegments;
  12781. }
  12782. return get(b, 'route.length') - get(a, 'route.length');
  12783. });
  12784. var state = childStates.find(function(state) {
  12785. var matcher = get(state, 'routeMatcher');
  12786. if (match = matcher.match(path)) { return true; }
  12787. });
  12788. Ember.assert("Could not find state for path " + path, !!state);
  12789. var resolvedState = Ember._ResolvedState.create({
  12790. manager: manager,
  12791. state: state,
  12792. match: match
  12793. });
  12794. var states = state.resolvePath(manager, match.remaining);
  12795. return Ember.A([resolvedState]).pushObjects(states);
  12796. },
  12797. /**
  12798. @private
  12799. Once `unroute` has finished unwinding, `routePath` will be called
  12800. with the remainder of the route.
  12801. For example, if you were in the /posts/1/comments state, and you
  12802. moved into the /posts/2/comments state, `routePath` will be called
  12803. on the state whose path is `/posts` with the path `/2/comments`.
  12804. */
  12805. routePath: function(manager, path) {
  12806. if (get(this, 'isLeafRoute')) { return; }
  12807. var resolvedStates = this.resolvePath(manager, path),
  12808. hasPromises = resolvedStates.some(function(s) { return get(s, 'hasPromise'); });
  12809. function runTransition() {
  12810. resolvedStates.forEach(function(rs) { rs.transition(); });
  12811. }
  12812. if (hasPromises) {
  12813. manager.transitionTo('loading');
  12814. Ember.assert('Loading state should be the child of a route', Ember.Routable.detect(get(manager, 'currentState.parentState')));
  12815. Ember.assert('Loading state should not be a route', !Ember.Routable.detect(get(manager, 'currentState')));
  12816. manager.handleStatePromises(resolvedStates, runTransition);
  12817. } else {
  12818. runTransition();
  12819. }
  12820. },
  12821. /**
  12822. @private
  12823. When you move to a new route by pressing the back
  12824. or forward button, this method is called first.
  12825. Its job is to move the state manager into a parent
  12826. state of the state it will eventually move into.
  12827. */
  12828. unroutePath: function(router, path) {
  12829. var parentState = get(this, 'parentState');
  12830. // If we're at the root state, we're done
  12831. if (parentState === router) {
  12832. return;
  12833. }
  12834. path = path.replace(/^(?=[^\/])/, "/");
  12835. var absolutePath = this.absoluteRoute(router);
  12836. var route = get(this, 'route');
  12837. // If the current path is empty, move up one state,
  12838. // because the index ('/') state must be a leaf node.
  12839. if (route !== '/') {
  12840. // If the current path is a prefix of the path we're trying
  12841. // to go to, we're done.
  12842. var index = path.indexOf(absolutePath),
  12843. next = path.charAt(absolutePath.length);
  12844. if (index === 0 && (next === "/" || next === "")) {
  12845. return;
  12846. }
  12847. }
  12848. // Transition to the parent and call unroute again.
  12849. router.enterState({
  12850. exitStates: [this],
  12851. enterStates: [],
  12852. finalState: parentState
  12853. });
  12854. router.send('unroutePath', path);
  12855. },
  12856. /**
  12857. The `connectOutlets` event will be triggered once a
  12858. state has been entered. It will be called with the
  12859. route's context.
  12860. */
  12861. connectOutlets: Ember.K,
  12862. /**
  12863. The `navigateAway` event will be triggered when the
  12864. URL changes due to the back/forward button
  12865. */
  12866. navigateAway: Ember.K
  12867. });
  12868. })();
  12869. (function() {
  12870. /**
  12871. @class
  12872. @extends Ember.Routable
  12873. */
  12874. Ember.Route = Ember.State.extend(Ember.Routable);
  12875. })();
  12876. (function() {
  12877. var escapeForRegex = function(text) {
  12878. return text.replace(/[\-\[\]{}()*+?.,\\\^\$|#\s]/g, "\\$&");
  12879. };
  12880. Ember._RouteMatcher = Ember.Object.extend({
  12881. state: null,
  12882. init: function() {
  12883. var route = this.route,
  12884. identifiers = [],
  12885. count = 1,
  12886. escaped;
  12887. // Strip off leading slash if present
  12888. if (route.charAt(0) === '/') {
  12889. route = this.route = route.substr(1);
  12890. }
  12891. escaped = escapeForRegex(route);
  12892. var regex = escaped.replace(/:([a-z_]+)(?=$|\/)/gi, function(match, id) {
  12893. identifiers[count++] = id;
  12894. return "([^/]+)";
  12895. });
  12896. this.identifiers = identifiers;
  12897. this.regex = new RegExp("^/?" + regex);
  12898. },
  12899. match: function(path) {
  12900. var match = path.match(this.regex);
  12901. if (match) {
  12902. var identifiers = this.identifiers,
  12903. hash = {};
  12904. for (var i=1, l=identifiers.length; i<l; i++) {
  12905. hash[identifiers[i]] = match[i];
  12906. }
  12907. return {
  12908. remaining: path.substr(match[0].length),
  12909. hash: identifiers.length > 0 ? hash : null
  12910. };
  12911. }
  12912. },
  12913. generate: function(hash) {
  12914. var identifiers = this.identifiers, route = this.route, id;
  12915. for (var i=1, l=identifiers.length; i<l; i++) {
  12916. id = identifiers[i];
  12917. route = route.replace(new RegExp(":" + id), hash[id]);
  12918. }
  12919. return route;
  12920. }
  12921. });
  12922. })();
  12923. (function() {
  12924. var get = Ember.get, set = Ember.set;
  12925. var merge = function(original, hash) {
  12926. for (var prop in hash) {
  12927. if (!hash.hasOwnProperty(prop)) { continue; }
  12928. if (original.hasOwnProperty(prop)) { continue; }
  12929. original[prop] = hash[prop];
  12930. }
  12931. };
  12932. /**
  12933. @class
  12934. `Ember.Router` is the subclass of `Ember.StateManager` responsible for providing URL-based
  12935. application state detection. The `Ember.Router` instance of an application detects the browser URL
  12936. at application load time and attempts to match it to a specific application state. Additionally
  12937. the router will update the URL to reflect an application's state changes over time.
  12938. ## Adding a Router Instance to Your Application
  12939. An instance of Ember.Router can be associated with an instance of Ember.Application in one of two ways:
  12940. You can provide a subclass of Ember.Router as the `Router` property of your application. An instance
  12941. of this Router class will be instantiated and route detection will be enabled when the application's
  12942. `initialize` method is called. The Router instance will be available as the `router` property
  12943. of the application:
  12944. App = Ember.Application.create({
  12945. Router: Ember.Router.extend({ ... })
  12946. });
  12947. App.initialize();
  12948. App.get('router') // an instance of App.Router
  12949. If you want to define a Router instance elsewhere, you can pass the instance to the application's
  12950. `initialize` method:
  12951. App = Ember.Application.create();
  12952. aRouter = Ember.Router.create({ ... });
  12953. App.initialize(aRouter);
  12954. App.get('router') // aRouter
  12955. ## Adding Routes to a Router
  12956. The `initialState` property of Ember.Router instances is named `root`. The state stored in this
  12957. property must be a subclass of Ember.Route. The `root` route acts as the container for the
  12958. set of routable states but is not routable itself. It should have states that are also subclasses
  12959. of Ember.Route which each have a `route` property describing the URL pattern you would like to detect.
  12960. App = Ember.Application.create({
  12961. Router: Ember.Router.extend({
  12962. root: Ember.Route.extend({
  12963. index: Ember.Route.extend({
  12964. route: '/'
  12965. }),
  12966. ... additional Ember.Routes ...
  12967. })
  12968. })
  12969. });
  12970. App.initialize();
  12971. When an application loads, Ember will parse the URL and attempt to find an Ember.Route within
  12972. the application's states that matches. (The example URL-matching below will use the default
  12973. 'hash syntax' provided by `Ember.HashLocation`.)
  12974. In the following route structure:
  12975. App = Ember.Application.create({
  12976. Router: Ember.Router.extend({
  12977. root: Ember.Route.extend({
  12978. aRoute: Ember.Route.extend({
  12979. route: '/'
  12980. }),
  12981. bRoute: Ember.Route.extend({
  12982. route: '/alphabeta'
  12983. })
  12984. })
  12985. })
  12986. });
  12987. App.initialize();
  12988. Loading the page at the URL '#/' will detect the route property of 'root.aRoute' ('/') and
  12989. transition the router first to the state named 'root' and then to the substate 'aRoute'.
  12990. Respectively, loading the page at the URL '#/alphabeta' would detect the route property of
  12991. 'root.bRoute' ('/alphabeta') and transition the router first to the state named 'root' and
  12992. then to the substate 'bRoute'.
  12993. ## Adding Nested Routes to a Router
  12994. Routes can contain nested subroutes each with their own `route` property describing the nested
  12995. portion of the URL they would like to detect and handle. Router, like all instances of StateManager,
  12996. cannot call `transitonTo` with an intermediary state. To avoid transitioning the Router into an
  12997. intermediary state when detecting URLs, a Route with nested routes must define both a base `route`
  12998. property for itself and a child Route with a `route` property of `'/'` which will be transitioned
  12999. to when the base route is detected in the URL:
  13000. Given the following application code:
  13001. App = Ember.Application.create({
  13002. Router: Ember.Router.extend({
  13003. root: Ember.Route.extend({
  13004. aRoute: Ember.Route.extend({
  13005. route: '/theBaseRouteForThisSet',
  13006. indexSubRoute: Ember.Route.extend({
  13007. route: '/',
  13008. }),
  13009. subRouteOne: Ember.Route.extend({
  13010. route: '/subroute1
  13011. }),
  13012. subRouteTwo: Ember.Route.extend({
  13013. route: '/subRoute2'
  13014. })
  13015. })
  13016. })
  13017. })
  13018. });
  13019. App.initialize();
  13020. When the application is loaded at '/theBaseRouteForThisSet' the Router will transition to the route
  13021. at path 'root.aRoute' and then transition to state 'indexSubRoute'.
  13022. When the application is loaded at '/theBaseRouteForThisSet/subRoute1' the Router will transition to
  13023. the route at path 'root.aRoute' and then transition to state 'subRouteOne'.
  13024. ## Route Transition Events
  13025. Transitioning between Ember.Route instances (including the transition into the detected
  13026. route when loading the application) triggers the same transition events as state transitions for
  13027. base `Ember.State`s. However, the default `setup` transition event is named `connectOutlets` on
  13028. Ember.Router instances (see 'Changing View Hierarchy in Response To State Change').
  13029. The following route structure when loaded with the URL "#/"
  13030. App = Ember.Application.create({
  13031. Router: Ember.Router.extend({
  13032. root: Ember.Route.extend({
  13033. aRoute: Ember.Route.extend({
  13034. route: '/',
  13035. enter: function(router) {
  13036. console.log("entering root.aRoute from", router.get('currentState.name'));
  13037. },
  13038. connectOutlets: function(router) {
  13039. console.log("entered root.aRoute, fully transitioned to", router.get('currentState.path'));
  13040. }
  13041. })
  13042. })
  13043. })
  13044. });
  13045. App.initialize();
  13046. Will result in console output of:
  13047. 'entering root.aRoute from root'
  13048. 'entered root.aRoute, fully transitioned to root.aRoute '
  13049. Ember.Route has two additional callbacks for handling URL serialization and deserialization. See
  13050. 'Serializing/Deserializing URLs'
  13051. ## Routes With Dynamic Segments
  13052. An Ember.Route's `route` property can reference dynamic sections of the URL by prefacing a URL segment
  13053. with the ':' character. The values of these dynamic segments will be passed as a hash to the
  13054. `deserialize` method of the matching Route (see 'Serializing/Deserializing URLs').
  13055. ## Serializing/Deserializing URLs
  13056. Ember.Route has two callbacks for associating a particular object context with a URL: `serialize`
  13057. for converting an object into a parameters hash to fill dynamic segments of a URL and `deserialize`
  13058. for converting a hash of dynamic segments from the URL into the appropriate object.
  13059. ### Deserializing A URL's Dynamic Segments
  13060. When an application is first loaded or the URL is changed manually (e.g. through the browser's
  13061. back button) the `deserialize` method of the URL's matching Ember.Route will be called with
  13062. the application's router as its first argument and a hash of the URLs dynamic segments and values
  13063. as its second argument.
  13064. The following route structure when loaded with the URL "#/fixed/thefirstvalue/anotherFixed/thesecondvalue":
  13065. App = Ember.Application.create({
  13066. Router: Ember.Router.extend({
  13067. root: Ember.Route.extend({
  13068. aRoute: Ember.Route.extend({
  13069. route: '/fixed/:dynamicSectionA/anotherFixed/:dynamicSectionB',
  13070. deserialize: function(router, params) {}
  13071. })
  13072. })
  13073. })
  13074. });
  13075. App.initialize();
  13076. Will call the 'deserialize' method of the Route instance at the path 'root.aRoute' with the
  13077. following hash as its second argument:
  13078. {
  13079. dynamicSectionA: 'thefirstvalue',
  13080. dynamicSectionB: 'thesecondvalue'
  13081. }
  13082. Within `deserialize` you should use this information to retrieve or create an appropriate context
  13083. object for the given URL (e.g. by loading from a remote API or accessing the browser's
  13084. `localStorage`). This object must be the `return` value of `deserialize` and will be
  13085. passed to the Route's `connectOutlets` and `serialize` methods.
  13086. When an application's state is changed from within the application itself, the context provided for
  13087. the transition will be passed and `deserialize` is not called (see 'Transitions Between States').
  13088. ### Serializing An Object For URLs with Dynamic Segments
  13089. When transitioning into a Route whose `route` property contains dynamic segments the Route's
  13090. `serialize` method is called with the Route's router as the first argument and the Route's
  13091. context as the second argument. The return value of `serialize` will be use to populate the
  13092. dynamic segments and should be a object with keys that match the names of the dynamic sections.
  13093. Given the following route structure:
  13094. App = Ember.Application.create({
  13095. Router: Ember.Router.extend({
  13096. root: Ember.Route.extend({
  13097. aRoute: Ember.Route.extend({
  13098. route: '/'
  13099. }),
  13100. bRoute: Ember.Route.extend({
  13101. route: '/staticSection/:someDynamicSegment',
  13102. serialize: function(router, context) {
  13103. return {
  13104. someDynamicSegment: context.get('name')
  13105. }
  13106. }
  13107. })
  13108. })
  13109. })
  13110. });
  13111. App.initialize();
  13112. Transitioning to "root.bRoute" with a context of `Object.create({name: 'Yehuda'})` will call
  13113. the Route's `serialize` method with the context as its second argument and update the URL to
  13114. '#/staticSection/Yehuda'.
  13115. ## Transitions Between States
  13116. Once a routed application has initialized its state based on the entry URL, subsequent transitions to other
  13117. states will update the URL if the entered Route has a `route` property. Given the following route structure
  13118. loaded at the URL '#/':
  13119. App = Ember.Application.create({
  13120. Router: Ember.Router.extend({
  13121. root: Ember.Route.extend({
  13122. aRoute: Ember.Route.extend({
  13123. route: '/',
  13124. moveElsewhere: Ember.Route.transitionTo('bRoute')
  13125. }),
  13126. bRoute: Ember.Route.extend({
  13127. route: '/someOtherLocation'
  13128. })
  13129. })
  13130. })
  13131. });
  13132. App.initialize();
  13133. And application code:
  13134. App.get('router').send('moveElsewhere');
  13135. Will transition the application's state to 'root.bRoute' and trigger an update of the URL to
  13136. '#/someOtherLocation'.
  13137. For URL patterns with dynamic segments a context can be supplied as the second argument to `send`.
  13138. The router will match dynamic segments names to keys on this object and fill in the URL with the
  13139. supplied values. Given the following state structure loaded at the URL '#/':
  13140. App = Ember.Application.create({
  13141. Router: Ember.Router.extend({
  13142. root: Ember.Route.extend({
  13143. aRoute: Ember.Route.extend({
  13144. route: '/',
  13145. moveElsewhere: Ember.Route.transitionTo('bRoute')
  13146. }),
  13147. bRoute: Ember.Route.extend({
  13148. route: '/a/route/:dynamicSection/:anotherDynamicSection',
  13149. connectOutlets: function(router, context) {},
  13150. })
  13151. })
  13152. })
  13153. });
  13154. App.initialize();
  13155. And application code:
  13156. App.get('router').send('moveElsewhere', {
  13157. dynamicSection: '42',
  13158. anotherDynamicSection: 'Life'
  13159. });
  13160. Will transition the application's state to 'root.bRoute' and trigger an update of the URL to
  13161. '#/a/route/42/Life'.
  13162. The context argument will also be passed as the second argument to the `serialize` method call.
  13163. ## Injection of Controller Singletons
  13164. During application initialization Ember will detect properties of the application ending in 'Controller',
  13165. create singleton instances of each class, and assign them as a properties on the router. The property name
  13166. will be the UpperCamel name converted to lowerCamel format. These controller classes should be subclasses
  13167. of Ember.ObjectController, Ember.ArrayController, Ember.Controller, or a custom Ember.Object that includes the
  13168. Ember.ControllerMixin mixin.
  13169. App = Ember.Application.create({
  13170. FooController: Ember.Object.create(Ember.ControllerMixin),
  13171. Router: Ember.Router.extend({ ... })
  13172. });
  13173. App.get('router.fooController'); // instance of App.FooController
  13174. The controller singletons will have their `namespace` property set to the application and their `target`
  13175. property set to the application's router singleton for easy integration with Ember's user event system.
  13176. See 'Changing View Hierarchy in Response To State Change' and 'Responding to User-initiated Events'
  13177. ## Responding to User-initiated Events
  13178. Controller instances injected into the router at application initialization have their `target` property
  13179. set to the application's router instance. These controllers will also be the default `context` for their
  13180. associated views. Uses of the `{{action}}` helper will automatically target the application's router.
  13181. Given the following application entered at the URL '#/':
  13182. App = Ember.Application.create({
  13183. Router: Ember.Router.extend({
  13184. root: Ember.Route.extend({
  13185. aRoute: Ember.Route.extend({
  13186. route: '/',
  13187. anActionOnTheRouter: function(router, context) {
  13188. router.transitionTo('anotherState', context);
  13189. }
  13190. })
  13191. anotherState: Ember.Route.extend({
  13192. route: '/differentUrl',
  13193. connectOutlets: function(router, context) {
  13194. }
  13195. })
  13196. })
  13197. })
  13198. });
  13199. App.initialize();
  13200. The following template:
  13201. <script type="text/x-handlebars" data-template-name="aView">
  13202. <h1><a {{action anActionOnTheRouter}}>{{title}}</a></h1>
  13203. </script>
  13204. Will delegate `click` events on the rendered `h1` to the application's router instance. In this case the
  13205. `anActionOnTheRouter` method of the state at 'root.aRoute' will be called with the view's controller
  13206. as the context argument. This context will be passed to the `connectOutlets` as its second argument.
  13207. Different `context` can be supplied from within the `{{action}}` helper, allowing specific context passing
  13208. between application states:
  13209. <script type="text/x-handlebars" data-template-name="photos">
  13210. {{#each photo in controller}}
  13211. <h1><a {{action showPhoto photo}}>{{title}}</a></h1>
  13212. {{/each}}
  13213. </script>
  13214. See Handlebars.helpers.action for additional usage examples.
  13215. ## Changing View Hierarchy in Response To State Change
  13216. Changes in application state that change the URL should be accompanied by associated changes in view
  13217. hierarchy. This can be accomplished by calling 'connectOutlet' on the injected controller singletons from
  13218. within the 'connectOutlets' event of an Ember.Route:
  13219. App = Ember.Application.create({
  13220. OneController: Ember.ObjectController.extend(),
  13221. OneView: Ember.View.extend(),
  13222. AnotherController: Ember.ObjectController.extend(),
  13223. AnotherView: Ember.View.extend(),
  13224. Router: Ember.Router.extend({
  13225. root: Ember.Route.extend({
  13226. aRoute: Ember.Route.extend({
  13227. route: '/',
  13228. connectOutlets: function(router, context) {
  13229. router.get('oneController').connectOutlet('another');
  13230. },
  13231. })
  13232. })
  13233. })
  13234. });
  13235. App.initialize();
  13236. This will detect the '{{outlet}}' portion of `oneController`'s view (an instance of `App.OneView`) and
  13237. fill it with a rendered instance of `App.AnotherView` whose `context` will be the single instance of
  13238. `App.AnotherController` stored on the router in the `anotherController` property.
  13239. For more information about Outlets, see `Ember.Handlebars.helpers.outlet`. For additional information on
  13240. the `connectOutlet` method, see `Ember.Controller.connectOutlet`. For more information on
  13241. controller injections, see `Ember.Application#initialize()`. For additional information about view context,
  13242. see `Ember.View`.
  13243. @extends Ember.StateManager
  13244. */
  13245. Ember.Router = Ember.StateManager.extend(
  13246. /** @scope Ember.Router.prototype */ {
  13247. /**
  13248. @property {String}
  13249. @default 'root'
  13250. */
  13251. initialState: 'root',
  13252. /**
  13253. The `Ember.Location` implementation to be used to manage the application
  13254. URL state. The following values are supported:
  13255. * 'hash': Uses URL fragment identifiers (like #/blog/1) for routing.
  13256. * 'none': Does not read or set the browser URL, but still allows for
  13257. routing to happen. Useful for testing.
  13258. @type String
  13259. @default 'hash'
  13260. */
  13261. location: 'hash',
  13262. /**
  13263. This is only used when a history location is used so that applications that
  13264. don't live at the root of the domain can append paths to their root.
  13265. @type String
  13266. @default '/'
  13267. */
  13268. rootURL: '/',
  13269. /**
  13270. On router, transitionEvent should be called connectOutlets
  13271. @property {String}
  13272. @default 'connectOutlets'
  13273. */
  13274. transitionEvent: 'connectOutlets',
  13275. transitionTo: function() {
  13276. this.abortRoutingPromises();
  13277. this._super.apply(this, arguments);
  13278. },
  13279. route: function(path) {
  13280. this.abortRoutingPromises();
  13281. set(this, 'isRouting', true);
  13282. var routableState;
  13283. try {
  13284. path = path.replace(/^(?=[^\/])/, "/");
  13285. this.send('navigateAway');
  13286. this.send('unroutePath', path);
  13287. routableState = get(this, 'currentState');
  13288. while (routableState && !routableState.get('isRoutable')) {
  13289. routableState = get(routableState, 'parentState');
  13290. }
  13291. var currentURL = routableState ? routableState.absoluteRoute(this) : '';
  13292. var rest = path.substr(currentURL.length);
  13293. this.send('routePath', rest);
  13294. } finally {
  13295. set(this, 'isRouting', false);
  13296. }
  13297. routableState = get(this, 'currentState');
  13298. while (routableState && !routableState.get('isRoutable')) {
  13299. routableState = get(routableState, 'parentState');
  13300. }
  13301. if (routableState) {
  13302. routableState.updateRoute(this, get(this, 'location'));
  13303. }
  13304. },
  13305. urlFor: function(path, hash) {
  13306. var currentState = get(this, 'currentState') || this,
  13307. state = this.findStateByPath(currentState, path);
  13308. Ember.assert(Ember.String.fmt("Could not find route with path '%@'", [path]), !!state);
  13309. Ember.assert("To get a URL for a state, it must have a `route` property.", !!get(state, 'routeMatcher'));
  13310. var location = get(this, 'location'),
  13311. absoluteRoute = state.absoluteRoute(this, hash);
  13312. return location.formatURL(absoluteRoute);
  13313. },
  13314. urlForEvent: function(eventName) {
  13315. var contexts = Array.prototype.slice.call(arguments, 1);
  13316. var currentState = get(this, 'currentState');
  13317. var targetStateName = currentState.lookupEventTransition(eventName);
  13318. Ember.assert(Ember.String.fmt("You must specify a target state for event '%@' in order to link to it in the current state '%@'.", [eventName, get(currentState, 'path')]), !!targetStateName);
  13319. var targetState = this.findStateByPath(currentState, targetStateName);
  13320. Ember.assert("Your target state name " + targetStateName + " for event " + eventName + " did not resolve to a state", !!targetState);
  13321. var hash = this.serializeRecursively(targetState, contexts, {});
  13322. return this.urlFor(targetStateName, hash);
  13323. },
  13324. /** @private */
  13325. serializeRecursively: function(state, contexts, hash) {
  13326. var parentState,
  13327. context = get(state, 'hasContext') ? contexts.pop() : null;
  13328. merge(hash, state.serialize(this, context));
  13329. parentState = state.get("parentState");
  13330. if (parentState && parentState instanceof Ember.Route) {
  13331. return this.serializeRecursively(parentState, contexts, hash);
  13332. } else {
  13333. return hash;
  13334. }
  13335. },
  13336. abortRoutingPromises: function() {
  13337. if (this._routingPromises) {
  13338. this._routingPromises.abort();
  13339. this._routingPromises = null;
  13340. }
  13341. },
  13342. /**
  13343. @private
  13344. */
  13345. handleStatePromises: function(states, complete) {
  13346. this.abortRoutingPromises();
  13347. this.set('isLocked', true);
  13348. var manager = this;
  13349. this._routingPromises = Ember._PromiseChain.create({
  13350. promises: states.slice(),
  13351. successCallback: function() {
  13352. manager.set('isLocked', false);
  13353. complete();
  13354. },
  13355. failureCallback: function() {
  13356. throw "Unable to load object";
  13357. },
  13358. promiseSuccessCallback: function(item, args) {
  13359. set(item, 'object', args[0]);
  13360. },
  13361. abortCallback: function() {
  13362. manager.set('isLocked', false);
  13363. }
  13364. }).start();
  13365. },
  13366. /** @private */
  13367. init: function() {
  13368. this._super();
  13369. var location = get(this, 'location'),
  13370. rootURL = get(this, 'rootURL');
  13371. if ('string' === typeof location) {
  13372. set(this, 'location', Ember.Location.create({
  13373. implementation: location,
  13374. rootURL: rootURL
  13375. }));
  13376. }
  13377. },
  13378. /** @private */
  13379. willDestroy: function() {
  13380. get(this, 'location').destroy();
  13381. }
  13382. });
  13383. })();
  13384. (function() {
  13385. // ==========================================================================
  13386. // Project: Ember Routing
  13387. // Copyright: ©2012 Tilde Inc. and contributors.
  13388. // License: Licensed under MIT license (see license.js)
  13389. // ==========================================================================
  13390. })();
  13391. (function() {
  13392. var get = Ember.get;
  13393. Ember.StateManager.reopen(
  13394. /** @scope Ember.StateManager.prototype */ {
  13395. /**
  13396. If the current state is a view state or the descendent of a view state,
  13397. this property will be the view associated with it. If there is no
  13398. view state active in this state manager, this value will be null.
  13399. @type Ember.View
  13400. */
  13401. currentView: Ember.computed(function() {
  13402. var currentState = get(this, 'currentState'),
  13403. view;
  13404. while (currentState) {
  13405. // TODO: Remove this when view state is removed
  13406. if (get(currentState, 'isViewState')) {
  13407. view = get(currentState, 'view');
  13408. if (view) { return view; }
  13409. }
  13410. currentState = get(currentState, 'parentState');
  13411. }
  13412. return null;
  13413. }).property('currentState').cacheable()
  13414. });
  13415. })();
  13416. (function() {
  13417. var get = Ember.get, set = Ember.set;
  13418. /**
  13419. @class
  13420. @deprecated
  13421. Ember.ViewState extends Ember.State to control the presence of a childView within a
  13422. container based on the current state of the ViewState's StateManager.
  13423. ## Interactions with Ember's View System.
  13424. When combined with instances of `Ember.StateManager`, ViewState is designed to
  13425. interact with Ember's view system to control which views are added to
  13426. and removed from the DOM based on the manager's current state.
  13427. By default, a StateManager will manage views inside the 'body' element. This can be
  13428. customized by setting the `rootElement` property to a CSS selector of an existing
  13429. HTML element you would prefer to receive view rendering.
  13430. viewStates = Ember.StateManager.create({
  13431. rootElement: '#some-other-element'
  13432. })
  13433. You can also specify a particular instance of `Ember.ContainerView` you would like to receive
  13434. view rendering by setting the `rootView` property. You will be responsible for placing
  13435. this element into the DOM yourself.
  13436. aLayoutView = Ember.ContainerView.create()
  13437. // make sure this view instance is added to the browser
  13438. aLayoutView.appendTo('body')
  13439. App.viewStates = Ember.StateManager.create({
  13440. rootView: aLayoutView
  13441. })
  13442. Once you have an instance of StateManager controlling a view, you can provide states
  13443. that are instances of `Ember.ViewState`. When the StateManager enters a state
  13444. that is an instance of `Ember.ViewState` that `ViewState`'s `view` property will be
  13445. instantiated and inserted into the StateManager's `rootView` or `rootElement`.
  13446. When a state is exited, the `ViewState`'s view will be removed from the StateManager's
  13447. view.
  13448. ContactListView = Ember.View.extend({
  13449. classNames: ['my-contacts-css-class'],
  13450. template: Ember.Handlebars.compile('<h2>People</h2>')
  13451. })
  13452. PhotoListView = Ember.View.extend({
  13453. classNames: ['my-photos-css-class'],
  13454. template: Ember.Handlebars.compile('<h2>Photos</h2>')
  13455. })
  13456. viewStates = Ember.StateManager.create({
  13457. showingPeople: Ember.ViewState.create({
  13458. view: ContactListView
  13459. }),
  13460. showingPhotos: Ember.ViewState.create({
  13461. view: PhotoListView
  13462. })
  13463. })
  13464. viewStates.transitionTo('showingPeople')
  13465. The above code will change the rendered HTML from
  13466. <body></body>
  13467. to
  13468. <body>
  13469. <div id="ember1" class="ember-view my-contacts-css-class">
  13470. <h2>People</h2>
  13471. </div>
  13472. </body>
  13473. Changing the current state via `transitionTo` from `showingPeople` to
  13474. `showingPhotos` will remove the `showingPeople` view and add the `showingPhotos` view:
  13475. viewStates.transitionTo('showingPhotos')
  13476. will change the rendered HTML to
  13477. <body>
  13478. <div id="ember2" class="ember-view my-photos-css-class">
  13479. <h2>Photos</h2>
  13480. </div>
  13481. </body>
  13482. When entering nested `ViewState`s, each state's view will be draw into the the StateManager's
  13483. `rootView` or `rootElement` as siblings.
  13484. ContactListView = Ember.View.extend({
  13485. classNames: ['my-contacts-css-class'],
  13486. template: Ember.Handlebars.compile('<h2>People</h2>')
  13487. })
  13488. EditAContactView = Ember.View.extend({
  13489. classNames: ['editing-a-contact-css-class'],
  13490. template: Ember.Handlebars.compile('Editing...')
  13491. })
  13492. viewStates = Ember.StateManager.create({
  13493. showingPeople: Ember.ViewState.create({
  13494. view: ContactListView,
  13495. withEditingPanel: Ember.ViewState.create({
  13496. view: EditAContactView
  13497. })
  13498. })
  13499. })
  13500. viewStates.transitionTo('showingPeople.withEditingPanel')
  13501. Will result in the following rendered HTML:
  13502. <body>
  13503. <div id="ember2" class="ember-view my-contacts-css-class">
  13504. <h2>People</h2>
  13505. </div>
  13506. <div id="ember2" class="ember-view editing-a-contact-css-class">
  13507. Editing...
  13508. </div>
  13509. </body>
  13510. ViewState views are added and removed from their StateManager's view via their
  13511. `enter` and `exit` methods. If you need to override these methods, be sure to call
  13512. `_super` to maintain the adding and removing behavior:
  13513. viewStates = Ember.StateManager.create({
  13514. aState: Ember.ViewState.create({
  13515. view: Ember.View.extend({}),
  13516. enter: function(manager){
  13517. // calling _super ensures this view will be
  13518. // properly inserted
  13519. this._super(manager);
  13520. // now you can do other things
  13521. }
  13522. })
  13523. })
  13524. ## Managing Multiple Sections of A Page With States
  13525. Multiple StateManagers can be combined to control multiple areas of an application's rendered views.
  13526. Given the following HTML body:
  13527. <body>
  13528. <div id='sidebar-nav'>
  13529. </div>
  13530. <div id='content-area'>
  13531. </div>
  13532. </body>
  13533. You could separately manage view state for each section with two StateManagers
  13534. navigationStates = Ember.StateManager.create({
  13535. rootElement: '#sidebar-nav',
  13536. userAuthenticated: Em.ViewState.create({
  13537. view: Ember.View.extend({})
  13538. }),
  13539. userNotAuthenticated: Em.ViewState.create({
  13540. view: Ember.View.extend({})
  13541. })
  13542. })
  13543. contentStates = Ember.StateManager.create({
  13544. rootElement: '#content-area',
  13545. books: Em.ViewState.create({
  13546. view: Ember.View.extend({})
  13547. }),
  13548. music: Em.ViewState.create({
  13549. view: Ember.View.extend({})
  13550. })
  13551. })
  13552. If you prefer to start with an empty body and manage state programmatically you
  13553. can also take advantage of StateManager's `rootView` property and the ability of
  13554. `Ember.ContainerView`s to manually manage their child views.
  13555. dashboard = Ember.ContainerView.create({
  13556. childViews: ['navigationAreaView', 'contentAreaView'],
  13557. navigationAreaView: Ember.ContainerView.create({}),
  13558. contentAreaView: Ember.ContainerView.create({})
  13559. })
  13560. navigationStates = Ember.StateManager.create({
  13561. rootView: dashboard.get('navigationAreaView'),
  13562. userAuthenticated: Em.ViewState.create({
  13563. view: Ember.View.extend({})
  13564. }),
  13565. userNotAuthenticated: Em.ViewState.create({
  13566. view: Ember.View.extend({})
  13567. })
  13568. })
  13569. contentStates = Ember.StateManager.create({
  13570. rootView: dashboard.get('contentAreaView'),
  13571. books: Em.ViewState.create({
  13572. view: Ember.View.extend({})
  13573. }),
  13574. music: Em.ViewState.create({
  13575. view: Ember.View.extend({})
  13576. })
  13577. })
  13578. dashboard.appendTo('body')
  13579. ## User Manipulation of State via `{{action}}` Helpers
  13580. The Handlebars `{{action}}` helper is StateManager-aware and will use StateManager action sending
  13581. to connect user interaction to action-based state transitions.
  13582. Given the following body and handlebars template
  13583. <body>
  13584. <script type='text/x-handlebars'>
  13585. <a href="#" {{action "anAction" target="App.appStates"}}> Go </a>
  13586. </script>
  13587. </body>
  13588. And application code
  13589. App = Ember.Application.create()
  13590. App.appStates = Ember.StateManager.create({
  13591. initialState: 'aState',
  13592. aState: Ember.State.create({
  13593. anAction: function(manager, context){}
  13594. }),
  13595. bState: Ember.State.create({})
  13596. })
  13597. A user initiated click or touch event on "Go" will trigger the 'anAction' method of
  13598. `App.appStates.aState` with `App.appStates` as the first argument and a
  13599. `jQuery.Event` object as the second object. The `jQuery.Event` will include a property
  13600. `view` that references the `Ember.View` object that was interacted with.
  13601. **/
  13602. Ember.ViewState = Ember.State.extend(
  13603. /** @scope Ember.ViewState.prototype */ {
  13604. isViewState: true,
  13605. init: function() {
  13606. Ember.deprecate("Ember.ViewState is deprecated and will be removed from future releases. Consider using the outlet pattern to display nested views instead. For more information, see http://emberjs.com/guides/outlets/.");
  13607. return this._super();
  13608. },
  13609. enter: function(stateManager) {
  13610. var view = get(this, 'view'), root, childViews;
  13611. if (view) {
  13612. if (Ember.View.detect(view)) {
  13613. view = view.create();
  13614. set(this, 'view', view);
  13615. }
  13616. Ember.assert('view must be an Ember.View', view instanceof Ember.View);
  13617. root = stateManager.get('rootView');
  13618. if (root) {
  13619. childViews = get(root, 'childViews');
  13620. childViews.pushObject(view);
  13621. } else {
  13622. root = stateManager.get('rootElement') || 'body';
  13623. view.appendTo(root);
  13624. }
  13625. }
  13626. },
  13627. exit: function(stateManager) {
  13628. var view = get(this, 'view');
  13629. if (view) {
  13630. // If the view has a parent view, then it is
  13631. // part of a view hierarchy and should be removed
  13632. // from its parent.
  13633. if (get(view, 'parentView')) {
  13634. view.removeFromParent();
  13635. } else {
  13636. // Otherwise, the view is a "root view" and
  13637. // was appended directly to the DOM.
  13638. view.remove();
  13639. }
  13640. }
  13641. }
  13642. });
  13643. })();
  13644. (function() {
  13645. // ==========================================================================
  13646. // Project: Ember Statecharts
  13647. // Copyright: ©2011 Living Social Inc. and contributors.
  13648. // License: Licensed under MIT license (see license.js)
  13649. // ==========================================================================
  13650. })();
  13651. (function() {
  13652. // ==========================================================================
  13653. // Project: metamorph
  13654. // Copyright: ©2011 My Company Inc. All rights reserved.
  13655. // ==========================================================================
  13656. (function(window) {
  13657. var K = function(){},
  13658. guid = 0,
  13659. document = window.document,
  13660. // Feature-detect the W3C range API, the extended check is for IE9 which only partially supports ranges
  13661. supportsRange = ('createRange' in document) && (typeof Range !== 'undefined') && Range.prototype.createContextualFragment,
  13662. // Internet Explorer prior to 9 does not allow setting innerHTML if the first element
  13663. // is a "zero-scope" element. This problem can be worked around by making
  13664. // the first node an invisible text node. We, like Modernizr, use &shy;
  13665. needsShy = (function(){
  13666. var testEl = document.createElement('div');
  13667. testEl.innerHTML = "<div></div>";
  13668. testEl.firstChild.innerHTML = "<script></script>";
  13669. return testEl.firstChild.innerHTML === '';
  13670. })();
  13671. // Constructor that supports either Metamorph('foo') or new
  13672. // Metamorph('foo');
  13673. //
  13674. // Takes a string of HTML as the argument.
  13675. var Metamorph = function(html) {
  13676. var self;
  13677. if (this instanceof Metamorph) {
  13678. self = this;
  13679. } else {
  13680. self = new K();
  13681. }
  13682. self.innerHTML = html;
  13683. var myGuid = 'metamorph-'+(guid++);
  13684. self.start = myGuid + '-start';
  13685. self.end = myGuid + '-end';
  13686. return self;
  13687. };
  13688. K.prototype = Metamorph.prototype;
  13689. var rangeFor, htmlFunc, removeFunc, outerHTMLFunc, appendToFunc, afterFunc, prependFunc, startTagFunc, endTagFunc;
  13690. outerHTMLFunc = function() {
  13691. return this.startTag() + this.innerHTML + this.endTag();
  13692. };
  13693. startTagFunc = function() {
  13694. return "<script id='" + this.start + "' type='text/x-placeholder'></script>";
  13695. };
  13696. endTagFunc = function() {
  13697. return "<script id='" + this.end + "' type='text/x-placeholder'></script>";
  13698. };
  13699. // If we have the W3C range API, this process is relatively straight forward.
  13700. if (supportsRange) {
  13701. // Get a range for the current morph. Optionally include the starting and
  13702. // ending placeholders.
  13703. rangeFor = function(morph, outerToo) {
  13704. var range = document.createRange();
  13705. var before = document.getElementById(morph.start);
  13706. var after = document.getElementById(morph.end);
  13707. if (outerToo) {
  13708. range.setStartBefore(before);
  13709. range.setEndAfter(after);
  13710. } else {
  13711. range.setStartAfter(before);
  13712. range.setEndBefore(after);
  13713. }
  13714. return range;
  13715. };
  13716. htmlFunc = function(html, outerToo) {
  13717. // get a range for the current metamorph object
  13718. var range = rangeFor(this, outerToo);
  13719. // delete the contents of the range, which will be the
  13720. // nodes between the starting and ending placeholder.
  13721. range.deleteContents();
  13722. // create a new document fragment for the HTML
  13723. var fragment = range.createContextualFragment(html);
  13724. // insert the fragment into the range
  13725. range.insertNode(fragment);
  13726. };
  13727. removeFunc = function() {
  13728. // get a range for the current metamorph object including
  13729. // the starting and ending placeholders.
  13730. var range = rangeFor(this, true);
  13731. // delete the entire range.
  13732. range.deleteContents();
  13733. };
  13734. appendToFunc = function(node) {
  13735. var range = document.createRange();
  13736. range.setStart(node);
  13737. range.collapse(false);
  13738. var frag = range.createContextualFragment(this.outerHTML());
  13739. node.appendChild(frag);
  13740. };
  13741. afterFunc = function(html) {
  13742. var range = document.createRange();
  13743. var after = document.getElementById(this.end);
  13744. range.setStartAfter(after);
  13745. range.setEndAfter(after);
  13746. var fragment = range.createContextualFragment(html);
  13747. range.insertNode(fragment);
  13748. };
  13749. prependFunc = function(html) {
  13750. var range = document.createRange();
  13751. var start = document.getElementById(this.start);
  13752. range.setStartAfter(start);
  13753. range.setEndAfter(start);
  13754. var fragment = range.createContextualFragment(html);
  13755. range.insertNode(fragment);
  13756. };
  13757. } else {
  13758. /**
  13759. * This code is mostly taken from jQuery, with one exception. In jQuery's case, we
  13760. * have some HTML and we need to figure out how to convert it into some nodes.
  13761. *
  13762. * In this case, jQuery needs to scan the HTML looking for an opening tag and use
  13763. * that as the key for the wrap map. In our case, we know the parent node, and
  13764. * can use its type as the key for the wrap map.
  13765. **/
  13766. var wrapMap = {
  13767. select: [ 1, "<select multiple='multiple'>", "</select>" ],
  13768. fieldset: [ 1, "<fieldset>", "</fieldset>" ],
  13769. table: [ 1, "<table>", "</table>" ],
  13770. tbody: [ 2, "<table><tbody>", "</tbody></table>" ],
  13771. tr: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
  13772. colgroup: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
  13773. map: [ 1, "<map>", "</map>" ],
  13774. _default: [ 0, "", "" ]
  13775. };
  13776. /**
  13777. * Given a parent node and some HTML, generate a set of nodes. Return the first
  13778. * node, which will allow us to traverse the rest using nextSibling.
  13779. *
  13780. * We need to do this because innerHTML in IE does not really parse the nodes.
  13781. **/
  13782. var firstNodeFor = function(parentNode, html) {
  13783. var arr = wrapMap[parentNode.tagName.toLowerCase()] || wrapMap._default;
  13784. var depth = arr[0], start = arr[1], end = arr[2];
  13785. if (needsShy) { html = '&shy;'+html; }
  13786. var element = document.createElement('div');
  13787. element.innerHTML = start + html + end;
  13788. for (var i=0; i<=depth; i++) {
  13789. element = element.firstChild;
  13790. }
  13791. // Look for &shy; to remove it.
  13792. if (needsShy) {
  13793. var shyElement = element;
  13794. // Sometimes we get nameless elements with the shy inside
  13795. while (shyElement.nodeType === 1 && !shyElement.nodeName) {
  13796. shyElement = shyElement.firstChild;
  13797. }
  13798. // At this point it's the actual unicode character.
  13799. if (shyElement.nodeType === 3 && shyElement.nodeValue.charAt(0) === "\u00AD") {
  13800. shyElement.nodeValue = shyElement.nodeValue.slice(1);
  13801. }
  13802. }
  13803. return element;
  13804. };
  13805. /**
  13806. * In some cases, Internet Explorer can create an anonymous node in
  13807. * the hierarchy with no tagName. You can create this scenario via:
  13808. *
  13809. * div = document.createElement("div");
  13810. * div.innerHTML = "<table>&shy<script></script><tr><td>hi</td></tr></table>";
  13811. * div.firstChild.firstChild.tagName //=> ""
  13812. *
  13813. * If our script markers are inside such a node, we need to find that
  13814. * node and use *it* as the marker.
  13815. **/
  13816. var realNode = function(start) {
  13817. while (start.parentNode.tagName === "") {
  13818. start = start.parentNode;
  13819. }
  13820. return start;
  13821. };
  13822. /**
  13823. * When automatically adding a tbody, Internet Explorer inserts the
  13824. * tbody immediately before the first <tr>. Other browsers create it
  13825. * before the first node, no matter what.
  13826. *
  13827. * This means the the following code:
  13828. *
  13829. * div = document.createElement("div");
  13830. * div.innerHTML = "<table><script id='first'></script><tr><td>hi</td></tr><script id='last'></script></table>
  13831. *
  13832. * Generates the following DOM in IE:
  13833. *
  13834. * + div
  13835. * + table
  13836. * - script id='first'
  13837. * + tbody
  13838. * + tr
  13839. * + td
  13840. * - "hi"
  13841. * - script id='last'
  13842. *
  13843. * Which means that the two script tags, even though they were
  13844. * inserted at the same point in the hierarchy in the original
  13845. * HTML, now have different parents.
  13846. *
  13847. * This code reparents the first script tag by making it the tbody's
  13848. * first child.
  13849. **/
  13850. var fixParentage = function(start, end) {
  13851. if (start.parentNode !== end.parentNode) {
  13852. end.parentNode.insertBefore(start, end.parentNode.firstChild);
  13853. }
  13854. };
  13855. htmlFunc = function(html, outerToo) {
  13856. // get the real starting node. see realNode for details.
  13857. var start = realNode(document.getElementById(this.start));
  13858. var end = document.getElementById(this.end);
  13859. var parentNode = end.parentNode;
  13860. var node, nextSibling, last;
  13861. // make sure that the start and end nodes share the same
  13862. // parent. If not, fix it.
  13863. fixParentage(start, end);
  13864. // remove all of the nodes after the starting placeholder and
  13865. // before the ending placeholder.
  13866. node = start.nextSibling;
  13867. while (node) {
  13868. nextSibling = node.nextSibling;
  13869. last = node === end;
  13870. // if this is the last node, and we want to remove it as well,
  13871. // set the `end` node to the next sibling. This is because
  13872. // for the rest of the function, we insert the new nodes
  13873. // before the end (note that insertBefore(node, null) is
  13874. // the same as appendChild(node)).
  13875. //
  13876. // if we do not want to remove it, just break.
  13877. if (last) {
  13878. if (outerToo) { end = node.nextSibling; } else { break; }
  13879. }
  13880. node.parentNode.removeChild(node);
  13881. // if this is the last node and we didn't break before
  13882. // (because we wanted to remove the outer nodes), break
  13883. // now.
  13884. if (last) { break; }
  13885. node = nextSibling;
  13886. }
  13887. // get the first node for the HTML string, even in cases like
  13888. // tables and lists where a simple innerHTML on a div would
  13889. // swallow some of the content.
  13890. node = firstNodeFor(start.parentNode, html);
  13891. // copy the nodes for the HTML between the starting and ending
  13892. // placeholder.
  13893. while (node) {
  13894. nextSibling = node.nextSibling;
  13895. parentNode.insertBefore(node, end);
  13896. node = nextSibling;
  13897. }
  13898. };
  13899. // remove the nodes in the DOM representing this metamorph.
  13900. //
  13901. // this includes the starting and ending placeholders.
  13902. removeFunc = function() {
  13903. var start = realNode(document.getElementById(this.start));
  13904. var end = document.getElementById(this.end);
  13905. this.html('');
  13906. start.parentNode.removeChild(start);
  13907. end.parentNode.removeChild(end);
  13908. };
  13909. appendToFunc = function(parentNode) {
  13910. var node = firstNodeFor(parentNode, this.outerHTML());
  13911. while (node) {
  13912. nextSibling = node.nextSibling;
  13913. parentNode.appendChild(node);
  13914. node = nextSibling;
  13915. }
  13916. };
  13917. afterFunc = function(html) {
  13918. // get the real starting node. see realNode for details.
  13919. var end = document.getElementById(this.end);
  13920. var insertBefore = end.nextSibling;
  13921. var parentNode = end.parentNode;
  13922. var nextSibling;
  13923. var node;
  13924. // get the first node for the HTML string, even in cases like
  13925. // tables and lists where a simple innerHTML on a div would
  13926. // swallow some of the content.
  13927. node = firstNodeFor(parentNode, html);
  13928. // copy the nodes for the HTML between the starting and ending
  13929. // placeholder.
  13930. while (node) {
  13931. nextSibling = node.nextSibling;
  13932. parentNode.insertBefore(node, insertBefore);
  13933. node = nextSibling;
  13934. }
  13935. };
  13936. prependFunc = function(html) {
  13937. var start = document.getElementById(this.start);
  13938. var parentNode = start.parentNode;
  13939. var nextSibling;
  13940. var node;
  13941. node = firstNodeFor(parentNode, html);
  13942. var insertBefore = start.nextSibling;
  13943. while (node) {
  13944. nextSibling = node.nextSibling;
  13945. parentNode.insertBefore(node, insertBefore);
  13946. node = nextSibling;
  13947. }
  13948. }
  13949. }
  13950. Metamorph.prototype.html = function(html) {
  13951. this.checkRemoved();
  13952. if (html === undefined) { return this.innerHTML; }
  13953. htmlFunc.call(this, html);
  13954. this.innerHTML = html;
  13955. };
  13956. Metamorph.prototype.replaceWith = function(html) {
  13957. this.checkRemoved();
  13958. htmlFunc.call(this, html, true);
  13959. };
  13960. Metamorph.prototype.remove = removeFunc;
  13961. Metamorph.prototype.outerHTML = outerHTMLFunc;
  13962. Metamorph.prototype.appendTo = appendToFunc;
  13963. Metamorph.prototype.after = afterFunc;
  13964. Metamorph.prototype.prepend = prependFunc;
  13965. Metamorph.prototype.startTag = startTagFunc;
  13966. Metamorph.prototype.endTag = endTagFunc;
  13967. Metamorph.prototype.isRemoved = function() {
  13968. var before = document.getElementById(this.start);
  13969. var after = document.getElementById(this.end);
  13970. return !before || !after;
  13971. };
  13972. Metamorph.prototype.checkRemoved = function() {
  13973. if (this.isRemoved()) {
  13974. throw new Error("Cannot perform operations on a Metamorph that is not in the DOM.");
  13975. }
  13976. };
  13977. window.Metamorph = Metamorph;
  13978. })(this);
  13979. })();
  13980. (function() {
  13981. // ==========================================================================
  13982. // Project: Ember Handlebars Views
  13983. // Copyright: ©2011 Strobe Inc. and contributors.
  13984. // License: Licensed under MIT license (see license.js)
  13985. // ==========================================================================
  13986. /*globals Handlebars */
  13987. var objectCreate = Ember.create;
  13988. /**
  13989. @namespace
  13990. @name Handlebars
  13991. @private
  13992. */
  13993. /**
  13994. @namespace
  13995. @name Handlebars.helpers
  13996. @description Helpers for Handlebars templates
  13997. */
  13998. Ember.assert("Ember Handlebars requires Handlebars 1.0.beta.5 or greater", window.Handlebars && window.Handlebars.VERSION.match(/^1\.0\.beta\.[56789]$|^1\.0\.rc\.[123456789]+/));
  13999. /**
  14000. @class
  14001. Prepares the Handlebars templating library for use inside Ember's view
  14002. system.
  14003. The Ember.Handlebars object is the standard Handlebars library, extended to use
  14004. Ember's get() method instead of direct property access, which allows
  14005. computed properties to be used inside templates.
  14006. To create an Ember.Handlebars template, call Ember.Handlebars.compile(). This will
  14007. return a function that can be used by Ember.View for rendering.
  14008. */
  14009. Ember.Handlebars = objectCreate(Handlebars);
  14010. Ember.Handlebars.helpers = objectCreate(Handlebars.helpers);
  14011. /**
  14012. Override the the opcode compiler and JavaScript compiler for Handlebars.
  14013. @private
  14014. */
  14015. Ember.Handlebars.Compiler = function() {};
  14016. Ember.Handlebars.Compiler.prototype = objectCreate(Handlebars.Compiler.prototype);
  14017. Ember.Handlebars.Compiler.prototype.compiler = Ember.Handlebars.Compiler;
  14018. /** @private */
  14019. Ember.Handlebars.JavaScriptCompiler = function() {};
  14020. Ember.Handlebars.JavaScriptCompiler.prototype = objectCreate(Handlebars.JavaScriptCompiler.prototype);
  14021. Ember.Handlebars.JavaScriptCompiler.prototype.compiler = Ember.Handlebars.JavaScriptCompiler;
  14022. Ember.Handlebars.JavaScriptCompiler.prototype.namespace = "Ember.Handlebars";
  14023. Ember.Handlebars.JavaScriptCompiler.prototype.initializeBuffer = function() {
  14024. return "''";
  14025. };
  14026. /**
  14027. Override the default buffer for Ember Handlebars. By default, Handlebars creates
  14028. an empty String at the beginning of each invocation and appends to it. Ember's
  14029. Handlebars overrides this to append to a single shared buffer.
  14030. @private
  14031. */
  14032. Ember.Handlebars.JavaScriptCompiler.prototype.appendToBuffer = function(string) {
  14033. return "data.buffer.push("+string+");";
  14034. };
  14035. /**
  14036. Rewrite simple mustaches from {{foo}} to {{bind "foo"}}. This means that all simple
  14037. mustaches in Ember's Handlebars will also set up an observer to keep the DOM
  14038. up to date when the underlying property changes.
  14039. @private
  14040. */
  14041. Ember.Handlebars.Compiler.prototype.mustache = function(mustache) {
  14042. if (mustache.params.length || mustache.hash) {
  14043. return Handlebars.Compiler.prototype.mustache.call(this, mustache);
  14044. } else {
  14045. var id = new Handlebars.AST.IdNode(['_triageMustache']);
  14046. // Update the mustache node to include a hash value indicating whether the original node
  14047. // was escaped. This will allow us to properly escape values when the underlying value
  14048. // changes and we need to re-render the value.
  14049. if(!mustache.escaped) {
  14050. mustache.hash = mustache.hash || new Handlebars.AST.HashNode([]);
  14051. mustache.hash.pairs.push(["unescaped", new Handlebars.AST.StringNode("true")]);
  14052. }
  14053. mustache = new Handlebars.AST.MustacheNode([id].concat([mustache.id]), mustache.hash, !mustache.escaped);
  14054. return Handlebars.Compiler.prototype.mustache.call(this, mustache);
  14055. }
  14056. };
  14057. /**
  14058. Used for precompilation of Ember Handlebars templates. This will not be used during normal
  14059. app execution.
  14060. @param {String} string The template to precompile
  14061. */
  14062. Ember.Handlebars.precompile = function(string) {
  14063. var ast = Handlebars.parse(string);
  14064. var options = {
  14065. knownHelpers: {
  14066. action: true,
  14067. unbound: true,
  14068. bindAttr: true,
  14069. template: true,
  14070. view: true,
  14071. _triageMustache: true
  14072. },
  14073. data: true,
  14074. stringParams: true
  14075. };
  14076. var environment = new Ember.Handlebars.Compiler().compile(ast, options);
  14077. return new Ember.Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true);
  14078. };
  14079. /**
  14080. The entry point for Ember Handlebars. This replaces the default Handlebars.compile and turns on
  14081. template-local data and String parameters.
  14082. @param {String} string The template to compile
  14083. */
  14084. Ember.Handlebars.compile = function(string) {
  14085. var ast = Handlebars.parse(string);
  14086. var options = { data: true, stringParams: true };
  14087. var environment = new Ember.Handlebars.Compiler().compile(ast, options);
  14088. var templateSpec = new Ember.Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true);
  14089. return Handlebars.template(templateSpec);
  14090. };
  14091. /**
  14092. If a path starts with a reserved keyword, returns the root
  14093. that should be used.
  14094. @private
  14095. */
  14096. var normalizePath = Ember.Handlebars.normalizePath = function(root, path, data) {
  14097. var keywords = (data && data.keywords) || {},
  14098. keyword, isKeyword;
  14099. // Get the first segment of the path. For example, if the
  14100. // path is "foo.bar.baz", returns "foo".
  14101. keyword = path.split('.', 1)[0];
  14102. // Test to see if the first path is a keyword that has been
  14103. // passed along in the view's data hash. If so, we will treat
  14104. // that object as the new root.
  14105. if (keywords.hasOwnProperty(keyword)) {
  14106. // Look up the value in the template's data hash.
  14107. root = keywords[keyword];
  14108. isKeyword = true;
  14109. // Handle cases where the entire path is the reserved
  14110. // word. In that case, return the object itself.
  14111. if (path === keyword) {
  14112. path = '';
  14113. } else {
  14114. // Strip the keyword from the path and look up
  14115. // the remainder from the newly found root.
  14116. path = path.substr(keyword.length+1);
  14117. }
  14118. }
  14119. return { root: root, path: path, isKeyword: isKeyword };
  14120. };
  14121. /**
  14122. Lookup both on root and on window. If the path starts with
  14123. a keyword, the corresponding object will be looked up in the
  14124. template's data hash and used to resolve the path.
  14125. @param {Object} root The object to look up the property on
  14126. @param {String} path The path to be lookedup
  14127. @param {Object} options The template's option hash
  14128. */
  14129. Ember.Handlebars.getPath = function(root, path, options) {
  14130. var data = options && options.data,
  14131. normalizedPath = normalizePath(root, path, data),
  14132. value;
  14133. // In cases where the path begins with a keyword, change the
  14134. // root to the value represented by that keyword, and ensure
  14135. // the path is relative to it.
  14136. root = normalizedPath.root;
  14137. path = normalizedPath.path;
  14138. value = Ember.get(root, path);
  14139. if (value === undefined && root !== window && Ember.isGlobalPath(path)) {
  14140. value = Ember.get(window, path);
  14141. }
  14142. return value;
  14143. };
  14144. /**
  14145. Registers a helper in Handlebars that will be called if no property with the
  14146. given name can be found on the current context object, and no helper with
  14147. that name is registered.
  14148. This throws an exception with a more helpful error message so the user can
  14149. track down where the problem is happening.
  14150. @name Handlebars.helpers.helperMissing
  14151. @param {String} path
  14152. @param {Hash} options
  14153. */
  14154. Ember.Handlebars.registerHelper('helperMissing', function(path, options) {
  14155. var error, view = "";
  14156. error = "%@ Handlebars error: Could not find property '%@' on object %@.";
  14157. if (options.data){
  14158. view = options.data.view;
  14159. }
  14160. throw new Ember.Error(Ember.String.fmt(error, [view, path, this]));
  14161. });
  14162. })();
  14163. (function() {
  14164. Ember.String.htmlSafe = function(str) {
  14165. return new Handlebars.SafeString(str);
  14166. };
  14167. var htmlSafe = Ember.String.htmlSafe;
  14168. if (Ember.EXTEND_PROTOTYPES) {
  14169. /**
  14170. @see Ember.String.htmlSafe
  14171. */
  14172. String.prototype.htmlSafe = function() {
  14173. return htmlSafe(this);
  14174. };
  14175. }
  14176. })();
  14177. (function() {
  14178. /*jshint newcap:false*/
  14179. var set = Ember.set, get = Ember.get;
  14180. var DOMManager = {
  14181. remove: function(view) {
  14182. var morph = view.morph;
  14183. if (morph.isRemoved()) { return; }
  14184. set(view, 'element', null);
  14185. view._lastInsert = null;
  14186. morph.remove();
  14187. },
  14188. prepend: function(view, childView) {
  14189. childView._insertElementLater(function() {
  14190. var morph = view.morph;
  14191. morph.prepend(childView.outerHTML);
  14192. childView.outerHTML = null;
  14193. });
  14194. },
  14195. after: function(view, nextView) {
  14196. nextView._insertElementLater(function() {
  14197. var morph = view.morph;
  14198. morph.after(nextView.outerHTML);
  14199. nextView.outerHTML = null;
  14200. });
  14201. },
  14202. replace: function(view) {
  14203. var morph = view.morph;
  14204. view.transitionTo('preRender');
  14205. view.clearRenderedChildren();
  14206. var buffer = view.renderToBuffer();
  14207. Ember.run.schedule('render', this, function() {
  14208. if (get(view, 'isDestroyed')) { return; }
  14209. view.invalidateRecursively('element');
  14210. view._notifyWillInsertElement();
  14211. morph.replaceWith(buffer.string());
  14212. view.transitionTo('inDOM');
  14213. view._notifyDidInsertElement();
  14214. });
  14215. },
  14216. empty: function(view) {
  14217. view.morph.html("");
  14218. }
  14219. };
  14220. // The `morph` and `outerHTML` properties are internal only
  14221. // and not observable.
  14222. Ember._Metamorph = Ember.Mixin.create({
  14223. isVirtual: true,
  14224. tagName: '',
  14225. init: function() {
  14226. this._super();
  14227. this.morph = Metamorph();
  14228. },
  14229. beforeRender: function(buffer) {
  14230. buffer.push(this.morph.startTag());
  14231. },
  14232. afterRender: function(buffer) {
  14233. buffer.push(this.morph.endTag());
  14234. },
  14235. createElement: function() {
  14236. var buffer = this.renderToBuffer();
  14237. this.outerHTML = buffer.string();
  14238. this.clearBuffer();
  14239. },
  14240. domManager: DOMManager
  14241. });
  14242. Ember._MetamorphView = Ember.View.extend(Ember._Metamorph);
  14243. })();
  14244. (function() {
  14245. // ==========================================================================
  14246. // Project: Ember Handlebars Views
  14247. // Copyright: ©2011 Strobe Inc. and contributors.
  14248. // License: Licensed under MIT license (see license.js)
  14249. // ==========================================================================
  14250. /*globals Handlebars */
  14251. var get = Ember.get, set = Ember.set, getPath = Ember.Handlebars.getPath;
  14252. /**
  14253. @ignore
  14254. @private
  14255. @class
  14256. Ember._HandlebarsBoundView is a private view created by the Handlebars `{{bind}}`
  14257. helpers that is used to keep track of bound properties.
  14258. Every time a property is bound using a `{{mustache}}`, an anonymous subclass
  14259. of Ember._HandlebarsBoundView is created with the appropriate sub-template and
  14260. context set up. When the associated property changes, just the template for
  14261. this view will re-render.
  14262. */
  14263. Ember._HandlebarsBoundView = Ember._MetamorphView.extend({
  14264. /** @scope Ember._HandlebarsBoundView.prototype */
  14265. /**
  14266. The function used to determine if the `displayTemplate` or
  14267. `inverseTemplate` should be rendered. This should be a function that takes
  14268. a value and returns a Boolean.
  14269. @type Function
  14270. @default null
  14271. */
  14272. shouldDisplayFunc: null,
  14273. /**
  14274. Whether the template rendered by this view gets passed the context object
  14275. of its parent template, or gets passed the value of retrieving `path`
  14276. from the `pathRoot`.
  14277. For example, this is true when using the `{{#if}}` helper, because the
  14278. template inside the helper should look up properties relative to the same
  14279. object as outside the block. This would be false when used with `{{#with
  14280. foo}}` because the template should receive the object found by evaluating
  14281. `foo`.
  14282. @type Boolean
  14283. @default false
  14284. */
  14285. preserveContext: false,
  14286. /**
  14287. If `preserveContext` is true, this is the object that will be used
  14288. to render the template.
  14289. @type Object
  14290. */
  14291. previousContext: null,
  14292. /**
  14293. The template to render when `shouldDisplayFunc` evaluates to true.
  14294. @type Function
  14295. @default null
  14296. */
  14297. displayTemplate: null,
  14298. /**
  14299. The template to render when `shouldDisplayFunc` evaluates to false.
  14300. @type Function
  14301. @default null
  14302. */
  14303. inverseTemplate: null,
  14304. /**
  14305. The path to look up on `pathRoot` that is passed to
  14306. `shouldDisplayFunc` to determine which template to render.
  14307. In addition, if `preserveContext` is false, the object at this path will
  14308. be passed to the template when rendering.
  14309. @type String
  14310. @default null
  14311. */
  14312. path: null,
  14313. /**
  14314. The object from which the `path` will be looked up. Sometimes this is the
  14315. same as the `previousContext`, but in cases where this view has been generated
  14316. for paths that start with a keyword such as `view` or `controller`, the
  14317. path root will be that resolved object.
  14318. @type Object
  14319. */
  14320. pathRoot: null,
  14321. normalizedValue: Ember.computed(function() {
  14322. var path = get(this, 'path'),
  14323. pathRoot = get(this, 'pathRoot'),
  14324. valueNormalizer = get(this, 'valueNormalizerFunc'),
  14325. result, templateData;
  14326. // Use the pathRoot as the result if no path is provided. This
  14327. // happens if the path is `this`, which gets normalized into
  14328. // a `pathRoot` of the current Handlebars context and a path
  14329. // of `''`.
  14330. if (path === '') {
  14331. result = pathRoot;
  14332. } else {
  14333. templateData = get(this, 'templateData');
  14334. result = getPath(pathRoot, path, { data: templateData });
  14335. }
  14336. return valueNormalizer ? valueNormalizer(result) : result;
  14337. }).property('path', 'pathRoot', 'valueNormalizerFunc').volatile(),
  14338. rerenderIfNeeded: function() {
  14339. if (!get(this, 'isDestroyed') && get(this, 'normalizedValue') !== this._lastNormalizedValue) {
  14340. this.rerender();
  14341. }
  14342. },
  14343. /**
  14344. Determines which template to invoke, sets up the correct state based on
  14345. that logic, then invokes the default Ember.View `render` implementation.
  14346. This method will first look up the `path` key on `pathRoot`,
  14347. then pass that value to the `shouldDisplayFunc` function. If that returns
  14348. true, the `displayTemplate` function will be rendered to DOM. Otherwise,
  14349. `inverseTemplate`, if specified, will be rendered.
  14350. For example, if this Ember._HandlebarsBoundView represented the {{#with foo}}
  14351. helper, it would look up the `foo` property of its context, and
  14352. `shouldDisplayFunc` would always return true. The object found by looking
  14353. up `foo` would be passed to `displayTemplate`.
  14354. @param {Ember.RenderBuffer} buffer
  14355. */
  14356. render: function(buffer) {
  14357. // If not invoked via a triple-mustache ({{{foo}}}), escape
  14358. // the content of the template.
  14359. var escape = get(this, 'isEscaped');
  14360. var shouldDisplay = get(this, 'shouldDisplayFunc'),
  14361. preserveContext = get(this, 'preserveContext'),
  14362. context = get(this, 'previousContext');
  14363. var inverseTemplate = get(this, 'inverseTemplate'),
  14364. displayTemplate = get(this, 'displayTemplate');
  14365. var result = get(this, 'normalizedValue');
  14366. this._lastNormalizedValue = result;
  14367. // First, test the conditional to see if we should
  14368. // render the template or not.
  14369. if (shouldDisplay(result)) {
  14370. set(this, 'template', displayTemplate);
  14371. // If we are preserving the context (for example, if this
  14372. // is an #if block, call the template with the same object.
  14373. if (preserveContext) {
  14374. set(this, '_context', context);
  14375. } else {
  14376. // Otherwise, determine if this is a block bind or not.
  14377. // If so, pass the specified object to the template
  14378. if (displayTemplate) {
  14379. set(this, '_context', result);
  14380. } else {
  14381. // This is not a bind block, just push the result of the
  14382. // expression to the render context and return.
  14383. if (result === null || result === undefined) {
  14384. result = "";
  14385. } else if (!(result instanceof Handlebars.SafeString)) {
  14386. result = String(result);
  14387. }
  14388. if (escape) { result = Handlebars.Utils.escapeExpression(result); }
  14389. buffer.push(result);
  14390. return;
  14391. }
  14392. }
  14393. } else if (inverseTemplate) {
  14394. set(this, 'template', inverseTemplate);
  14395. if (preserveContext) {
  14396. set(this, '_context', context);
  14397. } else {
  14398. set(this, '_context', result);
  14399. }
  14400. } else {
  14401. set(this, 'template', function() { return ''; });
  14402. }
  14403. return this._super(buffer);
  14404. }
  14405. });
  14406. })();
  14407. (function() {
  14408. // ==========================================================================
  14409. // Project: Ember Handlebars Views
  14410. // Copyright: ©2011 Strobe Inc. and contributors.
  14411. // License: Licensed under MIT license (see license.js)
  14412. // ==========================================================================
  14413. var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt;
  14414. var getPath = Ember.Handlebars.getPath, normalizePath = Ember.Handlebars.normalizePath;
  14415. var forEach = Ember.ArrayPolyfills.forEach;
  14416. var EmberHandlebars = Ember.Handlebars, helpers = EmberHandlebars.helpers;
  14417. // Binds a property into the DOM. This will create a hook in DOM that the
  14418. // KVO system will look for and update if the property changes.
  14419. /** @private */
  14420. function bind(property, options, preserveContext, shouldDisplay, valueNormalizer) {
  14421. var data = options.data,
  14422. fn = options.fn,
  14423. inverse = options.inverse,
  14424. view = data.view,
  14425. currentContext = this,
  14426. pathRoot, path, normalized;
  14427. normalized = normalizePath(currentContext, property, data);
  14428. pathRoot = normalized.root;
  14429. path = normalized.path;
  14430. // Set up observers for observable objects
  14431. if ('object' === typeof this) {
  14432. // Create the view that will wrap the output of this template/property
  14433. // and add it to the nearest view's childViews array.
  14434. // See the documentation of Ember._HandlebarsBoundView for more.
  14435. var bindView = view.createChildView(Ember._HandlebarsBoundView, {
  14436. preserveContext: preserveContext,
  14437. shouldDisplayFunc: shouldDisplay,
  14438. valueNormalizerFunc: valueNormalizer,
  14439. displayTemplate: fn,
  14440. inverseTemplate: inverse,
  14441. path: path,
  14442. pathRoot: pathRoot,
  14443. previousContext: currentContext,
  14444. isEscaped: !options.hash.unescaped,
  14445. templateData: options.data
  14446. });
  14447. view.appendChild(bindView);
  14448. /** @private */
  14449. var observer = function() {
  14450. Ember.run.once(bindView, 'rerenderIfNeeded');
  14451. };
  14452. // Observes the given property on the context and
  14453. // tells the Ember._HandlebarsBoundView to re-render. If property
  14454. // is an empty string, we are printing the current context
  14455. // object ({{this}}) so updating it is not our responsibility.
  14456. if (path !== '') {
  14457. Ember.addObserver(pathRoot, path, observer);
  14458. }
  14459. } else {
  14460. // The object is not observable, so just render it out and
  14461. // be done with it.
  14462. data.buffer.push(getPath(pathRoot, path, options));
  14463. }
  14464. }
  14465. /**
  14466. '_triageMustache' is used internally select between a binding and helper for
  14467. the given context. Until this point, it would be hard to determine if the
  14468. mustache is a property reference or a regular helper reference. This triage
  14469. helper resolves that.
  14470. This would not be typically invoked by directly.
  14471. @private
  14472. @name Handlebars.helpers._triageMustache
  14473. @param {String} property Property/helperID to triage
  14474. @param {Function} fn Context to provide for rendering
  14475. @returns {String} HTML string
  14476. */
  14477. EmberHandlebars.registerHelper('_triageMustache', function(property, fn) {
  14478. Ember.assert("You cannot pass more than one argument to the _triageMustache helper", arguments.length <= 2);
  14479. if (helpers[property]) {
  14480. return helpers[property].call(this, fn);
  14481. }
  14482. else {
  14483. return helpers.bind.apply(this, arguments);
  14484. }
  14485. });
  14486. /**
  14487. `bind` can be used to display a value, then update that value if it
  14488. changes. For example, if you wanted to print the `title` property of
  14489. `content`:
  14490. {{bind "content.title"}}
  14491. This will return the `title` property as a string, then create a new
  14492. observer at the specified path. If it changes, it will update the value in
  14493. DOM. Note that if you need to support IE7 and IE8 you must modify the
  14494. model objects properties using Ember.get() and Ember.set() for this to work as
  14495. it relies on Ember's KVO system. For all other browsers this will be handled
  14496. for you automatically.
  14497. @private
  14498. @name Handlebars.helpers.bind
  14499. @param {String} property Property to bind
  14500. @param {Function} fn Context to provide for rendering
  14501. @returns {String} HTML string
  14502. */
  14503. EmberHandlebars.registerHelper('bind', function(property, fn) {
  14504. Ember.assert("You cannot pass more than one argument to the bind helper", arguments.length <= 2);
  14505. var context = (fn.contexts && fn.contexts[0]) || this;
  14506. return bind.call(context, property, fn, false, function(result) {
  14507. return !Ember.none(result);
  14508. });
  14509. });
  14510. /**
  14511. Use the `boundIf` helper to create a conditional that re-evaluates
  14512. whenever the bound value changes.
  14513. {{#boundIf "content.shouldDisplayTitle"}}
  14514. {{content.title}}
  14515. {{/boundIf}}
  14516. @private
  14517. @name Handlebars.helpers.boundIf
  14518. @param {String} property Property to bind
  14519. @param {Function} fn Context to provide for rendering
  14520. @returns {String} HTML string
  14521. */
  14522. EmberHandlebars.registerHelper('boundIf', function(property, fn) {
  14523. var context = (fn.contexts && fn.contexts[0]) || this;
  14524. var func = function(result) {
  14525. if (Ember.typeOf(result) === 'array') {
  14526. return get(result, 'length') !== 0;
  14527. } else {
  14528. return !!result;
  14529. }
  14530. };
  14531. return bind.call(context, property, fn, true, func, func);
  14532. });
  14533. /**
  14534. @name Handlebars.helpers.with
  14535. @param {Function} context
  14536. @param {Hash} options
  14537. @returns {String} HTML string
  14538. */
  14539. EmberHandlebars.registerHelper('with', function(context, options) {
  14540. if (arguments.length === 4) {
  14541. var keywordName, path, rootPath, normalized;
  14542. Ember.assert("If you pass more than one argument to the with helper, it must be in the form #with foo as bar", arguments[1] === "as");
  14543. options = arguments[3];
  14544. keywordName = arguments[2];
  14545. path = arguments[0];
  14546. Ember.assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop);
  14547. if (Ember.isGlobalPath(path)) {
  14548. Ember.bind(options.data.keywords, keywordName, path);
  14549. } else {
  14550. normalized = normalizePath(this, path, options.data);
  14551. path = normalized.path;
  14552. rootPath = normalized.root;
  14553. // This is a workaround for the fact that you cannot bind separate objects
  14554. // together. When we implement that functionality, we should use it here.
  14555. var contextKey = Ember.$.expando + Ember.guidFor(rootPath);
  14556. options.data.keywords[contextKey] = rootPath;
  14557. // if the path is '' ("this"), just bind directly to the current context
  14558. var contextPath = path ? contextKey + '.' + path : contextKey;
  14559. Ember.bind(options.data.keywords, keywordName, contextPath);
  14560. }
  14561. return bind.call(this, path, options.fn, true, function(result) {
  14562. return !Ember.none(result);
  14563. });
  14564. } else {
  14565. Ember.assert("You must pass exactly one argument to the with helper", arguments.length === 2);
  14566. Ember.assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop);
  14567. return helpers.bind.call(options.contexts[0], context, options);
  14568. }
  14569. });
  14570. /**
  14571. @name Handlebars.helpers.if
  14572. @param {Function} context
  14573. @param {Hash} options
  14574. @returns {String} HTML string
  14575. */
  14576. EmberHandlebars.registerHelper('if', function(context, options) {
  14577. Ember.assert("You must pass exactly one argument to the if helper", arguments.length === 2);
  14578. Ember.assert("You must pass a block to the if helper", options.fn && options.fn !== Handlebars.VM.noop);
  14579. return helpers.boundIf.call(options.contexts[0], context, options);
  14580. });
  14581. /**
  14582. @name Handlebars.helpers.unless
  14583. @param {Function} context
  14584. @param {Hash} options
  14585. @returns {String} HTML string
  14586. */
  14587. EmberHandlebars.registerHelper('unless', function(context, options) {
  14588. Ember.assert("You must pass exactly one argument to the unless helper", arguments.length === 2);
  14589. Ember.assert("You must pass a block to the unless helper", options.fn && options.fn !== Handlebars.VM.noop);
  14590. var fn = options.fn, inverse = options.inverse;
  14591. options.fn = inverse;
  14592. options.inverse = fn;
  14593. return helpers.boundIf.call(options.contexts[0], context, options);
  14594. });
  14595. /**
  14596. `bindAttr` allows you to create a binding between DOM element attributes and
  14597. Ember objects. For example:
  14598. <img {{bindAttr src="imageUrl" alt="imageTitle"}}>
  14599. @name Handlebars.helpers.bindAttr
  14600. @param {Hash} options
  14601. @returns {String} HTML string
  14602. */
  14603. EmberHandlebars.registerHelper('bindAttr', function(options) {
  14604. var attrs = options.hash;
  14605. Ember.assert("You must specify at least one hash argument to bindAttr", !!Ember.keys(attrs).length);
  14606. var view = options.data.view;
  14607. var ret = [];
  14608. var ctx = this;
  14609. // Generate a unique id for this element. This will be added as a
  14610. // data attribute to the element so it can be looked up when
  14611. // the bound property changes.
  14612. var dataId = ++Ember.$.uuid;
  14613. // Handle classes differently, as we can bind multiple classes
  14614. var classBindings = attrs['class'];
  14615. if (classBindings !== null && classBindings !== undefined) {
  14616. var classResults = EmberHandlebars.bindClasses(this, classBindings, view, dataId, options);
  14617. ret.push('class="' + Handlebars.Utils.escapeExpression(classResults.join(' ')) + '"');
  14618. delete attrs['class'];
  14619. }
  14620. var attrKeys = Ember.keys(attrs);
  14621. // For each attribute passed, create an observer and emit the
  14622. // current value of the property as an attribute.
  14623. forEach.call(attrKeys, function(attr) {
  14624. var path = attrs[attr],
  14625. pathRoot, normalized;
  14626. Ember.assert(fmt("You must provide a String for a bound attribute, not %@", [path]), typeof path === 'string');
  14627. normalized = normalizePath(ctx, path, options.data);
  14628. pathRoot = normalized.root;
  14629. path = normalized.path;
  14630. var value = (path === 'this') ? pathRoot : getPath(pathRoot, path, options),
  14631. type = Ember.typeOf(value);
  14632. Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [value]), value === null || value === undefined || type === 'number' || type === 'string' || type === 'boolean');
  14633. var observer, invoker;
  14634. /** @private */
  14635. observer = function observer() {
  14636. var result = getPath(pathRoot, path, options);
  14637. Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [result]), result === null || result === undefined || typeof result === 'number' || typeof result === 'string' || typeof result === 'boolean');
  14638. var elem = view.$("[data-bindattr-" + dataId + "='" + dataId + "']");
  14639. // If we aren't able to find the element, it means the element
  14640. // to which we were bound has been removed from the view.
  14641. // In that case, we can assume the template has been re-rendered
  14642. // and we need to clean up the observer.
  14643. if (!elem || elem.length === 0) {
  14644. Ember.removeObserver(pathRoot, path, invoker);
  14645. return;
  14646. }
  14647. Ember.View.applyAttributeBindings(elem, attr, result);
  14648. };
  14649. /** @private */
  14650. invoker = function() {
  14651. Ember.run.once(observer);
  14652. };
  14653. // Add an observer to the view for when the property changes.
  14654. // When the observer fires, find the element using the
  14655. // unique data id and update the attribute to the new value.
  14656. if (path !== 'this') {
  14657. Ember.addObserver(pathRoot, path, invoker);
  14658. }
  14659. // if this changes, also change the logic in ember-views/lib/views/view.js
  14660. if ((type === 'string' || (type === 'number' && !isNaN(value)))) {
  14661. ret.push(attr + '="' + Handlebars.Utils.escapeExpression(value) + '"');
  14662. } else if (value && type === 'boolean') {
  14663. // The developer controls the attr name, so it should always be safe
  14664. ret.push(attr + '="' + attr + '"');
  14665. }
  14666. }, this);
  14667. // Add the unique identifier
  14668. // NOTE: We use all lower-case since Firefox has problems with mixed case in SVG
  14669. ret.push('data-bindattr-' + dataId + '="' + dataId + '"');
  14670. return new EmberHandlebars.SafeString(ret.join(' '));
  14671. });
  14672. /**
  14673. Helper that, given a space-separated string of property paths and a context,
  14674. returns an array of class names. Calling this method also has the side
  14675. effect of setting up observers at those property paths, such that if they
  14676. change, the correct class name will be reapplied to the DOM element.
  14677. For example, if you pass the string "fooBar", it will first look up the
  14678. "fooBar" value of the context. If that value is true, it will add the
  14679. "foo-bar" class to the current element (i.e., the dasherized form of
  14680. "fooBar"). If the value is a string, it will add that string as the class.
  14681. Otherwise, it will not add any new class name.
  14682. @param {Ember.Object} context
  14683. The context from which to lookup properties
  14684. @param {String} classBindings
  14685. A string, space-separated, of class bindings to use
  14686. @param {Ember.View} view
  14687. The view in which observers should look for the element to update
  14688. @param {Srting} bindAttrId
  14689. Optional bindAttr id used to lookup elements
  14690. @returns {Array} An array of class names to add
  14691. */
  14692. EmberHandlebars.bindClasses = function(context, classBindings, view, bindAttrId, options) {
  14693. var ret = [], newClass, value, elem;
  14694. // Helper method to retrieve the property from the context and
  14695. // determine which class string to return, based on whether it is
  14696. // a Boolean or not.
  14697. var classStringForPath = function(root, parsedPath, options) {
  14698. var val,
  14699. path = parsedPath.path;
  14700. if (path === 'this') {
  14701. val = root;
  14702. } else if (path === '') {
  14703. val = true;
  14704. } else {
  14705. val = getPath(root, path, options);
  14706. }
  14707. return Ember.View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName);
  14708. };
  14709. // For each property passed, loop through and setup
  14710. // an observer.
  14711. forEach.call(classBindings.split(' '), function(binding) {
  14712. // Variable in which the old class value is saved. The observer function
  14713. // closes over this variable, so it knows which string to remove when
  14714. // the property changes.
  14715. var oldClass;
  14716. var observer, invoker;
  14717. var parsedPath = Ember.View._parsePropertyPath(binding),
  14718. path = parsedPath.path,
  14719. pathRoot = context,
  14720. normalized;
  14721. if (path !== '' && path !== 'this') {
  14722. normalized = normalizePath(context, path, options.data);
  14723. pathRoot = normalized.root;
  14724. path = normalized.path;
  14725. }
  14726. // Set up an observer on the context. If the property changes, toggle the
  14727. // class name.
  14728. /** @private */
  14729. observer = function() {
  14730. // Get the current value of the property
  14731. newClass = classStringForPath(pathRoot, parsedPath, options);
  14732. elem = bindAttrId ? view.$("[data-bindattr-" + bindAttrId + "='" + bindAttrId + "']") : view.$();
  14733. // If we can't find the element anymore, a parent template has been
  14734. // re-rendered and we've been nuked. Remove the observer.
  14735. if (!elem || elem.length === 0) {
  14736. Ember.removeObserver(pathRoot, path, invoker);
  14737. } else {
  14738. // If we had previously added a class to the element, remove it.
  14739. if (oldClass) {
  14740. elem.removeClass(oldClass);
  14741. }
  14742. // If necessary, add a new class. Make sure we keep track of it so
  14743. // it can be removed in the future.
  14744. if (newClass) {
  14745. elem.addClass(newClass);
  14746. oldClass = newClass;
  14747. } else {
  14748. oldClass = null;
  14749. }
  14750. }
  14751. };
  14752. /** @private */
  14753. invoker = function() {
  14754. Ember.run.once(observer);
  14755. };
  14756. if (path !== '' && path !== 'this') {
  14757. Ember.addObserver(pathRoot, path, invoker);
  14758. }
  14759. // We've already setup the observer; now we just need to figure out the
  14760. // correct behavior right now on the first pass through.
  14761. value = classStringForPath(pathRoot, parsedPath, options);
  14762. if (value) {
  14763. ret.push(value);
  14764. // Make sure we save the current value so that it can be removed if the
  14765. // observer fires.
  14766. oldClass = value;
  14767. }
  14768. });
  14769. return ret;
  14770. };
  14771. })();
  14772. (function() {
  14773. // ==========================================================================
  14774. // Project: Ember Handlebars Views
  14775. // Copyright: ©2011 Strobe Inc. and contributors.
  14776. // License: Licensed under MIT license (see license.js)
  14777. // ==========================================================================
  14778. /*globals Handlebars */
  14779. // TODO: Don't require the entire module
  14780. var get = Ember.get, set = Ember.set;
  14781. var PARENT_VIEW_PATH = /^parentView\./;
  14782. var EmberHandlebars = Ember.Handlebars;
  14783. var VIEW_PRESERVES_CONTEXT = Ember.VIEW_PRESERVES_CONTEXT;
  14784. /** @private */
  14785. EmberHandlebars.ViewHelper = Ember.Object.create({
  14786. propertiesFromHTMLOptions: function(options, thisContext) {
  14787. var hash = options.hash, data = options.data;
  14788. var extensions = {},
  14789. classes = hash['class'],
  14790. dup = false;
  14791. if (hash.id) {
  14792. extensions.elementId = hash.id;
  14793. dup = true;
  14794. }
  14795. if (classes) {
  14796. classes = classes.split(' ');
  14797. extensions.classNames = classes;
  14798. dup = true;
  14799. }
  14800. if (hash.classBinding) {
  14801. extensions.classNameBindings = hash.classBinding.split(' ');
  14802. dup = true;
  14803. }
  14804. if (hash.classNameBindings) {
  14805. if (extensions.classNameBindings === undefined) extensions.classNameBindings = [];
  14806. extensions.classNameBindings = extensions.classNameBindings.concat(hash.classNameBindings.split(' '));
  14807. dup = true;
  14808. }
  14809. if (hash.attributeBindings) {
  14810. Ember.assert("Setting 'attributeBindings' via Handlebars is not allowed. Please subclass Ember.View and set it there instead.");
  14811. extensions.attributeBindings = null;
  14812. dup = true;
  14813. }
  14814. if (dup) {
  14815. hash = Ember.$.extend({}, hash);
  14816. delete hash.id;
  14817. delete hash['class'];
  14818. delete hash.classBinding;
  14819. }
  14820. // Set the proper context for all bindings passed to the helper. This applies to regular attribute bindings
  14821. // as well as class name bindings. If the bindings are local, make them relative to the current context
  14822. // instead of the view.
  14823. var path;
  14824. // Evaluate the context of regular attribute bindings:
  14825. for (var prop in hash) {
  14826. if (!hash.hasOwnProperty(prop)) { continue; }
  14827. // Test if the property ends in "Binding"
  14828. if (Ember.IS_BINDING.test(prop) && typeof hash[prop] === 'string') {
  14829. path = this.contextualizeBindingPath(hash[prop], data);
  14830. if (path) { hash[prop] = path; }
  14831. }
  14832. }
  14833. // Evaluate the context of class name bindings:
  14834. if (extensions.classNameBindings) {
  14835. for (var b in extensions.classNameBindings) {
  14836. var full = extensions.classNameBindings[b];
  14837. if (typeof full === 'string') {
  14838. // Contextualize the path of classNameBinding so this:
  14839. //
  14840. // classNameBinding="isGreen:green"
  14841. //
  14842. // is converted to this:
  14843. //
  14844. // classNameBinding="bindingContext.isGreen:green"
  14845. var parsedPath = Ember.View._parsePropertyPath(full);
  14846. path = this.contextualizeBindingPath(parsedPath.path, data);
  14847. if (path) { extensions.classNameBindings[b] = path + parsedPath.classNames; }
  14848. }
  14849. }
  14850. }
  14851. // Make the current template context available to the view
  14852. // for the bindings set up above.
  14853. extensions.bindingContext = thisContext;
  14854. return Ember.$.extend(hash, extensions);
  14855. },
  14856. // Transform bindings from the current context to a context that can be evaluated within the view.
  14857. // Returns null if the path shouldn't be changed.
  14858. //
  14859. // TODO: consider the addition of a prefix that would allow this method to return `path`.
  14860. contextualizeBindingPath: function(path, data) {
  14861. var normalized = Ember.Handlebars.normalizePath(null, path, data);
  14862. if (normalized.isKeyword) {
  14863. return 'templateData.keywords.' + path;
  14864. } else if (Ember.isGlobalPath(path)) {
  14865. return null;
  14866. } else if (path === 'this') {
  14867. return 'bindingContext';
  14868. } else {
  14869. return 'bindingContext.' + path;
  14870. }
  14871. },
  14872. helper: function(thisContext, path, options) {
  14873. var inverse = options.inverse,
  14874. data = options.data,
  14875. view = data.view,
  14876. fn = options.fn,
  14877. hash = options.hash,
  14878. newView;
  14879. if ('string' === typeof path) {
  14880. newView = EmberHandlebars.getPath(thisContext, path, options);
  14881. Ember.assert("Unable to find view at path '" + path + "'", !!newView);
  14882. } else {
  14883. newView = path;
  14884. }
  14885. Ember.assert(Ember.String.fmt('You must pass a view class to the #view helper, not %@ (%@)', [path, newView]), Ember.View.detect(newView));
  14886. var viewOptions = this.propertiesFromHTMLOptions(options, thisContext);
  14887. var currentView = data.view;
  14888. viewOptions.templateData = options.data;
  14889. if (fn) {
  14890. Ember.assert("You cannot provide a template block if you also specified a templateName", !get(viewOptions, 'templateName') && !get(newView.proto(), 'templateName'));
  14891. viewOptions.template = fn;
  14892. }
  14893. // We only want to override the `_context` computed property if there is
  14894. // no specified controller. See View#_context for more information.
  14895. if (VIEW_PRESERVES_CONTEXT && !newView.proto().controller && !newView.proto().controllerBinding && !viewOptions.controller && !viewOptions.controllerBinding) {
  14896. viewOptions._context = thisContext;
  14897. }
  14898. currentView.appendChild(newView, viewOptions);
  14899. }
  14900. });
  14901. /**
  14902. `{{view}}` inserts a new instance of `Ember.View` into a template passing its options
  14903. to the `Ember.View`'s `create` method and using the supplied block as the view's own template.
  14904. An empty `<body>` and the following template:
  14905. <script type="text/x-handlebars">
  14906. A span:
  14907. {{#view tagName="span"}}
  14908. hello.
  14909. {{/view}}
  14910. </script>
  14911. Will result in HTML structure:
  14912. <body>
  14913. <!-- Note: the handlebars template script
  14914. also results in a rendered Ember.View
  14915. which is the outer <div> here -->
  14916. <div class="ember-view">
  14917. A span:
  14918. <span id="ember1" class="ember-view">
  14919. Hello.
  14920. </span>
  14921. </div>
  14922. </body>
  14923. ### parentView setting
  14924. The `parentView` property of the new `Ember.View` instance created through `{{view}}`
  14925. will be set to the `Ember.View` instance of the template where `{{view}}` was called.
  14926. aView = Ember.View.create({
  14927. template: Ember.Handlebars.compile("{{#view}} my parent: {{parentView.elementId}} {{/view}}")
  14928. })
  14929. aView.appendTo('body')
  14930. Will result in HTML structure:
  14931. <div id="ember1" class="ember-view">
  14932. <div id="ember2" class="ember-view">
  14933. my parent: ember1
  14934. </div>
  14935. </div>
  14936. ### Setting CSS id and class attributes
  14937. The HTML `id` attribute can be set on the `{{view}}`'s resulting element with the `id` option.
  14938. This option will _not_ be passed to `Ember.View.create`.
  14939. <script type="text/x-handlebars">
  14940. {{#view tagName="span" id="a-custom-id"}}
  14941. hello.
  14942. {{/view}}
  14943. </script>
  14944. Results in the following HTML structure:
  14945. <div class="ember-view">
  14946. <span id="a-custom-id" class="ember-view">
  14947. hello.
  14948. </span>
  14949. </div>
  14950. The HTML `class` attribute can be set on the `{{view}}`'s resulting element with
  14951. the `class` or `classNameBindings` options. The `class` option
  14952. will directly set the CSS `class` attribute and will not be passed to
  14953. `Ember.View.create`. `classNameBindings` will be passed to `create` and use
  14954. `Ember.View`'s class name binding functionality:
  14955. <script type="text/x-handlebars">
  14956. {{#view tagName="span" class="a-custom-class"}}
  14957. hello.
  14958. {{/view}}
  14959. </script>
  14960. Results in the following HTML structure:
  14961. <div class="ember-view">
  14962. <span id="ember2" class="ember-view a-custom-class">
  14963. hello.
  14964. </span>
  14965. </div>
  14966. ### Supplying a different view class
  14967. `{{view}}` can take an optional first argument before its supplied options to specify a
  14968. path to a custom view class.
  14969. <script type="text/x-handlebars">
  14970. {{#view "MyApp.CustomView"}}
  14971. hello.
  14972. {{/view}}
  14973. </script>
  14974. The first argument can also be a relative path. Ember will search for the view class
  14975. starting at the `Ember.View` of the template where `{{view}}` was used as the root object:
  14976. MyApp = Ember.Application.create({})
  14977. MyApp.OuterView = Ember.View.extend({
  14978. innerViewClass: Ember.View.extend({
  14979. classNames: ['a-custom-view-class-as-property']
  14980. }),
  14981. template: Ember.Handlebars.compile('{{#view "innerViewClass"}} hi {{/view}}')
  14982. })
  14983. MyApp.OuterView.create().appendTo('body')
  14984. Will result in the following HTML:
  14985. <div id="ember1" class="ember-view">
  14986. <div id="ember2" class="ember-view a-custom-view-class-as-property">
  14987. hi
  14988. </div>
  14989. </div>
  14990. ### Blockless use
  14991. If you supply a custom `Ember.View` subclass that specifies its own template
  14992. or provide a `templateName` option to `{{view}}` it can be used without supplying a block.
  14993. Attempts to use both a `templateName` option and supply a block will throw an error.
  14994. <script type="text/x-handlebars">
  14995. {{view "MyApp.ViewWithATemplateDefined"}}
  14996. </script>
  14997. ### viewName property
  14998. You can supply a `viewName` option to `{{view}}`. The `Ember.View` instance will
  14999. be referenced as a property of its parent view by this name.
  15000. aView = Ember.View.create({
  15001. template: Ember.Handlebars.compile('{{#view viewName="aChildByName"}} hi {{/view}}')
  15002. })
  15003. aView.appendTo('body')
  15004. aView.get('aChildByName') // the instance of Ember.View created by {{view}} helper
  15005. @name Handlebars.helpers.view
  15006. @param {String} path
  15007. @param {Hash} options
  15008. @returns {String} HTML string
  15009. */
  15010. EmberHandlebars.registerHelper('view', function(path, options) {
  15011. Ember.assert("The view helper only takes a single argument", arguments.length <= 2);
  15012. // If no path is provided, treat path param as options.
  15013. if (path && path.data && path.data.isRenderData) {
  15014. options = path;
  15015. path = "Ember.View";
  15016. }
  15017. return EmberHandlebars.ViewHelper.helper(this, path, options);
  15018. });
  15019. })();
  15020. (function() {
  15021. // ==========================================================================
  15022. // Project: Ember Handlebars Views
  15023. // Copyright: ©2011 Strobe Inc. and contributors.
  15024. // License: Licensed under MIT license (see license.js)
  15025. // ==========================================================================
  15026. /*globals Handlebars */
  15027. // TODO: Don't require all of this module
  15028. var get = Ember.get, getPath = Ember.Handlebars.getPath, fmt = Ember.String.fmt;
  15029. /**
  15030. `{{collection}}` is a `Ember.Handlebars` helper for adding instances of
  15031. `Ember.CollectionView` to a template. See `Ember.CollectionView` for additional
  15032. information on how a `CollectionView` functions.
  15033. `{{collection}}`'s primary use is as a block helper with a `contentBinding` option
  15034. pointing towards an `Ember.Array`-compatible object. An `Ember.View` instance will
  15035. be created for each item in its `content` property. Each view will have its own
  15036. `content` property set to the appropriate item in the collection.
  15037. The provided block will be applied as the template for each item's view.
  15038. Given an empty `<body>` the following template:
  15039. <script type="text/x-handlebars">
  15040. {{#collection contentBinding="App.items"}}
  15041. Hi {{content.name}}
  15042. {{/collection}}
  15043. </script>
  15044. And the following application code
  15045. App = Ember.Application.create()
  15046. App.items = [
  15047. Ember.Object.create({name: 'Dave'}),
  15048. Ember.Object.create({name: 'Mary'}),
  15049. Ember.Object.create({name: 'Sara'})
  15050. ]
  15051. Will result in the HTML structure below
  15052. <div class="ember-view">
  15053. <div class="ember-view">Hi Dave</div>
  15054. <div class="ember-view">Hi Mary</div>
  15055. <div class="ember-view">Hi Sara</div>
  15056. </div>
  15057. ### Blockless Use
  15058. If you provide an `itemViewClass` option that has its own `template` you can omit
  15059. the block.
  15060. The following template:
  15061. <script type="text/x-handlebars">
  15062. {{collection contentBinding="App.items" itemViewClass="App.AnItemView"}}
  15063. </script>
  15064. And application code
  15065. App = Ember.Application.create()
  15066. App.items = [
  15067. Ember.Object.create({name: 'Dave'}),
  15068. Ember.Object.create({name: 'Mary'}),
  15069. Ember.Object.create({name: 'Sara'})
  15070. ]
  15071. App.AnItemView = Ember.View.extend({
  15072. template: Ember.Handlebars.compile("Greetings {{content.name}}")
  15073. })
  15074. Will result in the HTML structure below
  15075. <div class="ember-view">
  15076. <div class="ember-view">Greetings Dave</div>
  15077. <div class="ember-view">Greetings Mary</div>
  15078. <div class="ember-view">Greetings Sara</div>
  15079. </div>
  15080. ### Specifying a CollectionView subclass
  15081. By default the `{{collection}}` helper will create an instance of `Ember.CollectionView`.
  15082. You can supply a `Ember.CollectionView` subclass to the helper by passing it
  15083. as the first argument:
  15084. <script type="text/x-handlebars">
  15085. {{#collection App.MyCustomCollectionClass contentBinding="App.items"}}
  15086. Hi {{content.name}}
  15087. {{/collection}}
  15088. </script>
  15089. ### Forwarded `item.*`-named Options
  15090. As with the `{{view}}`, helper options passed to the `{{collection}}` will be set on
  15091. the resulting `Ember.CollectionView` as properties. Additionally, options prefixed with
  15092. `item` will be applied to the views rendered for each item (note the camelcasing):
  15093. <script type="text/x-handlebars">
  15094. {{#collection contentBinding="App.items"
  15095. itemTagName="p"
  15096. itemClassNames="greeting"}}
  15097. Howdy {{content.name}}
  15098. {{/collection}}
  15099. </script>
  15100. Will result in the following HTML structure:
  15101. <div class="ember-view">
  15102. <p class="ember-view greeting">Howdy Dave</p>
  15103. <p class="ember-view greeting">Howdy Mary</p>
  15104. <p class="ember-view greeting">Howdy Sara</p>
  15105. </div>
  15106. @name Handlebars.helpers.collection
  15107. @param {String} path
  15108. @param {Hash} options
  15109. @returns {String} HTML string
  15110. */
  15111. Ember.Handlebars.registerHelper('collection', function(path, options) {
  15112. // If no path is provided, treat path param as options.
  15113. if (path && path.data && path.data.isRenderData) {
  15114. options = path;
  15115. path = undefined;
  15116. Ember.assert("You cannot pass more than one argument to the collection helper", arguments.length === 1);
  15117. } else {
  15118. Ember.assert("You cannot pass more than one argument to the collection helper", arguments.length === 2);
  15119. }
  15120. var fn = options.fn;
  15121. var data = options.data;
  15122. var inverse = options.inverse;
  15123. // If passed a path string, convert that into an object.
  15124. // Otherwise, just default to the standard class.
  15125. var collectionClass;
  15126. collectionClass = path ? getPath(this, path, options) : Ember.CollectionView;
  15127. Ember.assert(fmt("%@ #collection: Could not find collection class %@", [data.view, path]), !!collectionClass);
  15128. var hash = options.hash, itemHash = {}, match;
  15129. // Extract item view class if provided else default to the standard class
  15130. var itemViewClass, itemViewPath = hash.itemViewClass;
  15131. var collectionPrototype = collectionClass.proto();
  15132. delete hash.itemViewClass;
  15133. itemViewClass = itemViewPath ? getPath(collectionPrototype, itemViewPath, options) : collectionPrototype.itemViewClass;
  15134. Ember.assert(fmt("%@ #collection: Could not find itemViewClass %@", [data.view, itemViewPath]), !!itemViewClass);
  15135. // Go through options passed to the {{collection}} helper and extract options
  15136. // that configure item views instead of the collection itself.
  15137. for (var prop in hash) {
  15138. if (hash.hasOwnProperty(prop)) {
  15139. match = prop.match(/^item(.)(.*)$/);
  15140. if(match) {
  15141. // Convert itemShouldFoo -> shouldFoo
  15142. itemHash[match[1].toLowerCase() + match[2]] = hash[prop];
  15143. // Delete from hash as this will end up getting passed to the
  15144. // {{view}} helper method.
  15145. delete hash[prop];
  15146. }
  15147. }
  15148. }
  15149. var tagName = hash.tagName || collectionPrototype.tagName;
  15150. if (fn) {
  15151. itemHash.template = fn;
  15152. delete options.fn;
  15153. }
  15154. var emptyViewClass;
  15155. if (inverse && inverse !== Handlebars.VM.noop) {
  15156. emptyViewClass = get(collectionPrototype, 'emptyViewClass');
  15157. emptyViewClass = emptyViewClass.extend({
  15158. template: inverse,
  15159. tagName: itemHash.tagName
  15160. });
  15161. } else if (hash.emptyViewClass) {
  15162. emptyViewClass = getPath(this, hash.emptyViewClass, options);
  15163. }
  15164. hash.emptyView = emptyViewClass;
  15165. if (hash.eachHelper === 'each') {
  15166. itemHash._context = Ember.computed(function() {
  15167. return get(this, 'content');
  15168. }).property('content');
  15169. delete hash.eachHelper;
  15170. }
  15171. var viewOptions = Ember.Handlebars.ViewHelper.propertiesFromHTMLOptions({ data: data, hash: itemHash }, this);
  15172. hash.itemViewClass = itemViewClass.extend(viewOptions);
  15173. return Ember.Handlebars.helpers.view.call(this, collectionClass, options);
  15174. });
  15175. })();
  15176. (function() {
  15177. // ==========================================================================
  15178. // Project: Ember Handlebars Views
  15179. // Copyright: ©2011 Strobe Inc. and contributors.
  15180. // License: Licensed under MIT license (see license.js)
  15181. // ==========================================================================
  15182. /*globals Handlebars */
  15183. var getPath = Ember.Handlebars.getPath;
  15184. /**
  15185. `unbound` allows you to output a property without binding. *Important:* The
  15186. output will not be updated if the property changes. Use with caution.
  15187. <div>{{unbound somePropertyThatDoesntChange}}</div>
  15188. @name Handlebars.helpers.unbound
  15189. @param {String} property
  15190. @returns {String} HTML string
  15191. */
  15192. Ember.Handlebars.registerHelper('unbound', function(property, fn) {
  15193. var context = (fn.contexts && fn.contexts[0]) || this;
  15194. return getPath(context, property, fn);
  15195. });
  15196. })();
  15197. (function() {
  15198. // ==========================================================================
  15199. // Project: Ember Handlebars Views
  15200. // Copyright: ©2011 Strobe Inc. and contributors.
  15201. // License: Licensed under MIT license (see license.js)
  15202. // ==========================================================================
  15203. /*jshint debug:true*/
  15204. var getPath = Ember.Handlebars.getPath, normalizePath = Ember.Handlebars.normalizePath;
  15205. /**
  15206. `log` allows you to output the value of a value in the current rendering
  15207. context.
  15208. {{log myVariable}}
  15209. @name Handlebars.helpers.log
  15210. @param {String} property
  15211. */
  15212. Ember.Handlebars.registerHelper('log', function(property, options) {
  15213. var context = (options.contexts && options.contexts[0]) || this,
  15214. normalized = normalizePath(context, property, options.data),
  15215. pathRoot = normalized.root,
  15216. path = normalized.path,
  15217. value = (path === 'this') ? pathRoot : getPath(pathRoot, path, options);
  15218. Ember.Logger.log(value);
  15219. });
  15220. /**
  15221. The `debugger` helper executes the `debugger` statement in the current
  15222. context.
  15223. {{debugger}}
  15224. @name Handlebars.helpers.debugger
  15225. @param {String} property
  15226. */
  15227. Ember.Handlebars.registerHelper('debugger', function() {
  15228. debugger;
  15229. });
  15230. })();
  15231. (function() {
  15232. var get = Ember.get, set = Ember.set;
  15233. Ember.Handlebars.EachView = Ember.CollectionView.extend(Ember._Metamorph, {
  15234. itemViewClass: Ember._MetamorphView,
  15235. emptyViewClass: Ember._MetamorphView,
  15236. createChildView: function(view, attrs) {
  15237. view = this._super(view, attrs);
  15238. // At the moment, if a container view subclass wants
  15239. // to insert keywords, it is responsible for cloning
  15240. // the keywords hash. This will be fixed momentarily.
  15241. var keyword = get(this, 'keyword');
  15242. if (keyword) {
  15243. var data = get(view, 'templateData');
  15244. data = Ember.copy(data);
  15245. data.keywords = view.cloneKeywords();
  15246. set(view, 'templateData', data);
  15247. var content = get(view, 'content');
  15248. // In this case, we do not bind, because the `content` of
  15249. // a #each item cannot change.
  15250. data.keywords[keyword] = content;
  15251. }
  15252. return view;
  15253. }
  15254. });
  15255. Ember.Handlebars.registerHelper('each', function(path, options) {
  15256. if (arguments.length === 4) {
  15257. Ember.assert("If you pass more than one argument to the each helper, it must be in the form #each foo in bar", arguments[1] === "in");
  15258. var keywordName = arguments[0];
  15259. options = arguments[3];
  15260. path = arguments[2];
  15261. if (path === '') { path = "this"; }
  15262. options.hash.keyword = keywordName;
  15263. } else {
  15264. options.hash.eachHelper = 'each';
  15265. }
  15266. Ember.assert("You must pass a block to the each helper", options.fn && options.fn !== Handlebars.VM.noop);
  15267. options.hash.contentBinding = path;
  15268. // Set up emptyView as a metamorph with no tag
  15269. //options.hash.emptyViewClass = Ember._MetamorphView;
  15270. return Ember.Handlebars.helpers.collection.call(this, 'Ember.Handlebars.EachView', options);
  15271. });
  15272. })();
  15273. (function() {
  15274. /**
  15275. `template` allows you to render a template from inside another template.
  15276. This allows you to re-use the same template in multiple places. For example:
  15277. <script type="text/x-handlebars">
  15278. {{#with loggedInUser}}
  15279. Last Login: {{lastLogin}}
  15280. User Info: {{template "user_info"}}
  15281. {{/with}}
  15282. </script>
  15283. <script type="text/x-handlebars" data-template-name="user_info">
  15284. Name: <em>{{name}}</em>
  15285. Karma: <em>{{karma}}</em>
  15286. </script>
  15287. This helper looks for templates in the global Ember.TEMPLATES hash. If you
  15288. add &lt;script&gt; tags to your page with the `data-template-name` attribute set,
  15289. they will be compiled and placed in this hash automatically.
  15290. You can also manually register templates by adding them to the hash:
  15291. Ember.TEMPLATES["my_cool_template"] = Ember.Handlebars.compile('<b>{{user}}</b>');
  15292. @name Handlebars.helpers.template
  15293. @param {String} templateName the template to render
  15294. */
  15295. Ember.Handlebars.registerHelper('template', function(name, options) {
  15296. var template = Ember.TEMPLATES[name];
  15297. Ember.assert("Unable to find template with name '"+name+"'.", !!template);
  15298. Ember.TEMPLATES[name](this, { data: options.data });
  15299. });
  15300. })();
  15301. (function() {
  15302. var EmberHandlebars = Ember.Handlebars,
  15303. getPath = EmberHandlebars.getPath,
  15304. get = Ember.get,
  15305. a_slice = Array.prototype.slice;
  15306. var ActionHelper = EmberHandlebars.ActionHelper = {
  15307. registeredActions: {}
  15308. };
  15309. ActionHelper.registerAction = function(actionName, options) {
  15310. var actionId = (++Ember.$.uuid).toString();
  15311. ActionHelper.registeredActions[actionId] = {
  15312. eventName: options.eventName,
  15313. handler: function(event) {
  15314. var modifier = event.shiftKey || event.metaKey || event.altKey || event.ctrlKey,
  15315. secondaryClick = event.which > 1, // IE9 may return undefined
  15316. nonStandard = modifier || secondaryClick;
  15317. if (options.link && nonStandard) {
  15318. // Allow the browser to handle special link clicks normally
  15319. return;
  15320. }
  15321. event.preventDefault();
  15322. event.view = options.view;
  15323. if (options.hasOwnProperty('context')) {
  15324. event.context = options.context;
  15325. }
  15326. if (options.hasOwnProperty('contexts')) {
  15327. event.contexts = options.contexts;
  15328. }
  15329. var target = options.target;
  15330. // Check for StateManager (or compatible object)
  15331. if (target.isState && typeof target.send === 'function') {
  15332. return target.send(actionName, event);
  15333. } else {
  15334. Ember.assert(Ember.String.fmt('Target %@ does not have action %@', [target, actionName]), target[actionName]);
  15335. return target[actionName].call(target, event);
  15336. }
  15337. }
  15338. };
  15339. options.view.on('willRerender', function() {
  15340. delete ActionHelper.registeredActions[actionId];
  15341. });
  15342. return actionId;
  15343. };
  15344. /**
  15345. The `{{action}}` helper registers an HTML element within a template for
  15346. DOM event handling and forwards that interaction to the Application's router,
  15347. the template's `Ember.View` instance, or supplied `target` option (see 'Specifiying a Target').
  15348. User interaction with that element will invoke the supplied action name on
  15349. the appropriate target.
  15350. Given the following Handlebars template on the page
  15351. <script type="text/x-handlebars" data-template-name='a-template'>
  15352. <div {{action anActionName}}>
  15353. click me
  15354. </div>
  15355. </script>
  15356. And application code
  15357. AView = Ember.View.extend({
  15358. templateName; 'a-template',
  15359. anActionName: function(event){}
  15360. });
  15361. aView = AView.create();
  15362. aView.appendTo('body');
  15363. Will results in the following rendered HTML
  15364. <div class="ember-view">
  15365. <div data-ember-action="1">
  15366. click me
  15367. </div>
  15368. </div>
  15369. Clicking "click me" will trigger the `anActionName` method of the `aView`
  15370. object with a `jQuery.Event` object as its argument. The `jQuery.Event`
  15371. object will be extended to include a `view` property that is set to the
  15372. original view interacted with (in this case the `aView` object).
  15373. ### Event Propagation
  15374. Events triggered through the action helper will automatically have
  15375. `.preventDefault()` called on them. You do not need to do so in your event
  15376. handlers. To stop propagation of the event, simply return `false` from your
  15377. handler.
  15378. If you need the default handler to trigger you should either register your
  15379. own event handler, or use event methods on your view class. See Ember.View
  15380. 'Responding to Browser Events' for more information.
  15381. ### Specifying DOM event type
  15382. By default the `{{action}}` helper registers for DOM `click` events. You can
  15383. supply an `on` option to the helper to specify a different DOM event name:
  15384. <script type="text/x-handlebars" data-template-name='a-template'>
  15385. <div {{action anActionName on="doubleClick"}}>
  15386. click me
  15387. </div>
  15388. </script>
  15389. See Ember.View 'Responding to Browser Events' for a list of
  15390. acceptable DOM event names.
  15391. Because `{{action}}` depends on Ember's event dispatch system it will only
  15392. function if an `Ember.EventDispatcher` instance is available. An
  15393. `Ember.EventDispatcher` instance will be created when a new
  15394. `Ember.Application` is created. Having an instance of `Ember.Application`
  15395. will satisfy this requirement.
  15396. ### Specifying a Target
  15397. There are several possible target objects for `{{action}}` helpers:
  15398. In a typical `Ember.Router`-backed Application where views are managed
  15399. through use of the `{{outlet}}` helper, actions will be forwarded to the
  15400. current state of the Applications's Router. See Ember.Router 'Responding
  15401. to User-initiated Events' for more information.
  15402. If you manaully set the `target` property on the controller of a template's
  15403. `Ember.View` instance, the specifed `controller.target` will become the target
  15404. for any actions. Likely custom values for a controller's `target` are the
  15405. controller itself or a StateManager other than the Application's Router.
  15406. If the templates's view lacks a controller property the view itself is the target.
  15407. Finally, a `target` option can be provided to the helper to change which object
  15408. will receive the method call. This option must be a string representing a
  15409. path to an object:
  15410. <script type="text/x-handlebars" data-template-name='a-template'>
  15411. <div {{action anActionName target="MyApplication.someObject"}}>
  15412. click me
  15413. </div>
  15414. </script>
  15415. Clicking "click me" in the rendered HTML of the above template will trigger
  15416. the `anActionName` method of the object at `MyApplication.someObject`.
  15417. The first argument to this method will be a `jQuery.Event` extended to
  15418. include a `view` property that is set to the original view interacted with.
  15419. A path relative to the template's `Ember.View` instance can also be used as
  15420. a target:
  15421. <script type="text/x-handlebars" data-template-name='a-template'>
  15422. <div {{action anActionName target="parentView"}}>
  15423. click me
  15424. </div>
  15425. </script>
  15426. Clicking "click me" in the rendered HTML of the above template will trigger
  15427. the `anActionName` method of the view's parent view.
  15428. The `{{action}}` helper is `Ember.StateManager` aware. If the target of the
  15429. action is an `Ember.StateManager` instance `{{action}}` will use the `send`
  15430. functionality of StateManagers. The documentation for `Ember.StateManager`
  15431. has additional information about this use.
  15432. If an action's target does not implement a method that matches the supplied
  15433. action name an error will be thrown.
  15434. <script type="text/x-handlebars" data-template-name='a-template'>
  15435. <div {{action aMethodNameThatIsMissing}}>
  15436. click me
  15437. </div>
  15438. </script>
  15439. With the following application code
  15440. AView = Ember.View.extend({
  15441. templateName; 'a-template',
  15442. // note: no method 'aMethodNameThatIsMissing'
  15443. anActionName: function(event){}
  15444. });
  15445. aView = AView.create();
  15446. aView.appendTo('body');
  15447. Will throw `Uncaught TypeError: Cannot call method 'call' of undefined` when
  15448. "click me" is clicked.
  15449. ### Specifying a context
  15450. By default the `{{action}}` helper passes the current Handlebars context
  15451. along in the `jQuery.Event` object. You may specify an alternate object to
  15452. pass as the context by providing a property path:
  15453. <script type="text/x-handlebars" data-template-name='a-template'>
  15454. {{#each person in people}}
  15455. <div {{action edit person}}>
  15456. click me
  15457. </div>
  15458. {{/each}}
  15459. </script>
  15460. @name Handlebars.helpers.action
  15461. @param {String} actionName
  15462. @param {Object...} contexts
  15463. @param {Hash} options
  15464. */
  15465. EmberHandlebars.registerHelper('action', function(actionName) {
  15466. var options = arguments[arguments.length - 1],
  15467. contexts = a_slice.call(arguments, 1, -1);
  15468. var hash = options.hash,
  15469. view = options.data.view,
  15470. target, controller, link;
  15471. // create a hash to pass along to registerAction
  15472. var action = {
  15473. eventName: hash.on || "click"
  15474. };
  15475. action.view = view = get(view, 'concreteView');
  15476. if (hash.target) {
  15477. target = getPath(this, hash.target, options);
  15478. } else if (controller = options.data.keywords.controller) {
  15479. target = get(controller, 'target');
  15480. }
  15481. action.target = target = target || view;
  15482. if (contexts.length) {
  15483. action.contexts = contexts = Ember.EnumerableUtils.map(contexts, function(context) {
  15484. return getPath(this, context, options);
  15485. }, this);
  15486. action.context = contexts[0];
  15487. }
  15488. var output = [], url;
  15489. if (hash.href && target.urlForEvent) {
  15490. url = target.urlForEvent.apply(target, [actionName].concat(contexts));
  15491. output.push('href="' + url + '"');
  15492. action.link = true;
  15493. }
  15494. var actionId = ActionHelper.registerAction(actionName, action);
  15495. output.push('data-ember-action="' + actionId + '"');
  15496. return new EmberHandlebars.SafeString(output.join(" "));
  15497. });
  15498. })();
  15499. (function() {
  15500. var get = Ember.get, set = Ember.set;
  15501. /**
  15502. When used in a Handlebars template that is assigned to an `Ember.View` instance's
  15503. `layout` property Ember will render the layout template first, inserting the view's
  15504. own rendered output at the `{{ yield }}` location.
  15505. An empty `<body>` and the following application code:
  15506. AView = Ember.View.extend({
  15507. classNames: ['a-view-with-layout'],
  15508. layout: Ember.Handlebars.compile('<div class="wrapper">{{ yield }}</div>'),
  15509. template: Ember.Handlebars.compile('<span>I am wrapped</span>')
  15510. })
  15511. aView = AView.create()
  15512. aView.appendTo('body')
  15513. Will result in the following HTML output:
  15514. <body>
  15515. <div class='ember-view a-view-with-layout'>
  15516. <div class="wrapper">
  15517. <span>I am wrapped</span>
  15518. </div>
  15519. </div>
  15520. </body>
  15521. The yield helper cannot be used outside of a template assigned to an `Ember.View`'s `layout` property
  15522. and will throw an error if attempted.
  15523. BView = Ember.View.extend({
  15524. classNames: ['a-view-with-layout'],
  15525. template: Ember.Handlebars.compile('{{yield}}')
  15526. })
  15527. bView = BView.create()
  15528. bView.appendTo('body')
  15529. // throws
  15530. // Uncaught Error: assertion failed: You called yield in a template that was not a layout
  15531. @name Handlebars.helpers.yield
  15532. @param {Hash} options
  15533. @returns {String} HTML string
  15534. */
  15535. Ember.Handlebars.registerHelper('yield', function(options) {
  15536. var view = options.data.view, template;
  15537. while (view && !get(view, 'layout')) {
  15538. view = get(view, 'parentView');
  15539. }
  15540. Ember.assert("You called yield in a template that was not a layout", !!view);
  15541. template = get(view, 'template');
  15542. if (template) { template(this, options); }
  15543. });
  15544. })();
  15545. (function() {
  15546. /**
  15547. The `outlet` helper allows you to specify that the current
  15548. view's controller will fill in the view for a given area.
  15549. {{outlet}}
  15550. By default, when the the current controller's `view`
  15551. property changes, the outlet will replace its current
  15552. view with the new view.
  15553. controller.set('view', someView);
  15554. You can also specify a particular name, other than view:
  15555. {{outlet masterView}}
  15556. {{outlet detailView}}
  15557. Then, you can control several outlets from a single
  15558. controller:
  15559. controller.set('masterView', postsView);
  15560. controller.set('detailView', postView);
  15561. @name Handlebars.helpers.outlet
  15562. @param {String} property the property on the controller
  15563. that holds the view for this outlet
  15564. */
  15565. Ember.Handlebars.registerHelper('outlet', function(property, options) {
  15566. if (property && property.data && property.data.isRenderData) {
  15567. options = property;
  15568. property = 'view';
  15569. }
  15570. options.hash.currentViewBinding = "controller." + property;
  15571. return Ember.Handlebars.helpers.view.call(this, Ember.ContainerView, options);
  15572. });
  15573. })();
  15574. (function() {
  15575. // ==========================================================================
  15576. // Project: Ember Handlebars Views
  15577. // Copyright: ©2011 Strobe Inc. and contributors.
  15578. // License: Licensed under MIT license (see license.js)
  15579. // ==========================================================================
  15580. })();
  15581. (function() {
  15582. // ==========================================================================
  15583. // Project: Ember Handlebars Views
  15584. // Copyright: ©2011 Strobe Inc. and contributors.
  15585. // License: Licensed under MIT license (see license.js)
  15586. // ==========================================================================
  15587. })();
  15588. (function() {
  15589. // ==========================================================================
  15590. // Project: Ember Handlebars Views
  15591. // Copyright: ©2011 Strobe Inc. and contributors.
  15592. // License: Licensed under MIT license (see license.js)
  15593. // ==========================================================================
  15594. var set = Ember.set, get = Ember.get;
  15595. /**
  15596. @class
  15597. Creates an HTML input of type 'checkbox' with HTML related properties
  15598. applied directly to the input.
  15599. {{view Ember.Checkbox classNames="applicaton-specific-checkbox"}}
  15600. <input id="ember1" class="ember-view ember-checkbox applicaton-specific-checkbox" type="checkbox">
  15601. You can add a `label` tag yourself in the template where the Ember.Checkbox is being used.
  15602. <label>
  15603. Some Title
  15604. {{view Ember.Checkbox classNames="applicaton-specific-checkbox"}}
  15605. </label>
  15606. The `checked` attribute of an Ember.Checkbox object should always be set
  15607. through the Ember object or by interacting with its rendered element representation
  15608. via the mouse, keyboard, or touch. Updating the value of the checkbox via jQuery will
  15609. result in the checked value of the object and its element losing synchronization.
  15610. ## Layout and LayoutName properties
  15611. Because HTML `input` elements are self closing `layout` and `layoutName` properties will
  15612. not be applied. See `Ember.View`'s layout section for more information.
  15613. @extends Ember.View
  15614. */
  15615. Ember.Checkbox = Ember.View.extend({
  15616. classNames: ['ember-checkbox'],
  15617. tagName: 'input',
  15618. attributeBindings: ['type', 'checked', 'disabled', 'tabindex'],
  15619. type: "checkbox",
  15620. checked: false,
  15621. disabled: false,
  15622. init: function() {
  15623. this._super();
  15624. this.on("change", this, this._updateElementValue);
  15625. },
  15626. /**
  15627. @private
  15628. */
  15629. _updateElementValue: function() {
  15630. set(this, 'checked', this.$().prop('checked'));
  15631. }
  15632. });
  15633. })();
  15634. (function() {
  15635. // ==========================================================================
  15636. // Project: Ember Handlebars Views
  15637. // Copyright: ©2011 Strobe Inc. and contributors.
  15638. // License: Licensed under MIT license (see license.js)
  15639. // ==========================================================================
  15640. var get = Ember.get, set = Ember.set;
  15641. /** @class */
  15642. Ember.TextSupport = Ember.Mixin.create(
  15643. /** @scope Ember.TextSupport.prototype */ {
  15644. value: "",
  15645. attributeBindings: ['placeholder', 'disabled', 'maxlength', 'tabindex'],
  15646. placeholder: null,
  15647. disabled: false,
  15648. maxlength: null,
  15649. insertNewline: Ember.K,
  15650. cancel: Ember.K,
  15651. /** @private */
  15652. init: function() {
  15653. this._super();
  15654. this.on("focusOut", this, this._elementValueDidChange);
  15655. this.on("change", this, this._elementValueDidChange);
  15656. this.on("keyUp", this, this.interpretKeyEvents);
  15657. },
  15658. /**
  15659. @private
  15660. */
  15661. interpretKeyEvents: function(event) {
  15662. var map = Ember.TextSupport.KEY_EVENTS;
  15663. var method = map[event.keyCode];
  15664. this._elementValueDidChange();
  15665. if (method) { return this[method](event); }
  15666. },
  15667. _elementValueDidChange: function() {
  15668. set(this, 'value', this.$().val());
  15669. }
  15670. });
  15671. Ember.TextSupport.KEY_EVENTS = {
  15672. 13: 'insertNewline',
  15673. 27: 'cancel'
  15674. };
  15675. })();
  15676. (function() {
  15677. // ==========================================================================
  15678. // Project: Ember Handlebars Views
  15679. // Copyright: ©2011 Strobe Inc. and contributors.
  15680. // License: Licensed under MIT license (see license.js)
  15681. // ==========================================================================
  15682. var get = Ember.get, set = Ember.set;
  15683. /**
  15684. @class
  15685. The `Ember.TextField` view class renders a text
  15686. [input](https://developer.mozilla.org/en/HTML/Element/Input) element. It
  15687. allows for binding Ember properties to the text field contents (`value`),
  15688. live-updating as the user inputs text.
  15689. Example:
  15690. {{view Ember.TextField valueBinding="firstName"}}
  15691. ## Layout and LayoutName properties
  15692. Because HTML `input` elements are self closing `layout` and `layoutName` properties will
  15693. not be applied. See `Ember.View`'s layout section for more information.
  15694. @extends Ember.View
  15695. @extends Ember.TextSupport
  15696. */
  15697. Ember.TextField = Ember.View.extend(Ember.TextSupport,
  15698. /** @scope Ember.TextField.prototype */ {
  15699. classNames: ['ember-text-field'],
  15700. tagName: "input",
  15701. attributeBindings: ['type', 'value', 'size'],
  15702. /**
  15703. The value attribute of the input element. As the user inputs text, this
  15704. property is updated live.
  15705. @type String
  15706. @default ""
  15707. */
  15708. value: "",
  15709. /**
  15710. The type attribute of the input element.
  15711. @type String
  15712. @default "text"
  15713. */
  15714. type: "text",
  15715. /**
  15716. The size of the text field in characters.
  15717. @type String
  15718. @default null
  15719. */
  15720. size: null
  15721. });
  15722. })();
  15723. (function() {
  15724. // ==========================================================================
  15725. // Project: Ember Handlebars Views
  15726. // Copyright: ©2011 Strobe Inc. and contributors.
  15727. // License: Licensed under MIT license (see license.js)
  15728. // ==========================================================================
  15729. var get = Ember.get, set = Ember.set;
  15730. Ember.Button = Ember.View.extend(Ember.TargetActionSupport, {
  15731. classNames: ['ember-button'],
  15732. classNameBindings: ['isActive'],
  15733. tagName: 'button',
  15734. propagateEvents: false,
  15735. attributeBindings: ['type', 'disabled', 'href', 'tabindex'],
  15736. /** @private
  15737. Overrides TargetActionSupport's targetObject computed
  15738. property to use Handlebars-specific path resolution.
  15739. */
  15740. targetObject: Ember.computed(function() {
  15741. var target = get(this, 'target'),
  15742. root = get(this, 'context'),
  15743. data = get(this, 'templateData');
  15744. if (typeof target !== 'string') { return target; }
  15745. return Ember.Handlebars.getPath(root, target, { data: data });
  15746. }).property('target').cacheable(),
  15747. // Defaults to 'button' if tagName is 'input' or 'button'
  15748. type: Ember.computed(function(key, value) {
  15749. var tagName = this.get('tagName');
  15750. if (value !== undefined) { this._type = value; }
  15751. if (this._type !== undefined) { return this._type; }
  15752. if (tagName === 'input' || tagName === 'button') { return 'button'; }
  15753. }).property('tagName').cacheable(),
  15754. disabled: false,
  15755. // Allow 'a' tags to act like buttons
  15756. href: Ember.computed(function() {
  15757. return this.get('tagName') === 'a' ? '#' : null;
  15758. }).property('tagName').cacheable(),
  15759. mouseDown: function() {
  15760. if (!get(this, 'disabled')) {
  15761. set(this, 'isActive', true);
  15762. this._mouseDown = true;
  15763. this._mouseEntered = true;
  15764. }
  15765. return get(this, 'propagateEvents');
  15766. },
  15767. mouseLeave: function() {
  15768. if (this._mouseDown) {
  15769. set(this, 'isActive', false);
  15770. this._mouseEntered = false;
  15771. }
  15772. },
  15773. mouseEnter: function() {
  15774. if (this._mouseDown) {
  15775. set(this, 'isActive', true);
  15776. this._mouseEntered = true;
  15777. }
  15778. },
  15779. mouseUp: function(event) {
  15780. if (get(this, 'isActive')) {
  15781. // Actually invoke the button's target and action.
  15782. // This method comes from the Ember.TargetActionSupport mixin.
  15783. this.triggerAction();
  15784. set(this, 'isActive', false);
  15785. }
  15786. this._mouseDown = false;
  15787. this._mouseEntered = false;
  15788. return get(this, 'propagateEvents');
  15789. },
  15790. keyDown: function(event) {
  15791. // Handle space or enter
  15792. if (event.keyCode === 13 || event.keyCode === 32) {
  15793. this.mouseDown();
  15794. }
  15795. },
  15796. keyUp: function(event) {
  15797. // Handle space or enter
  15798. if (event.keyCode === 13 || event.keyCode === 32) {
  15799. this.mouseUp();
  15800. }
  15801. },
  15802. // TODO: Handle proper touch behavior. Including should make inactive when
  15803. // finger moves more than 20x outside of the edge of the button (vs mouse
  15804. // which goes inactive as soon as mouse goes out of edges.)
  15805. touchStart: function(touch) {
  15806. return this.mouseDown(touch);
  15807. },
  15808. touchEnd: function(touch) {
  15809. return this.mouseUp(touch);
  15810. },
  15811. init: function() {
  15812. Ember.deprecate("Ember.Button is deprecated and will be removed from future releases. Consider using the `{{action}}` helper.");
  15813. this._super();
  15814. }
  15815. });
  15816. })();
  15817. (function() {
  15818. // ==========================================================================
  15819. // Project: Ember Handlebars Views
  15820. // Copyright: ©2011 Strobe Inc. and contributors.
  15821. // License: Licensed under MIT license (see license.js)
  15822. // ==========================================================================
  15823. var get = Ember.get, set = Ember.set;
  15824. /**
  15825. @class
  15826. The `Ember.TextArea` view class renders a
  15827. [textarea](https://developer.mozilla.org/en/HTML/Element/textarea) element.
  15828. It allows for binding Ember properties to the text area contents (`value`),
  15829. live-updating as the user inputs text.
  15830. ## Layout and LayoutName properties
  15831. Because HTML `textarea` elements do not contain inner HTML the `layout` and `layoutName`
  15832. properties will not be applied. See `Ember.View`'s layout section for more information.
  15833. @extends Ember.View
  15834. @extends Ember.TextSupport
  15835. */
  15836. Ember.TextArea = Ember.View.extend(Ember.TextSupport,
  15837. /** @scope Ember.TextArea.prototype */ {
  15838. classNames: ['ember-text-area'],
  15839. tagName: "textarea",
  15840. attributeBindings: ['rows', 'cols'],
  15841. rows: null,
  15842. cols: null,
  15843. _updateElementValue: Ember.observer(function() {
  15844. // We do this check so cursor position doesn't get affected in IE
  15845. var value = get(this, 'value'),
  15846. $el = this.$();
  15847. if ($el && value !== $el.val()) {
  15848. $el.val(value);
  15849. }
  15850. }, 'value'),
  15851. /** @private */
  15852. init: function() {
  15853. this._super();
  15854. this.on("didInsertElement", this, this._updateElementValue);
  15855. }
  15856. });
  15857. })();
  15858. (function() {
  15859. Ember.TabContainerView = Ember.View.extend({
  15860. init: function() {
  15861. Ember.deprecate("Ember.TabContainerView is deprecated and will be removed from future releases.");
  15862. this._super();
  15863. }
  15864. });
  15865. })();
  15866. (function() {
  15867. var get = Ember.get;
  15868. Ember.TabPaneView = Ember.View.extend({
  15869. tabsContainer: Ember.computed(function() {
  15870. return this.nearestInstanceOf(Ember.TabContainerView);
  15871. }).property().volatile(),
  15872. isVisible: Ember.computed(function() {
  15873. return get(this, 'viewName') === get(this, 'tabsContainer.currentView');
  15874. }).property('tabsContainer.currentView').volatile(),
  15875. init: function() {
  15876. Ember.deprecate("Ember.TabPaneView is deprecated and will be removed from future releases.");
  15877. this._super();
  15878. }
  15879. });
  15880. })();
  15881. (function() {
  15882. var get = Ember.get, setPath = Ember.setPath;
  15883. Ember.TabView = Ember.View.extend({
  15884. tabsContainer: Ember.computed(function() {
  15885. return this.nearestInstanceOf(Ember.TabContainerView);
  15886. }).property().volatile(),
  15887. mouseUp: function() {
  15888. setPath(this, 'tabsContainer.currentView', get(this, 'value'));
  15889. },
  15890. init: function() {
  15891. Ember.deprecate("Ember.TabView is deprecated and will be removed from future releases.");
  15892. this._super();
  15893. }
  15894. });
  15895. })();
  15896. (function() {
  15897. })();
  15898. (function() {
  15899. /*jshint eqeqeq:false */
  15900. var set = Ember.set, get = Ember.get;
  15901. var indexOf = Ember.EnumerableUtils.indexOf, indexesOf = Ember.EnumerableUtils.indexesOf;
  15902. /**
  15903. @class
  15904. The Ember.Select view class renders a
  15905. [select](https://developer.mozilla.org/en/HTML/Element/select) HTML element,
  15906. allowing the user to choose from a list of options. The selected option(s)
  15907. are updated live in the `selection` property, while the corresponding value
  15908. is updated in the `value` property.
  15909. ### Using Strings
  15910. The simplest version of an Ember.Select takes an array of strings for the options
  15911. of a select box and a valueBinding to set the value.
  15912. Example:
  15913. App.controller = Ember.Object.create({
  15914. selected: null,
  15915. content: [
  15916. "Yehuda",
  15917. "Tom"
  15918. ]
  15919. })
  15920. {{view Ember.Select
  15921. contentBinding="App.controller.content"
  15922. valueBinding="App.controller.selected"
  15923. }}
  15924. Would result in the following HTML:
  15925. <select class="ember-select">
  15926. <option value="Yehuda">Yehuda</option>
  15927. <option value="Tom">Tom</option>
  15928. </select>
  15929. Selecting Yehuda from the select box will set `App.controller.selected` to "Yehuda"
  15930. ### Using Objects
  15931. An Ember.Select can also take an array of JS or Ember objects.
  15932. When using objects you need to supply optionLabelPath and optionValuePath parameters
  15933. which will be used to get the label and value for each of the options.
  15934. Usually you will bind to either the selection or the value attribute of the select.
  15935. Use selectionBinding if you would like to set the whole object as a property on the target.
  15936. Use valueBinding if you would like to set just the value.
  15937. Example using selectionBinding:
  15938. App.controller = Ember.Object.create({
  15939. selectedPerson: null,
  15940. selectedPersonId: null,
  15941. content: [
  15942. Ember.Object.create({firstName: "Yehuda", id: 1}),
  15943. Ember.Object.create({firstName: "Tom", id: 2})
  15944. ]
  15945. })
  15946. {{view Ember.Select
  15947. contentBinding="App.controller.content"
  15948. optionLabelPath="content.firstName"
  15949. optionValuePath="content.id"
  15950. selectionBinding="App.controller.selectedPerson"
  15951. prompt="Please Select"}}
  15952. <select class="ember-select">
  15953. <option value>Please Select</option>
  15954. <option value="1">Yehuda</option>
  15955. <option value="2">Tom</option>
  15956. </select>
  15957. Selecting Yehuda here will set `App.controller.selectedPerson` to
  15958. the Yehuda object.
  15959. Example using valueBinding:
  15960. {{view Ember.Select
  15961. contentBinding="App.controller.content"
  15962. optionLabelPath="content.firstName"
  15963. optionValuePath="content.id"
  15964. valueBinding="App.controller.selectedPersonId"
  15965. prompt="Please Select"}}
  15966. Selecting Yehuda in this case will set `App.controller.selectedPersonId` to 1.
  15967. @extends Ember.View
  15968. */
  15969. Ember.Select = Ember.View.extend(
  15970. /** @scope Ember.Select.prototype */ {
  15971. tagName: 'select',
  15972. classNames: ['ember-select'],
  15973. defaultTemplate: Ember.Handlebars.compile('{{#if view.prompt}}<option value>{{view.prompt}}</option>{{/if}}{{#each view.content}}{{view Ember.SelectOption contentBinding="this"}}{{/each}}'),
  15974. attributeBindings: ['multiple', 'tabindex'],
  15975. /**
  15976. The `multiple` attribute of the select element. Indicates whether multiple
  15977. options can be selected.
  15978. @type Boolean
  15979. @default false
  15980. */
  15981. multiple: false,
  15982. /**
  15983. The list of options.
  15984. If `optionLabelPath` and `optionValuePath` are not overridden, this should
  15985. be a list of strings, which will serve simultaneously as labels and values.
  15986. Otherwise, this should be a list of objects. For instance:
  15987. content: Ember.A([
  15988. { id: 1, firstName: 'Yehuda' },
  15989. { id: 2, firstName: 'Tom' }
  15990. ]),
  15991. optionLabelPath: 'content.firstName',
  15992. optionValuePath: 'content.id'
  15993. @type Array
  15994. @default null
  15995. */
  15996. content: null,
  15997. /**
  15998. When `multiple` is false, the element of `content` that is currently
  15999. selected, if any.
  16000. When `multiple` is true, an array of such elements.
  16001. @type Object or Array
  16002. @default null
  16003. */
  16004. selection: null,
  16005. /**
  16006. In single selection mode (when `multiple` is false), value can be used to get
  16007. the current selection's value or set the selection by it's value.
  16008. It is not currently supported in multiple selection mode.
  16009. @type String
  16010. @default null
  16011. */
  16012. value: Ember.computed(function(key, value) {
  16013. if (arguments.length === 2) { return value; }
  16014. var valuePath = get(this, 'optionValuePath').replace(/^content\.?/, '');
  16015. return valuePath ? get(this, 'selection.' + valuePath) : get(this, 'selection');
  16016. }).property('selection').cacheable(),
  16017. /**
  16018. If given, a top-most dummy option will be rendered to serve as a user
  16019. prompt.
  16020. @type String
  16021. @default null
  16022. */
  16023. prompt: null,
  16024. /**
  16025. The path of the option labels. See `content`.
  16026. @type String
  16027. @default 'content'
  16028. */
  16029. optionLabelPath: 'content',
  16030. /**
  16031. The path of the option values. See `content`.
  16032. @type String
  16033. @default 'content'
  16034. */
  16035. optionValuePath: 'content',
  16036. _change: function() {
  16037. if (get(this, 'multiple')) {
  16038. this._changeMultiple();
  16039. } else {
  16040. this._changeSingle();
  16041. }
  16042. },
  16043. selectionDidChange: Ember.observer(function() {
  16044. var selection = get(this, 'selection'),
  16045. isArray = Ember.isArray(selection);
  16046. if (get(this, 'multiple')) {
  16047. if (!isArray) {
  16048. set(this, 'selection', Ember.A([selection]));
  16049. return;
  16050. }
  16051. this._selectionDidChangeMultiple();
  16052. } else {
  16053. this._selectionDidChangeSingle();
  16054. }
  16055. }, 'selection'),
  16056. valueDidChange: Ember.observer(function() {
  16057. var content = get(this, 'content'),
  16058. value = get(this, 'value'),
  16059. valuePath = get(this, 'optionValuePath').replace(/^content\.?/, ''),
  16060. selectedValue = (valuePath ? get(this, 'selection.' + valuePath) : get(this, 'selection')),
  16061. selection;
  16062. if (value !== selectedValue) {
  16063. selection = content.find(function(obj) {
  16064. return value === (valuePath ? get(obj, valuePath) : obj);
  16065. });
  16066. this.set('selection', selection);
  16067. }
  16068. }, 'value'),
  16069. _triggerChange: function() {
  16070. var selection = get(this, 'selection');
  16071. if (selection) { this.selectionDidChange(); }
  16072. this._change();
  16073. },
  16074. _changeSingle: function() {
  16075. var selectedIndex = this.$()[0].selectedIndex,
  16076. content = get(this, 'content'),
  16077. prompt = get(this, 'prompt');
  16078. if (!content) { return; }
  16079. if (prompt && selectedIndex === 0) { set(this, 'selection', null); return; }
  16080. if (prompt) { selectedIndex -= 1; }
  16081. set(this, 'selection', content.objectAt(selectedIndex));
  16082. },
  16083. _changeMultiple: function() {
  16084. var options = this.$('option:selected'),
  16085. prompt = get(this, 'prompt'),
  16086. offset = prompt ? 1 : 0,
  16087. content = get(this, 'content');
  16088. if (!content){ return; }
  16089. if (options) {
  16090. var selectedIndexes = options.map(function(){
  16091. return this.index - offset;
  16092. }).toArray();
  16093. set(this, 'selection', content.objectsAt(selectedIndexes));
  16094. }
  16095. },
  16096. _selectionDidChangeSingle: function() {
  16097. var el = this.get('element');
  16098. if (!el) { return; }
  16099. var content = get(this, 'content'),
  16100. selection = get(this, 'selection'),
  16101. selectionIndex = content ? indexOf(content, selection) : -1,
  16102. prompt = get(this, 'prompt');
  16103. if (prompt) { selectionIndex += 1; }
  16104. if (el) { el.selectedIndex = selectionIndex; }
  16105. },
  16106. _selectionDidChangeMultiple: function() {
  16107. var content = get(this, 'content'),
  16108. selection = get(this, 'selection'),
  16109. selectedIndexes = content ? indexesOf(content, selection) : [-1],
  16110. prompt = get(this, 'prompt'),
  16111. offset = prompt ? 1 : 0,
  16112. options = this.$('option'),
  16113. adjusted;
  16114. if (options) {
  16115. options.each(function() {
  16116. adjusted = this.index > -1 ? this.index + offset : -1;
  16117. this.selected = indexOf(selectedIndexes, adjusted) > -1;
  16118. });
  16119. }
  16120. },
  16121. init: function() {
  16122. this._super();
  16123. this.on("didInsertElement", this, this._triggerChange);
  16124. this.on("change", this, this._change);
  16125. }
  16126. });
  16127. Ember.SelectOption = Ember.View.extend({
  16128. tagName: 'option',
  16129. attributeBindings: ['value', 'selected'],
  16130. defaultTemplate: function(context, options) {
  16131. options = { data: options.data, hash: {} };
  16132. Ember.Handlebars.helpers.bind.call(context, "view.label", options);
  16133. },
  16134. init: function() {
  16135. this.labelPathDidChange();
  16136. this.valuePathDidChange();
  16137. this._super();
  16138. },
  16139. selected: Ember.computed(function() {
  16140. var content = get(this, 'content'),
  16141. selection = get(this, 'parentView.selection');
  16142. if (get(this, 'parentView.multiple')) {
  16143. return selection && indexOf(selection, content) > -1;
  16144. } else {
  16145. // Primitives get passed through bindings as objects... since
  16146. // `new Number(4) !== 4`, we use `==` below
  16147. return content == selection;
  16148. }
  16149. }).property('content', 'parentView.selection').volatile(),
  16150. labelPathDidChange: Ember.observer(function() {
  16151. var labelPath = get(this, 'parentView.optionLabelPath');
  16152. if (!labelPath) { return; }
  16153. Ember.defineProperty(this, 'label', Ember.computed(function() {
  16154. return get(this, labelPath);
  16155. }).property(labelPath).cacheable());
  16156. }, 'parentView.optionLabelPath'),
  16157. valuePathDidChange: Ember.observer(function() {
  16158. var valuePath = get(this, 'parentView.optionValuePath');
  16159. if (!valuePath) { return; }
  16160. Ember.defineProperty(this, 'value', Ember.computed(function() {
  16161. return get(this, valuePath);
  16162. }).property(valuePath).cacheable());
  16163. }, 'parentView.optionValuePath')
  16164. });
  16165. })();
  16166. (function() {
  16167. // ==========================================================================
  16168. // Project: Ember Handlebars Views
  16169. // Copyright: ©2011 Strobe Inc. and contributors.
  16170. // License: Licensed under MIT license (see license.js)
  16171. // ==========================================================================
  16172. })();
  16173. (function() {
  16174. // ==========================================================================
  16175. // Project: Ember Handlebars Views
  16176. // Copyright: ©2011 Strobe Inc. and contributors.
  16177. // License: Licensed under MIT license (see license.js)
  16178. // ==========================================================================
  16179. /*globals Handlebars */
  16180. // Find templates stored in the head tag as script tags and make them available
  16181. // to Ember.CoreView in the global Ember.TEMPLATES object. This will be run as as
  16182. // jQuery DOM-ready callback.
  16183. //
  16184. // Script tags with "text/x-handlebars" will be compiled
  16185. // with Ember's Handlebars and are suitable for use as a view's template.
  16186. // Those with type="text/x-raw-handlebars" will be compiled with regular
  16187. // Handlebars and are suitable for use in views' computed properties.
  16188. Ember.Handlebars.bootstrap = function(ctx) {
  16189. var selectors = 'script[type="text/x-handlebars"], script[type="text/x-raw-handlebars"]';
  16190. Ember.$(selectors, ctx)
  16191. .each(function() {
  16192. // Get a reference to the script tag
  16193. var script = Ember.$(this),
  16194. type = script.attr('type');
  16195. var compile = (script.attr('type') === 'text/x-raw-handlebars') ?
  16196. Ember.$.proxy(Handlebars.compile, Handlebars) :
  16197. Ember.$.proxy(Ember.Handlebars.compile, Ember.Handlebars),
  16198. // Get the name of the script, used by Ember.View's templateName property.
  16199. // First look for data-template-name attribute, then fall back to its
  16200. // id if no name is found.
  16201. templateName = script.attr('data-template-name') || script.attr('id'),
  16202. template = compile(script.html()),
  16203. view, viewPath, elementId, options;
  16204. if (templateName) {
  16205. // For templates which have a name, we save them and then remove them from the DOM
  16206. Ember.TEMPLATES[templateName] = template;
  16207. // Remove script tag from DOM
  16208. script.remove();
  16209. } else {
  16210. if (script.parents('head').length !== 0) {
  16211. // don't allow inline templates in the head
  16212. throw new Ember.Error("Template found in <head> without a name specified. " +
  16213. "Please provide a data-template-name attribute.\n" +
  16214. script.html());
  16215. }
  16216. // For templates which will be evaluated inline in the HTML document, instantiates a new
  16217. // view, and replaces the script tag holding the template with the new
  16218. // view's DOM representation.
  16219. //
  16220. // Users can optionally specify a custom view subclass to use by setting the
  16221. // data-view attribute of the script tag.
  16222. viewPath = script.attr('data-view');
  16223. view = viewPath ? Ember.get(viewPath) : Ember.View;
  16224. // Get the id of the script, used by Ember.View's elementId property,
  16225. // Look for data-element-id attribute.
  16226. elementId = script.attr('data-element-id');
  16227. options = { template: template };
  16228. if (elementId) { options.elementId = elementId; }
  16229. view = view.create(options);
  16230. view._insertElementLater(function() {
  16231. script.replaceWith(this.$());
  16232. // Avoid memory leak in IE
  16233. script = null;
  16234. });
  16235. }
  16236. });
  16237. };
  16238. /** @private */
  16239. function bootstrap() {
  16240. Ember.Handlebars.bootstrap( Ember.$(document) );
  16241. }
  16242. /*
  16243. We tie this to application.load to ensure that we've at least
  16244. attempted to bootstrap at the point that the application is loaded.
  16245. We also tie this to document ready since we're guaranteed that all
  16246. the inline templates are present at this point.
  16247. There's no harm to running this twice, since we remove the templates
  16248. from the DOM after processing.
  16249. */
  16250. Ember.$(document).ready(bootstrap);
  16251. Ember.onLoad('application', bootstrap);
  16252. })();
  16253. (function() {
  16254. // ==========================================================================
  16255. // Project: Ember Handlebars Views
  16256. // Copyright: ©2011 Strobe Inc. and contributors.
  16257. // License: Licensed under MIT license (see license.js)
  16258. // ==========================================================================
  16259. })();
  16260. // Version: v1.0.pre
  16261. // Last commit: 7955b85 (2012-08-03 14:50:17 -0700)
  16262. (function() {
  16263. // ==========================================================================
  16264. // Project: Ember
  16265. // Copyright: ©2011 Strobe Inc. and contributors.
  16266. // License: Licensed under MIT license (see license.js)
  16267. // ==========================================================================
  16268. })();