knockout.js 283 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934
  1. /*!
  2. * Knockout JavaScript library v3.4.2
  3. * (c) The Knockout.js team - http://knockoutjs.com/
  4. * License: MIT (http://www.opensource.org/licenses/mit-license.php)
  5. */
  6. (function(){
  7. var DEBUG=true;
  8. (function(undefined){
  9. // (0, eval)('this') is a robust way of getting a reference to the global object
  10. // For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023
  11. var window = this || (0, eval)('this'),
  12. document = window['document'],
  13. navigator = window['navigator'],
  14. jQueryInstance = window["jQuery"],
  15. JSON = window["JSON"];
  16. (function(factory) {
  17. // Support three module loading scenarios
  18. if (typeof define === 'function' && define['amd']) {
  19. // [1] AMD anonymous module
  20. define(['exports', 'require'], factory);
  21. } else if (typeof exports === 'object' && typeof module === 'object') {
  22. // [2] CommonJS/Node.js
  23. factory(module['exports'] || exports); // module.exports is for Node.js
  24. } else {
  25. // [3] No module loader (plain <script> tag) - put directly in global namespace
  26. factory(window['ko'] = {});
  27. }
  28. }(function(koExports, amdRequire){
  29. // Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
  30. // In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
  31. var ko = typeof koExports !== 'undefined' ? koExports : {};
  32. // Google Closure Compiler helpers (used only to make the minified file smaller)
  33. ko.exportSymbol = function(koPath, object) {
  34. var tokens = koPath.split(".");
  35. // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
  36. // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
  37. var target = ko;
  38. for (var i = 0; i < tokens.length - 1; i++)
  39. target = target[tokens[i]];
  40. target[tokens[tokens.length - 1]] = object;
  41. };
  42. ko.exportProperty = function(owner, publicName, object) {
  43. owner[publicName] = object;
  44. };
  45. ko.version = "3.4.2";
  46. ko.exportSymbol('version', ko.version);
  47. // For any options that may affect various areas of Knockout and aren't directly associated with data binding.
  48. ko.options = {
  49. 'deferUpdates': false,
  50. 'useOnlyNativeEvents': false
  51. };
  52. //ko.exportSymbol('options', ko.options); // 'options' isn't minified
  53. ko.utils = (function () {
  54. function objectForEach(obj, action) {
  55. for (var prop in obj) {
  56. if (obj.hasOwnProperty(prop)) {
  57. action(prop, obj[prop]);
  58. }
  59. }
  60. }
  61. function extend(target, source) {
  62. if (source) {
  63. for(var prop in source) {
  64. if(source.hasOwnProperty(prop)) {
  65. target[prop] = source[prop];
  66. }
  67. }
  68. }
  69. return target;
  70. }
  71. function setPrototypeOf(obj, proto) {
  72. obj.__proto__ = proto;
  73. return obj;
  74. }
  75. var canSetPrototype = ({ __proto__: [] } instanceof Array);
  76. var canUseSymbols = !DEBUG && typeof Symbol === 'function';
  77. // Represent the known event types in a compact way, then at runtime transform it into a hash with event name as key (for fast lookup)
  78. var knownEvents = {}, knownEventTypesByEventName = {};
  79. var keyEventTypeName = (navigator && /Firefox\/2/i.test(navigator.userAgent)) ? 'KeyboardEvent' : 'UIEvents';
  80. knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
  81. knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
  82. objectForEach(knownEvents, function(eventType, knownEventsForType) {
  83. if (knownEventsForType.length) {
  84. for (var i = 0, j = knownEventsForType.length; i < j; i++)
  85. knownEventTypesByEventName[knownEventsForType[i]] = eventType;
  86. }
  87. });
  88. var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
  89. // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
  90. // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
  91. // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
  92. // If there is a future need to detect specific versions of IE10+, we will amend this.
  93. var ieVersion = document && (function() {
  94. var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
  95. // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
  96. while (
  97. div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
  98. iElems[0]
  99. ) {}
  100. return version > 4 ? version : undefined;
  101. }());
  102. var isIe6 = ieVersion === 6,
  103. isIe7 = ieVersion === 7;
  104. function isClickOnCheckableElement(element, eventType) {
  105. if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
  106. if (eventType.toLowerCase() != "click") return false;
  107. var inputType = element.type;
  108. return (inputType == "checkbox") || (inputType == "radio");
  109. }
  110. // For details on the pattern for changing node classes
  111. // see: https://github.com/knockout/knockout/issues/1597
  112. var cssClassNameRegex = /\S+/g;
  113. function toggleDomNodeCssClass(node, classNames, shouldHaveClass) {
  114. var addOrRemoveFn;
  115. if (classNames) {
  116. if (typeof node.classList === 'object') {
  117. addOrRemoveFn = node.classList[shouldHaveClass ? 'add' : 'remove'];
  118. ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
  119. addOrRemoveFn.call(node.classList, className);
  120. });
  121. } else if (typeof node.className['baseVal'] === 'string') {
  122. // SVG tag .classNames is an SVGAnimatedString instance
  123. toggleObjectClassPropertyString(node.className, 'baseVal', classNames, shouldHaveClass);
  124. } else {
  125. // node.className ought to be a string.
  126. toggleObjectClassPropertyString(node, 'className', classNames, shouldHaveClass);
  127. }
  128. }
  129. }
  130. function toggleObjectClassPropertyString(obj, prop, classNames, shouldHaveClass) {
  131. // obj/prop is either a node/'className' or a SVGAnimatedString/'baseVal'.
  132. var currentClassNames = obj[prop].match(cssClassNameRegex) || [];
  133. ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
  134. ko.utils.addOrRemoveItem(currentClassNames, className, shouldHaveClass);
  135. });
  136. obj[prop] = currentClassNames.join(" ");
  137. }
  138. return {
  139. fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
  140. arrayForEach: function (array, action) {
  141. for (var i = 0, j = array.length; i < j; i++)
  142. action(array[i], i);
  143. },
  144. arrayIndexOf: function (array, item) {
  145. if (typeof Array.prototype.indexOf == "function")
  146. return Array.prototype.indexOf.call(array, item);
  147. for (var i = 0, j = array.length; i < j; i++)
  148. if (array[i] === item)
  149. return i;
  150. return -1;
  151. },
  152. arrayFirst: function (array, predicate, predicateOwner) {
  153. for (var i = 0, j = array.length; i < j; i++)
  154. if (predicate.call(predicateOwner, array[i], i))
  155. return array[i];
  156. return null;
  157. },
  158. arrayRemoveItem: function (array, itemToRemove) {
  159. var index = ko.utils.arrayIndexOf(array, itemToRemove);
  160. if (index > 0) {
  161. array.splice(index, 1);
  162. }
  163. else if (index === 0) {
  164. array.shift();
  165. }
  166. },
  167. arrayGetDistinctValues: function (array) {
  168. array = array || [];
  169. var result = [];
  170. for (var i = 0, j = array.length; i < j; i++) {
  171. if (ko.utils.arrayIndexOf(result, array[i]) < 0)
  172. result.push(array[i]);
  173. }
  174. return result;
  175. },
  176. arrayMap: function (array, mapping) {
  177. array = array || [];
  178. var result = [];
  179. for (var i = 0, j = array.length; i < j; i++)
  180. result.push(mapping(array[i], i));
  181. return result;
  182. },
  183. arrayFilter: function (array, predicate) {
  184. array = array || [];
  185. var result = [];
  186. for (var i = 0, j = array.length; i < j; i++)
  187. if (predicate(array[i], i))
  188. result.push(array[i]);
  189. return result;
  190. },
  191. arrayPushAll: function (array, valuesToPush) {
  192. if (valuesToPush instanceof Array)
  193. array.push.apply(array, valuesToPush);
  194. else
  195. for (var i = 0, j = valuesToPush.length; i < j; i++)
  196. array.push(valuesToPush[i]);
  197. return array;
  198. },
  199. addOrRemoveItem: function(array, value, included) {
  200. var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.peekObservable(array), value);
  201. if (existingEntryIndex < 0) {
  202. if (included)
  203. array.push(value);
  204. } else {
  205. if (!included)
  206. array.splice(existingEntryIndex, 1);
  207. }
  208. },
  209. canSetPrototype: canSetPrototype,
  210. extend: extend,
  211. setPrototypeOf: setPrototypeOf,
  212. setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : extend,
  213. objectForEach: objectForEach,
  214. objectMap: function(source, mapping) {
  215. if (!source)
  216. return source;
  217. var target = {};
  218. for (var prop in source) {
  219. if (source.hasOwnProperty(prop)) {
  220. target[prop] = mapping(source[prop], prop, source);
  221. }
  222. }
  223. return target;
  224. },
  225. emptyDomNode: function (domNode) {
  226. while (domNode.firstChild) {
  227. ko.removeNode(domNode.firstChild);
  228. }
  229. },
  230. moveCleanedNodesToContainerElement: function(nodes) {
  231. // Ensure it's a real array, as we're about to reparent the nodes and
  232. // we don't want the underlying collection to change while we're doing that.
  233. var nodesArray = ko.utils.makeArray(nodes);
  234. var templateDocument = (nodesArray[0] && nodesArray[0].ownerDocument) || document;
  235. var container = templateDocument.createElement('div');
  236. for (var i = 0, j = nodesArray.length; i < j; i++) {
  237. container.appendChild(ko.cleanNode(nodesArray[i]));
  238. }
  239. return container;
  240. },
  241. cloneNodes: function (nodesArray, shouldCleanNodes) {
  242. for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
  243. var clonedNode = nodesArray[i].cloneNode(true);
  244. newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
  245. }
  246. return newNodesArray;
  247. },
  248. setDomNodeChildren: function (domNode, childNodes) {
  249. ko.utils.emptyDomNode(domNode);
  250. if (childNodes) {
  251. for (var i = 0, j = childNodes.length; i < j; i++)
  252. domNode.appendChild(childNodes[i]);
  253. }
  254. },
  255. replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
  256. var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
  257. if (nodesToReplaceArray.length > 0) {
  258. var insertionPoint = nodesToReplaceArray[0];
  259. var parent = insertionPoint.parentNode;
  260. for (var i = 0, j = newNodesArray.length; i < j; i++)
  261. parent.insertBefore(newNodesArray[i], insertionPoint);
  262. for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
  263. ko.removeNode(nodesToReplaceArray[i]);
  264. }
  265. }
  266. },
  267. fixUpContinuousNodeArray: function(continuousNodeArray, parentNode) {
  268. // Before acting on a set of nodes that were previously outputted by a template function, we have to reconcile
  269. // them against what is in the DOM right now. It may be that some of the nodes have already been removed, or that
  270. // new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
  271. // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
  272. // So, this function translates the old "map" output array into its best guess of the set of current DOM nodes.
  273. //
  274. // Rules:
  275. // [A] Any leading nodes that have been removed should be ignored
  276. // These most likely correspond to memoization nodes that were already removed during binding
  277. // See https://github.com/knockout/knockout/pull/440
  278. // [B] Any trailing nodes that have been remove should be ignored
  279. // This prevents the code here from adding unrelated nodes to the array while processing rule [C]
  280. // See https://github.com/knockout/knockout/pull/1903
  281. // [C] We want to output a continuous series of nodes. So, ignore any nodes that have already been removed,
  282. // and include any nodes that have been inserted among the previous collection
  283. if (continuousNodeArray.length) {
  284. // The parent node can be a virtual element; so get the real parent node
  285. parentNode = (parentNode.nodeType === 8 && parentNode.parentNode) || parentNode;
  286. // Rule [A]
  287. while (continuousNodeArray.length && continuousNodeArray[0].parentNode !== parentNode)
  288. continuousNodeArray.splice(0, 1);
  289. // Rule [B]
  290. while (continuousNodeArray.length > 1 && continuousNodeArray[continuousNodeArray.length - 1].parentNode !== parentNode)
  291. continuousNodeArray.length--;
  292. // Rule [C]
  293. if (continuousNodeArray.length > 1) {
  294. var current = continuousNodeArray[0], last = continuousNodeArray[continuousNodeArray.length - 1];
  295. // Replace with the actual new continuous node set
  296. continuousNodeArray.length = 0;
  297. while (current !== last) {
  298. continuousNodeArray.push(current);
  299. current = current.nextSibling;
  300. }
  301. continuousNodeArray.push(last);
  302. }
  303. }
  304. return continuousNodeArray;
  305. },
  306. setOptionNodeSelectionState: function (optionNode, isSelected) {
  307. // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
  308. if (ieVersion < 7)
  309. optionNode.setAttribute("selected", isSelected);
  310. else
  311. optionNode.selected = isSelected;
  312. },
  313. stringTrim: function (string) {
  314. return string === null || string === undefined ? '' :
  315. string.trim ?
  316. string.trim() :
  317. string.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
  318. },
  319. stringStartsWith: function (string, startsWith) {
  320. string = string || "";
  321. if (startsWith.length > string.length)
  322. return false;
  323. return string.substring(0, startsWith.length) === startsWith;
  324. },
  325. domNodeIsContainedBy: function (node, containedByNode) {
  326. if (node === containedByNode)
  327. return true;
  328. if (node.nodeType === 11)
  329. return false; // Fixes issue #1162 - can't use node.contains for document fragments on IE8
  330. if (containedByNode.contains)
  331. return containedByNode.contains(node.nodeType === 3 ? node.parentNode : node);
  332. if (containedByNode.compareDocumentPosition)
  333. return (containedByNode.compareDocumentPosition(node) & 16) == 16;
  334. while (node && node != containedByNode) {
  335. node = node.parentNode;
  336. }
  337. return !!node;
  338. },
  339. domNodeIsAttachedToDocument: function (node) {
  340. return ko.utils.domNodeIsContainedBy(node, node.ownerDocument.documentElement);
  341. },
  342. anyDomNodeIsAttachedToDocument: function(nodes) {
  343. return !!ko.utils.arrayFirst(nodes, ko.utils.domNodeIsAttachedToDocument);
  344. },
  345. tagNameLower: function(element) {
  346. // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
  347. // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
  348. // we don't need to do the .toLowerCase() as it will always be lower case anyway.
  349. return element && element.tagName && element.tagName.toLowerCase();
  350. },
  351. catchFunctionErrors: function (delegate) {
  352. return ko['onError'] ? function () {
  353. try {
  354. return delegate.apply(this, arguments);
  355. } catch (e) {
  356. ko['onError'] && ko['onError'](e);
  357. throw e;
  358. }
  359. } : delegate;
  360. },
  361. setTimeout: function (handler, timeout) {
  362. return setTimeout(ko.utils.catchFunctionErrors(handler), timeout);
  363. },
  364. deferError: function (error) {
  365. setTimeout(function () {
  366. ko['onError'] && ko['onError'](error);
  367. throw error;
  368. }, 0);
  369. },
  370. registerEventHandler: function (element, eventType, handler) {
  371. var wrappedHandler = ko.utils.catchFunctionErrors(handler);
  372. var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
  373. if (!ko.options['useOnlyNativeEvents'] && !mustUseAttachEvent && jQueryInstance) {
  374. jQueryInstance(element)['bind'](eventType, wrappedHandler);
  375. } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
  376. element.addEventListener(eventType, wrappedHandler, false);
  377. else if (typeof element.attachEvent != "undefined") {
  378. var attachEventHandler = function (event) { wrappedHandler.call(element, event); },
  379. attachEventName = "on" + eventType;
  380. element.attachEvent(attachEventName, attachEventHandler);
  381. // IE does not dispose attachEvent handlers automatically (unlike with addEventListener)
  382. // so to avoid leaks, we have to remove them manually. See bug #856
  383. ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
  384. element.detachEvent(attachEventName, attachEventHandler);
  385. });
  386. } else
  387. throw new Error("Browser doesn't support addEventListener or attachEvent");
  388. },
  389. triggerEvent: function (element, eventType) {
  390. if (!(element && element.nodeType))
  391. throw new Error("element must be a DOM node when calling triggerEvent");
  392. // For click events on checkboxes and radio buttons, jQuery toggles the element checked state *after* the
  393. // event handler runs instead of *before*. (This was fixed in 1.9 for checkboxes but not for radio buttons.)
  394. // IE doesn't change the checked state when you trigger the click event using "fireEvent".
  395. // In both cases, we'll use the click method instead.
  396. var useClickWorkaround = isClickOnCheckableElement(element, eventType);
  397. if (!ko.options['useOnlyNativeEvents'] && jQueryInstance && !useClickWorkaround) {
  398. jQueryInstance(element)['trigger'](eventType);
  399. } else if (typeof document.createEvent == "function") {
  400. if (typeof element.dispatchEvent == "function") {
  401. var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
  402. var event = document.createEvent(eventCategory);
  403. event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
  404. element.dispatchEvent(event);
  405. }
  406. else
  407. throw new Error("The supplied element doesn't support dispatchEvent");
  408. } else if (useClickWorkaround && element.click) {
  409. element.click();
  410. } else if (typeof element.fireEvent != "undefined") {
  411. element.fireEvent("on" + eventType);
  412. } else {
  413. throw new Error("Browser doesn't support triggering events");
  414. }
  415. },
  416. unwrapObservable: function (value) {
  417. return ko.isObservable(value) ? value() : value;
  418. },
  419. peekObservable: function (value) {
  420. return ko.isObservable(value) ? value.peek() : value;
  421. },
  422. toggleDomNodeCssClass: toggleDomNodeCssClass,
  423. setTextContent: function(element, textContent) {
  424. var value = ko.utils.unwrapObservable(textContent);
  425. if ((value === null) || (value === undefined))
  426. value = "";
  427. // We need there to be exactly one child: a text node.
  428. // If there are no children, more than one, or if it's not a text node,
  429. // we'll clear everything and create a single text node.
  430. var innerTextNode = ko.virtualElements.firstChild(element);
  431. if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
  432. ko.virtualElements.setDomNodeChildren(element, [element.ownerDocument.createTextNode(value)]);
  433. } else {
  434. innerTextNode.data = value;
  435. }
  436. ko.utils.forceRefresh(element);
  437. },
  438. setElementName: function(element, name) {
  439. element.name = name;
  440. // Workaround IE 6/7 issue
  441. // - https://github.com/SteveSanderson/knockout/issues/197
  442. // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
  443. if (ieVersion <= 7) {
  444. try {
  445. element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
  446. }
  447. catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
  448. }
  449. },
  450. forceRefresh: function(node) {
  451. // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
  452. if (ieVersion >= 9) {
  453. // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
  454. var elem = node.nodeType == 1 ? node : node.parentNode;
  455. if (elem.style)
  456. elem.style.zoom = elem.style.zoom;
  457. }
  458. },
  459. ensureSelectElementIsRenderedCorrectly: function(selectElement) {
  460. // Workaround for IE9 rendering bug - it doesn't reliably display all the text in dynamically-added select boxes unless you force it to re-render by updating the width.
  461. // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
  462. // Also fixes IE7 and IE8 bug that causes selects to be zero width if enclosed by 'if' or 'with'. (See issue #839)
  463. if (ieVersion) {
  464. var originalWidth = selectElement.style.width;
  465. selectElement.style.width = 0;
  466. selectElement.style.width = originalWidth;
  467. }
  468. },
  469. range: function (min, max) {
  470. min = ko.utils.unwrapObservable(min);
  471. max = ko.utils.unwrapObservable(max);
  472. var result = [];
  473. for (var i = min; i <= max; i++)
  474. result.push(i);
  475. return result;
  476. },
  477. makeArray: function(arrayLikeObject) {
  478. var result = [];
  479. for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
  480. result.push(arrayLikeObject[i]);
  481. };
  482. return result;
  483. },
  484. createSymbolOrString: function(identifier) {
  485. return canUseSymbols ? Symbol(identifier) : identifier;
  486. },
  487. isIe6 : isIe6,
  488. isIe7 : isIe7,
  489. ieVersion : ieVersion,
  490. getFormFields: function(form, fieldName) {
  491. var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
  492. var isMatchingField = (typeof fieldName == 'string')
  493. ? function(field) { return field.name === fieldName }
  494. : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
  495. var matches = [];
  496. for (var i = fields.length - 1; i >= 0; i--) {
  497. if (isMatchingField(fields[i]))
  498. matches.push(fields[i]);
  499. };
  500. return matches;
  501. },
  502. parseJson: function (jsonString) {
  503. if (typeof jsonString == "string") {
  504. jsonString = ko.utils.stringTrim(jsonString);
  505. if (jsonString) {
  506. if (JSON && JSON.parse) // Use native parsing where available
  507. return JSON.parse(jsonString);
  508. return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
  509. }
  510. }
  511. return null;
  512. },
  513. stringifyJson: function (data, replacer, space) { // replacer and space are optional
  514. if (!JSON || !JSON.stringify)
  515. throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");
  516. return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
  517. },
  518. postJson: function (urlOrForm, data, options) {
  519. options = options || {};
  520. var params = options['params'] || {};
  521. var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
  522. var url = urlOrForm;
  523. // If we were given a form, use its 'action' URL and pick out any requested field values
  524. if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
  525. var originalForm = urlOrForm;
  526. url = originalForm.action;
  527. for (var i = includeFields.length - 1; i >= 0; i--) {
  528. var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
  529. for (var j = fields.length - 1; j >= 0; j--)
  530. params[fields[j].name] = fields[j].value;
  531. }
  532. }
  533. data = ko.utils.unwrapObservable(data);
  534. var form = document.createElement("form");
  535. form.style.display = "none";
  536. form.action = url;
  537. form.method = "post";
  538. for (var key in data) {
  539. // Since 'data' this is a model object, we include all properties including those inherited from its prototype
  540. var input = document.createElement("input");
  541. input.type = "hidden";
  542. input.name = key;
  543. input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
  544. form.appendChild(input);
  545. }
  546. objectForEach(params, function(key, value) {
  547. var input = document.createElement("input");
  548. input.type = "hidden";
  549. input.name = key;
  550. input.value = value;
  551. form.appendChild(input);
  552. });
  553. document.body.appendChild(form);
  554. options['submitter'] ? options['submitter'](form) : form.submit();
  555. setTimeout(function () { form.parentNode.removeChild(form); }, 0);
  556. }
  557. }
  558. }());
  559. ko.exportSymbol('utils', ko.utils);
  560. ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
  561. ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
  562. ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
  563. ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
  564. ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
  565. ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
  566. ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
  567. ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
  568. ko.exportSymbol('utils.extend', ko.utils.extend);
  569. ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
  570. ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
  571. ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
  572. ko.exportSymbol('utils.postJson', ko.utils.postJson);
  573. ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
  574. ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
  575. ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
  576. ko.exportSymbol('utils.range', ko.utils.range);
  577. ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
  578. ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
  579. ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
  580. ko.exportSymbol('utils.objectForEach', ko.utils.objectForEach);
  581. ko.exportSymbol('utils.addOrRemoveItem', ko.utils.addOrRemoveItem);
  582. ko.exportSymbol('utils.setTextContent', ko.utils.setTextContent);
  583. ko.exportSymbol('unwrap', ko.utils.unwrapObservable); // Convenient shorthand, because this is used so commonly
  584. if (!Function.prototype['bind']) {
  585. // Function.prototype.bind is a standard part of ECMAScript 5th Edition (December 2009, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf)
  586. // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
  587. Function.prototype['bind'] = function (object) {
  588. var originalFunction = this;
  589. if (arguments.length === 1) {
  590. return function () {
  591. return originalFunction.apply(object, arguments);
  592. };
  593. } else {
  594. var partialArgs = Array.prototype.slice.call(arguments, 1);
  595. return function () {
  596. var args = partialArgs.slice(0);
  597. args.push.apply(args, arguments);
  598. return originalFunction.apply(object, args);
  599. };
  600. }
  601. };
  602. }
  603. ko.utils.domData = new (function () {
  604. var uniqueId = 0;
  605. var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
  606. var dataStore = {};
  607. function getAll(node, createIfNotFound) {
  608. var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
  609. var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
  610. if (!hasExistingDataStore) {
  611. if (!createIfNotFound)
  612. return undefined;
  613. dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
  614. dataStore[dataStoreKey] = {};
  615. }
  616. return dataStore[dataStoreKey];
  617. }
  618. return {
  619. get: function (node, key) {
  620. var allDataForNode = getAll(node, false);
  621. return allDataForNode === undefined ? undefined : allDataForNode[key];
  622. },
  623. set: function (node, key, value) {
  624. if (value === undefined) {
  625. // Make sure we don't actually create a new domData key if we are actually deleting a value
  626. if (getAll(node, false) === undefined)
  627. return;
  628. }
  629. var allDataForNode = getAll(node, true);
  630. allDataForNode[key] = value;
  631. },
  632. clear: function (node) {
  633. var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
  634. if (dataStoreKey) {
  635. delete dataStore[dataStoreKey];
  636. node[dataStoreKeyExpandoPropertyName] = null;
  637. return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
  638. }
  639. return false;
  640. },
  641. nextKey: function () {
  642. return (uniqueId++) + dataStoreKeyExpandoPropertyName;
  643. }
  644. };
  645. })();
  646. ko.exportSymbol('utils.domData', ko.utils.domData);
  647. ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
  648. ko.utils.domNodeDisposal = new (function () {
  649. var domDataKey = ko.utils.domData.nextKey();
  650. var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
  651. var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
  652. function getDisposeCallbacksCollection(node, createIfNotFound) {
  653. var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
  654. if ((allDisposeCallbacks === undefined) && createIfNotFound) {
  655. allDisposeCallbacks = [];
  656. ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
  657. }
  658. return allDisposeCallbacks;
  659. }
  660. function destroyCallbacksCollection(node) {
  661. ko.utils.domData.set(node, domDataKey, undefined);
  662. }
  663. function cleanSingleNode(node) {
  664. // Run all the dispose callbacks
  665. var callbacks = getDisposeCallbacksCollection(node, false);
  666. if (callbacks) {
  667. callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
  668. for (var i = 0; i < callbacks.length; i++)
  669. callbacks[i](node);
  670. }
  671. // Erase the DOM data
  672. ko.utils.domData.clear(node);
  673. // Perform cleanup needed by external libraries (currently only jQuery, but can be extended)
  674. ko.utils.domNodeDisposal["cleanExternalData"](node);
  675. // Clear any immediate-child comment nodes, as these wouldn't have been found by
  676. // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
  677. if (cleanableNodeTypesWithDescendants[node.nodeType])
  678. cleanImmediateCommentTypeChildren(node);
  679. }
  680. function cleanImmediateCommentTypeChildren(nodeWithChildren) {
  681. var child, nextChild = nodeWithChildren.firstChild;
  682. while (child = nextChild) {
  683. nextChild = child.nextSibling;
  684. if (child.nodeType === 8)
  685. cleanSingleNode(child);
  686. }
  687. }
  688. return {
  689. addDisposeCallback : function(node, callback) {
  690. if (typeof callback != "function")
  691. throw new Error("Callback must be a function");
  692. getDisposeCallbacksCollection(node, true).push(callback);
  693. },
  694. removeDisposeCallback : function(node, callback) {
  695. var callbacksCollection = getDisposeCallbacksCollection(node, false);
  696. if (callbacksCollection) {
  697. ko.utils.arrayRemoveItem(callbacksCollection, callback);
  698. if (callbacksCollection.length == 0)
  699. destroyCallbacksCollection(node);
  700. }
  701. },
  702. cleanNode : function(node) {
  703. // First clean this node, where applicable
  704. if (cleanableNodeTypes[node.nodeType]) {
  705. cleanSingleNode(node);
  706. // ... then its descendants, where applicable
  707. if (cleanableNodeTypesWithDescendants[node.nodeType]) {
  708. // Clone the descendants list in case it changes during iteration
  709. var descendants = [];
  710. ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
  711. for (var i = 0, j = descendants.length; i < j; i++)
  712. cleanSingleNode(descendants[i]);
  713. }
  714. }
  715. return node;
  716. },
  717. removeNode : function(node) {
  718. ko.cleanNode(node);
  719. if (node.parentNode)
  720. node.parentNode.removeChild(node);
  721. },
  722. "cleanExternalData" : function (node) {
  723. // Special support for jQuery here because it's so commonly used.
  724. // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
  725. // so notify it to tear down any resources associated with the node & descendants here.
  726. if (jQueryInstance && (typeof jQueryInstance['cleanData'] == "function"))
  727. jQueryInstance['cleanData']([node]);
  728. }
  729. };
  730. })();
  731. ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
  732. ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
  733. ko.exportSymbol('cleanNode', ko.cleanNode);
  734. ko.exportSymbol('removeNode', ko.removeNode);
  735. ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
  736. ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
  737. ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
  738. (function () {
  739. var none = [0, "", ""],
  740. table = [1, "<table>", "</table>"],
  741. tbody = [2, "<table><tbody>", "</tbody></table>"],
  742. tr = [3, "<table><tbody><tr>", "</tr></tbody></table>"],
  743. select = [1, "<select multiple='multiple'>", "</select>"],
  744. lookup = {
  745. 'thead': table,
  746. 'tbody': table,
  747. 'tfoot': table,
  748. 'tr': tbody,
  749. 'td': tr,
  750. 'th': tr,
  751. 'option': select,
  752. 'optgroup': select
  753. },
  754. // This is needed for old IE if you're *not* using either jQuery or innerShiv. Doesn't affect other cases.
  755. mayRequireCreateElementHack = ko.utils.ieVersion <= 8;
  756. function getWrap(tags) {
  757. var m = tags.match(/^<([a-z]+)[ >]/);
  758. return (m && lookup[m[1]]) || none;
  759. }
  760. function simpleHtmlParse(html, documentContext) {
  761. documentContext || (documentContext = document);
  762. var windowContext = documentContext['parentWindow'] || documentContext['defaultView'] || window;
  763. // Based on jQuery's "clean" function, but only accounting for table-related elements.
  764. // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
  765. // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
  766. // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
  767. // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
  768. // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
  769. // Trim whitespace, otherwise indexOf won't work as expected
  770. var tags = ko.utils.stringTrim(html).toLowerCase(), div = documentContext.createElement("div"),
  771. wrap = getWrap(tags),
  772. depth = wrap[0];
  773. // Go to html and back, then peel off extra wrappers
  774. // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
  775. var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
  776. if (typeof windowContext['innerShiv'] == "function") {
  777. // Note that innerShiv is deprecated in favour of html5shiv. We should consider adding
  778. // support for html5shiv (except if no explicit support is needed, e.g., if html5shiv
  779. // somehow shims the native APIs so it just works anyway)
  780. div.appendChild(windowContext['innerShiv'](markup));
  781. } else {
  782. if (mayRequireCreateElementHack) {
  783. // The document.createElement('my-element') trick to enable custom elements in IE6-8
  784. // only works if we assign innerHTML on an element associated with that document.
  785. documentContext.appendChild(div);
  786. }
  787. div.innerHTML = markup;
  788. if (mayRequireCreateElementHack) {
  789. div.parentNode.removeChild(div);
  790. }
  791. }
  792. // Move to the right depth
  793. while (depth--)
  794. div = div.lastChild;
  795. return ko.utils.makeArray(div.lastChild.childNodes);
  796. }
  797. function jQueryHtmlParse(html, documentContext) {
  798. // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
  799. if (jQueryInstance['parseHTML']) {
  800. return jQueryInstance['parseHTML'](html, documentContext) || []; // Ensure we always return an array and never null
  801. } else {
  802. // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
  803. var elems = jQueryInstance['clean']([html], documentContext);
  804. // As of jQuery 1.7.1, jQuery parses the HTML by appending it to some dummy parent nodes held in an in-memory document fragment.
  805. // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
  806. // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
  807. if (elems && elems[0]) {
  808. // Find the top-most parent element that's a direct child of a document fragment
  809. var elem = elems[0];
  810. while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
  811. elem = elem.parentNode;
  812. // ... then detach it
  813. if (elem.parentNode)
  814. elem.parentNode.removeChild(elem);
  815. }
  816. return elems;
  817. }
  818. }
  819. ko.utils.parseHtmlFragment = function(html, documentContext) {
  820. return jQueryInstance ?
  821. jQueryHtmlParse(html, documentContext) : // As below, benefit from jQuery's optimisations where possible
  822. simpleHtmlParse(html, documentContext); // ... otherwise, this simple logic will do in most common cases.
  823. };
  824. ko.utils.setHtml = function(node, html) {
  825. ko.utils.emptyDomNode(node);
  826. // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
  827. html = ko.utils.unwrapObservable(html);
  828. if ((html !== null) && (html !== undefined)) {
  829. if (typeof html != 'string')
  830. html = html.toString();
  831. // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
  832. // for example <tr> elements which are not normally allowed to exist on their own.
  833. // If you've referenced jQuery we'll use that rather than duplicating its code.
  834. if (jQueryInstance) {
  835. jQueryInstance(node)['html'](html);
  836. } else {
  837. // ... otherwise, use KO's own parsing logic.
  838. var parsedNodes = ko.utils.parseHtmlFragment(html, node.ownerDocument);
  839. for (var i = 0; i < parsedNodes.length; i++)
  840. node.appendChild(parsedNodes[i]);
  841. }
  842. }
  843. };
  844. })();
  845. ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
  846. ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
  847. ko.memoization = (function () {
  848. var memos = {};
  849. function randomMax8HexChars() {
  850. return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
  851. }
  852. function generateRandomId() {
  853. return randomMax8HexChars() + randomMax8HexChars();
  854. }
  855. function findMemoNodes(rootNode, appendToArray) {
  856. if (!rootNode)
  857. return;
  858. if (rootNode.nodeType == 8) {
  859. var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
  860. if (memoId != null)
  861. appendToArray.push({ domNode: rootNode, memoId: memoId });
  862. } else if (rootNode.nodeType == 1) {
  863. for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
  864. findMemoNodes(childNodes[i], appendToArray);
  865. }
  866. }
  867. return {
  868. memoize: function (callback) {
  869. if (typeof callback != "function")
  870. throw new Error("You can only pass a function to ko.memoization.memoize()");
  871. var memoId = generateRandomId();
  872. memos[memoId] = callback;
  873. return "<!--[ko_memo:" + memoId + "]-->";
  874. },
  875. unmemoize: function (memoId, callbackParams) {
  876. var callback = memos[memoId];
  877. if (callback === undefined)
  878. throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
  879. try {
  880. callback.apply(null, callbackParams || []);
  881. return true;
  882. }
  883. finally { delete memos[memoId]; }
  884. },
  885. unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
  886. var memos = [];
  887. findMemoNodes(domNode, memos);
  888. for (var i = 0, j = memos.length; i < j; i++) {
  889. var node = memos[i].domNode;
  890. var combinedParams = [node];
  891. if (extraCallbackParamsArray)
  892. ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
  893. ko.memoization.unmemoize(memos[i].memoId, combinedParams);
  894. node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
  895. if (node.parentNode)
  896. node.parentNode.removeChild(node); // If possible, erase it totally (not always possible - someone else might just hold a reference to it then call unmemoizeDomNodeAndDescendants again)
  897. }
  898. },
  899. parseMemoText: function (memoText) {
  900. var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
  901. return match ? match[1] : null;
  902. }
  903. };
  904. })();
  905. ko.exportSymbol('memoization', ko.memoization);
  906. ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
  907. ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
  908. ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
  909. ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
  910. ko.tasks = (function () {
  911. var scheduler,
  912. taskQueue = [],
  913. taskQueueLength = 0,
  914. nextHandle = 1,
  915. nextIndexToProcess = 0;
  916. if (window['MutationObserver']) {
  917. // Chrome 27+, Firefox 14+, IE 11+, Opera 15+, Safari 6.1+
  918. // From https://github.com/petkaantonov/bluebird * Copyright (c) 2014 Petka Antonov * License: MIT
  919. scheduler = (function (callback) {
  920. var div = document.createElement("div");
  921. new MutationObserver(callback).observe(div, {attributes: true});
  922. return function () { div.classList.toggle("foo"); };
  923. })(scheduledProcess);
  924. } else if (document && "onreadystatechange" in document.createElement("script")) {
  925. // IE 6-10
  926. // From https://github.com/YuzuJS/setImmediate * Copyright (c) 2012 Barnesandnoble.com, llc, Donavon West, and Domenic Denicola * License: MIT
  927. scheduler = function (callback) {
  928. var script = document.createElement("script");
  929. script.onreadystatechange = function () {
  930. script.onreadystatechange = null;
  931. document.documentElement.removeChild(script);
  932. script = null;
  933. callback();
  934. };
  935. document.documentElement.appendChild(script);
  936. };
  937. } else {
  938. scheduler = function (callback) {
  939. setTimeout(callback, 0);
  940. };
  941. }
  942. function processTasks() {
  943. if (taskQueueLength) {
  944. // Each mark represents the end of a logical group of tasks and the number of these groups is
  945. // limited to prevent unchecked recursion.
  946. var mark = taskQueueLength, countMarks = 0;
  947. // nextIndexToProcess keeps track of where we are in the queue; processTasks can be called recursively without issue
  948. for (var task; nextIndexToProcess < taskQueueLength; ) {
  949. if (task = taskQueue[nextIndexToProcess++]) {
  950. if (nextIndexToProcess > mark) {
  951. if (++countMarks >= 5000) {
  952. nextIndexToProcess = taskQueueLength; // skip all tasks remaining in the queue since any of them could be causing the recursion
  953. ko.utils.deferError(Error("'Too much recursion' after processing " + countMarks + " task groups."));
  954. break;
  955. }
  956. mark = taskQueueLength;
  957. }
  958. try {
  959. task();
  960. } catch (ex) {
  961. ko.utils.deferError(ex);
  962. }
  963. }
  964. }
  965. }
  966. }
  967. function scheduledProcess() {
  968. processTasks();
  969. // Reset the queue
  970. nextIndexToProcess = taskQueueLength = taskQueue.length = 0;
  971. }
  972. function scheduleTaskProcessing() {
  973. ko.tasks['scheduler'](scheduledProcess);
  974. }
  975. var tasks = {
  976. 'scheduler': scheduler, // Allow overriding the scheduler
  977. schedule: function (func) {
  978. if (!taskQueueLength) {
  979. scheduleTaskProcessing();
  980. }
  981. taskQueue[taskQueueLength++] = func;
  982. return nextHandle++;
  983. },
  984. cancel: function (handle) {
  985. var index = handle - (nextHandle - taskQueueLength);
  986. if (index >= nextIndexToProcess && index < taskQueueLength) {
  987. taskQueue[index] = null;
  988. }
  989. },
  990. // For testing only: reset the queue and return the previous queue length
  991. 'resetForTesting': function () {
  992. var length = taskQueueLength - nextIndexToProcess;
  993. nextIndexToProcess = taskQueueLength = taskQueue.length = 0;
  994. return length;
  995. },
  996. runEarly: processTasks
  997. };
  998. return tasks;
  999. })();
  1000. ko.exportSymbol('tasks', ko.tasks);
  1001. ko.exportSymbol('tasks.schedule', ko.tasks.schedule);
  1002. //ko.exportSymbol('tasks.cancel', ko.tasks.cancel); "cancel" isn't minified
  1003. ko.exportSymbol('tasks.runEarly', ko.tasks.runEarly);
  1004. ko.extenders = {
  1005. 'throttle': function(target, timeout) {
  1006. // Throttling means two things:
  1007. // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
  1008. // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
  1009. target['throttleEvaluation'] = timeout;
  1010. // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
  1011. // so the target cannot change value synchronously or faster than a certain rate
  1012. var writeTimeoutInstance = null;
  1013. return ko.dependentObservable({
  1014. 'read': target,
  1015. 'write': function(value) {
  1016. clearTimeout(writeTimeoutInstance);
  1017. writeTimeoutInstance = ko.utils.setTimeout(function() {
  1018. target(value);
  1019. }, timeout);
  1020. }
  1021. });
  1022. },
  1023. 'rateLimit': function(target, options) {
  1024. var timeout, method, limitFunction;
  1025. if (typeof options == 'number') {
  1026. timeout = options;
  1027. } else {
  1028. timeout = options['timeout'];
  1029. method = options['method'];
  1030. }
  1031. // rateLimit supersedes deferred updates
  1032. target._deferUpdates = false;
  1033. limitFunction = method == 'notifyWhenChangesStop' ? debounce : throttle;
  1034. target.limit(function(callback) {
  1035. return limitFunction(callback, timeout);
  1036. });
  1037. },
  1038. 'deferred': function(target, options) {
  1039. if (options !== true) {
  1040. throw new Error('The \'deferred\' extender only accepts the value \'true\', because it is not supported to turn deferral off once enabled.')
  1041. }
  1042. if (!target._deferUpdates) {
  1043. target._deferUpdates = true;
  1044. target.limit(function (callback) {
  1045. var handle,
  1046. ignoreUpdates = false;
  1047. return function () {
  1048. if (!ignoreUpdates) {
  1049. ko.tasks.cancel(handle);
  1050. handle = ko.tasks.schedule(callback);
  1051. try {
  1052. ignoreUpdates = true;
  1053. target['notifySubscribers'](undefined, 'dirty');
  1054. } finally {
  1055. ignoreUpdates = false;
  1056. }
  1057. }
  1058. };
  1059. });
  1060. }
  1061. },
  1062. 'notify': function(target, notifyWhen) {
  1063. target["equalityComparer"] = notifyWhen == "always" ?
  1064. null : // null equalityComparer means to always notify
  1065. valuesArePrimitiveAndEqual;
  1066. }
  1067. };
  1068. var primitiveTypes = { 'undefined':1, 'boolean':1, 'number':1, 'string':1 };
  1069. function valuesArePrimitiveAndEqual(a, b) {
  1070. var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
  1071. return oldValueIsPrimitive ? (a === b) : false;
  1072. }
  1073. function throttle(callback, timeout) {
  1074. var timeoutInstance;
  1075. return function () {
  1076. if (!timeoutInstance) {
  1077. timeoutInstance = ko.utils.setTimeout(function () {
  1078. timeoutInstance = undefined;
  1079. callback();
  1080. }, timeout);
  1081. }
  1082. };
  1083. }
  1084. function debounce(callback, timeout) {
  1085. var timeoutInstance;
  1086. return function () {
  1087. clearTimeout(timeoutInstance);
  1088. timeoutInstance = ko.utils.setTimeout(callback, timeout);
  1089. };
  1090. }
  1091. function applyExtenders(requestedExtenders) {
  1092. var target = this;
  1093. if (requestedExtenders) {
  1094. ko.utils.objectForEach(requestedExtenders, function(key, value) {
  1095. var extenderHandler = ko.extenders[key];
  1096. if (typeof extenderHandler == 'function') {
  1097. target = extenderHandler(target, value) || target;
  1098. }
  1099. });
  1100. }
  1101. return target;
  1102. }
  1103. ko.exportSymbol('extenders', ko.extenders);
  1104. ko.subscription = function (target, callback, disposeCallback) {
  1105. this._target = target;
  1106. this.callback = callback;
  1107. this.disposeCallback = disposeCallback;
  1108. this.isDisposed = false;
  1109. ko.exportProperty(this, 'dispose', this.dispose);
  1110. };
  1111. ko.subscription.prototype.dispose = function () {
  1112. this.isDisposed = true;
  1113. this.disposeCallback();
  1114. };
  1115. ko.subscribable = function () {
  1116. ko.utils.setPrototypeOfOrExtend(this, ko_subscribable_fn);
  1117. ko_subscribable_fn.init(this);
  1118. }
  1119. var defaultEvent = "change";
  1120. // Moved out of "limit" to avoid the extra closure
  1121. function limitNotifySubscribers(value, event) {
  1122. if (!event || event === defaultEvent) {
  1123. this._limitChange(value);
  1124. } else if (event === 'beforeChange') {
  1125. this._limitBeforeChange(value);
  1126. } else {
  1127. this._origNotifySubscribers(value, event);
  1128. }
  1129. }
  1130. var ko_subscribable_fn = {
  1131. init: function(instance) {
  1132. instance._subscriptions = { "change": [] };
  1133. instance._versionNumber = 1;
  1134. },
  1135. subscribe: function (callback, callbackTarget, event) {
  1136. var self = this;
  1137. event = event || defaultEvent;
  1138. var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
  1139. var subscription = new ko.subscription(self, boundCallback, function () {
  1140. ko.utils.arrayRemoveItem(self._subscriptions[event], subscription);
  1141. if (self.afterSubscriptionRemove)
  1142. self.afterSubscriptionRemove(event);
  1143. });
  1144. if (self.beforeSubscriptionAdd)
  1145. self.beforeSubscriptionAdd(event);
  1146. if (!self._subscriptions[event])
  1147. self._subscriptions[event] = [];
  1148. self._subscriptions[event].push(subscription);
  1149. return subscription;
  1150. },
  1151. "notifySubscribers": function (valueToNotify, event) {
  1152. event = event || defaultEvent;
  1153. if (event === defaultEvent) {
  1154. this.updateVersion();
  1155. }
  1156. if (this.hasSubscriptionsForEvent(event)) {
  1157. var subs = event === defaultEvent && this._changeSubscriptions || this._subscriptions[event].slice(0);
  1158. try {
  1159. ko.dependencyDetection.begin(); // Begin suppressing dependency detection (by setting the top frame to undefined)
  1160. for (var i = 0, subscription; subscription = subs[i]; ++i) {
  1161. // In case a subscription was disposed during the arrayForEach cycle, check
  1162. // for isDisposed on each subscription before invoking its callback
  1163. if (!subscription.isDisposed)
  1164. subscription.callback(valueToNotify);
  1165. }
  1166. } finally {
  1167. ko.dependencyDetection.end(); // End suppressing dependency detection
  1168. }
  1169. }
  1170. },
  1171. getVersion: function () {
  1172. return this._versionNumber;
  1173. },
  1174. hasChanged: function (versionToCheck) {
  1175. return this.getVersion() !== versionToCheck;
  1176. },
  1177. updateVersion: function () {
  1178. ++this._versionNumber;
  1179. },
  1180. limit: function(limitFunction) {
  1181. var self = this, selfIsObservable = ko.isObservable(self),
  1182. ignoreBeforeChange, notifyNextChange, previousValue, pendingValue, beforeChange = 'beforeChange';
  1183. if (!self._origNotifySubscribers) {
  1184. self._origNotifySubscribers = self["notifySubscribers"];
  1185. self["notifySubscribers"] = limitNotifySubscribers;
  1186. }
  1187. var finish = limitFunction(function() {
  1188. self._notificationIsPending = false;
  1189. // If an observable provided a reference to itself, access it to get the latest value.
  1190. // This allows computed observables to delay calculating their value until needed.
  1191. if (selfIsObservable && pendingValue === self) {
  1192. pendingValue = self._evalIfChanged ? self._evalIfChanged() : self();
  1193. }
  1194. var shouldNotify = notifyNextChange || self.isDifferent(previousValue, pendingValue);
  1195. notifyNextChange = ignoreBeforeChange = false;
  1196. if (shouldNotify) {
  1197. self._origNotifySubscribers(previousValue = pendingValue);
  1198. }
  1199. });
  1200. self._limitChange = function(value) {
  1201. self._changeSubscriptions = self._subscriptions[defaultEvent].slice(0);
  1202. self._notificationIsPending = ignoreBeforeChange = true;
  1203. pendingValue = value;
  1204. finish();
  1205. };
  1206. self._limitBeforeChange = function(value) {
  1207. if (!ignoreBeforeChange) {
  1208. previousValue = value;
  1209. self._origNotifySubscribers(value, beforeChange);
  1210. }
  1211. };
  1212. self._notifyNextChangeIfValueIsDifferent = function() {
  1213. if (self.isDifferent(previousValue, self.peek(true /*evaluate*/))) {
  1214. notifyNextChange = true;
  1215. }
  1216. };
  1217. },
  1218. hasSubscriptionsForEvent: function(event) {
  1219. return this._subscriptions[event] && this._subscriptions[event].length;
  1220. },
  1221. getSubscriptionsCount: function (event) {
  1222. if (event) {
  1223. return this._subscriptions[event] && this._subscriptions[event].length || 0;
  1224. } else {
  1225. var total = 0;
  1226. ko.utils.objectForEach(this._subscriptions, function(eventName, subscriptions) {
  1227. if (eventName !== 'dirty')
  1228. total += subscriptions.length;
  1229. });
  1230. return total;
  1231. }
  1232. },
  1233. isDifferent: function(oldValue, newValue) {
  1234. return !this['equalityComparer'] || !this['equalityComparer'](oldValue, newValue);
  1235. },
  1236. extend: applyExtenders
  1237. };
  1238. ko.exportProperty(ko_subscribable_fn, 'subscribe', ko_subscribable_fn.subscribe);
  1239. ko.exportProperty(ko_subscribable_fn, 'extend', ko_subscribable_fn.extend);
  1240. ko.exportProperty(ko_subscribable_fn, 'getSubscriptionsCount', ko_subscribable_fn.getSubscriptionsCount);
  1241. // For browsers that support proto assignment, we overwrite the prototype of each
  1242. // observable instance. Since observables are functions, we need Function.prototype
  1243. // to still be in the prototype chain.
  1244. if (ko.utils.canSetPrototype) {
  1245. ko.utils.setPrototypeOf(ko_subscribable_fn, Function.prototype);
  1246. }
  1247. ko.subscribable['fn'] = ko_subscribable_fn;
  1248. ko.isSubscribable = function (instance) {
  1249. return instance != null && typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
  1250. };
  1251. ko.exportSymbol('subscribable', ko.subscribable);
  1252. ko.exportSymbol('isSubscribable', ko.isSubscribable);
  1253. ko.computedContext = ko.dependencyDetection = (function () {
  1254. var outerFrames = [],
  1255. currentFrame,
  1256. lastId = 0;
  1257. // Return a unique ID that can be assigned to an observable for dependency tracking.
  1258. // Theoretically, you could eventually overflow the number storage size, resulting
  1259. // in duplicate IDs. But in JavaScript, the largest exact integral value is 2^53
  1260. // or 9,007,199,254,740,992. If you created 1,000,000 IDs per second, it would
  1261. // take over 285 years to reach that number.
  1262. // Reference http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html
  1263. function getId() {
  1264. return ++lastId;
  1265. }
  1266. function begin(options) {
  1267. outerFrames.push(currentFrame);
  1268. currentFrame = options;
  1269. }
  1270. function end() {
  1271. currentFrame = outerFrames.pop();
  1272. }
  1273. return {
  1274. begin: begin,
  1275. end: end,
  1276. registerDependency: function (subscribable) {
  1277. if (currentFrame) {
  1278. if (!ko.isSubscribable(subscribable))
  1279. throw new Error("Only subscribable things can act as dependencies");
  1280. currentFrame.callback.call(currentFrame.callbackTarget, subscribable, subscribable._id || (subscribable._id = getId()));
  1281. }
  1282. },
  1283. ignore: function (callback, callbackTarget, callbackArgs) {
  1284. try {
  1285. begin();
  1286. return callback.apply(callbackTarget, callbackArgs || []);
  1287. } finally {
  1288. end();
  1289. }
  1290. },
  1291. getDependenciesCount: function () {
  1292. if (currentFrame)
  1293. return currentFrame.computed.getDependenciesCount();
  1294. },
  1295. isInitial: function() {
  1296. if (currentFrame)
  1297. return currentFrame.isInitial;
  1298. }
  1299. };
  1300. })();
  1301. ko.exportSymbol('computedContext', ko.computedContext);
  1302. ko.exportSymbol('computedContext.getDependenciesCount', ko.computedContext.getDependenciesCount);
  1303. ko.exportSymbol('computedContext.isInitial', ko.computedContext.isInitial);
  1304. ko.exportSymbol('ignoreDependencies', ko.ignoreDependencies = ko.dependencyDetection.ignore);
  1305. var observableLatestValue = ko.utils.createSymbolOrString('_latestValue');
  1306. ko.observable = function (initialValue) {
  1307. function observable() {
  1308. if (arguments.length > 0) {
  1309. // Write
  1310. // Ignore writes if the value hasn't changed
  1311. if (observable.isDifferent(observable[observableLatestValue], arguments[0])) {
  1312. observable.valueWillMutate();
  1313. observable[observableLatestValue] = arguments[0];
  1314. observable.valueHasMutated();
  1315. }
  1316. return this; // Permits chained assignments
  1317. }
  1318. else {
  1319. // Read
  1320. ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
  1321. return observable[observableLatestValue];
  1322. }
  1323. }
  1324. observable[observableLatestValue] = initialValue;
  1325. // Inherit from 'subscribable'
  1326. if (!ko.utils.canSetPrototype) {
  1327. // 'subscribable' won't be on the prototype chain unless we put it there directly
  1328. ko.utils.extend(observable, ko.subscribable['fn']);
  1329. }
  1330. ko.subscribable['fn'].init(observable);
  1331. // Inherit from 'observable'
  1332. ko.utils.setPrototypeOfOrExtend(observable, observableFn);
  1333. if (ko.options['deferUpdates']) {
  1334. ko.extenders['deferred'](observable, true);
  1335. }
  1336. return observable;
  1337. }
  1338. // Define prototype for observables
  1339. var observableFn = {
  1340. 'equalityComparer': valuesArePrimitiveAndEqual,
  1341. peek: function() { return this[observableLatestValue]; },
  1342. valueHasMutated: function () { this['notifySubscribers'](this[observableLatestValue]); },
  1343. valueWillMutate: function () { this['notifySubscribers'](this[observableLatestValue], 'beforeChange'); }
  1344. };
  1345. // Note that for browsers that don't support proto assignment, the
  1346. // inheritance chain is created manually in the ko.observable constructor
  1347. if (ko.utils.canSetPrototype) {
  1348. ko.utils.setPrototypeOf(observableFn, ko.subscribable['fn']);
  1349. }
  1350. var protoProperty = ko.observable.protoProperty = '__ko_proto__';
  1351. observableFn[protoProperty] = ko.observable;
  1352. ko.hasPrototype = function(instance, prototype) {
  1353. if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
  1354. if (instance[protoProperty] === prototype) return true;
  1355. return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
  1356. };
  1357. ko.isObservable = function (instance) {
  1358. return ko.hasPrototype(instance, ko.observable);
  1359. }
  1360. ko.isWriteableObservable = function (instance) {
  1361. // Observable
  1362. if ((typeof instance == 'function') && instance[protoProperty] === ko.observable)
  1363. return true;
  1364. // Writeable dependent observable
  1365. if ((typeof instance == 'function') && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
  1366. return true;
  1367. // Anything else
  1368. return false;
  1369. }
  1370. ko.exportSymbol('observable', ko.observable);
  1371. ko.exportSymbol('isObservable', ko.isObservable);
  1372. ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
  1373. ko.exportSymbol('isWritableObservable', ko.isWriteableObservable);
  1374. ko.exportSymbol('observable.fn', observableFn);
  1375. ko.exportProperty(observableFn, 'peek', observableFn.peek);
  1376. ko.exportProperty(observableFn, 'valueHasMutated', observableFn.valueHasMutated);
  1377. ko.exportProperty(observableFn, 'valueWillMutate', observableFn.valueWillMutate);
  1378. ko.observableArray = function (initialValues) {
  1379. initialValues = initialValues || [];
  1380. if (typeof initialValues != 'object' || !('length' in initialValues))
  1381. throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
  1382. var result = ko.observable(initialValues);
  1383. ko.utils.setPrototypeOfOrExtend(result, ko.observableArray['fn']);
  1384. return result.extend({'trackArrayChanges':true});
  1385. };
  1386. ko.observableArray['fn'] = {
  1387. 'remove': function (valueOrPredicate) {
  1388. var underlyingArray = this.peek();
  1389. var removedValues = [];
  1390. var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
  1391. for (var i = 0; i < underlyingArray.length; i++) {
  1392. var value = underlyingArray[i];
  1393. if (predicate(value)) {
  1394. if (removedValues.length === 0) {
  1395. this.valueWillMutate();
  1396. }
  1397. removedValues.push(value);
  1398. underlyingArray.splice(i, 1);
  1399. i--;
  1400. }
  1401. }
  1402. if (removedValues.length) {
  1403. this.valueHasMutated();
  1404. }
  1405. return removedValues;
  1406. },
  1407. 'removeAll': function (arrayOfValues) {
  1408. // If you passed zero args, we remove everything
  1409. if (arrayOfValues === undefined) {
  1410. var underlyingArray = this.peek();
  1411. var allValues = underlyingArray.slice(0);
  1412. this.valueWillMutate();
  1413. underlyingArray.splice(0, underlyingArray.length);
  1414. this.valueHasMutated();
  1415. return allValues;
  1416. }
  1417. // If you passed an arg, we interpret it as an array of entries to remove
  1418. if (!arrayOfValues)
  1419. return [];
  1420. return this['remove'](function (value) {
  1421. return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
  1422. });
  1423. },
  1424. 'destroy': function (valueOrPredicate) {
  1425. var underlyingArray = this.peek();
  1426. var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
  1427. this.valueWillMutate();
  1428. for (var i = underlyingArray.length - 1; i >= 0; i--) {
  1429. var value = underlyingArray[i];
  1430. if (predicate(value))
  1431. underlyingArray[i]["_destroy"] = true;
  1432. }
  1433. this.valueHasMutated();
  1434. },
  1435. 'destroyAll': function (arrayOfValues) {
  1436. // If you passed zero args, we destroy everything
  1437. if (arrayOfValues === undefined)
  1438. return this['destroy'](function() { return true });
  1439. // If you passed an arg, we interpret it as an array of entries to destroy
  1440. if (!arrayOfValues)
  1441. return [];
  1442. return this['destroy'](function (value) {
  1443. return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
  1444. });
  1445. },
  1446. 'indexOf': function (item) {
  1447. var underlyingArray = this();
  1448. return ko.utils.arrayIndexOf(underlyingArray, item);
  1449. },
  1450. 'replace': function(oldItem, newItem) {
  1451. var index = this['indexOf'](oldItem);
  1452. if (index >= 0) {
  1453. this.valueWillMutate();
  1454. this.peek()[index] = newItem;
  1455. this.valueHasMutated();
  1456. }
  1457. }
  1458. };
  1459. // Note that for browsers that don't support proto assignment, the
  1460. // inheritance chain is created manually in the ko.observableArray constructor
  1461. if (ko.utils.canSetPrototype) {
  1462. ko.utils.setPrototypeOf(ko.observableArray['fn'], ko.observable['fn']);
  1463. }
  1464. // Populate ko.observableArray.fn with read/write functions from native arrays
  1465. // Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
  1466. // because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
  1467. ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
  1468. ko.observableArray['fn'][methodName] = function () {
  1469. // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
  1470. // (for consistency with mutating regular observables)
  1471. var underlyingArray = this.peek();
  1472. this.valueWillMutate();
  1473. this.cacheDiffForKnownOperation(underlyingArray, methodName, arguments);
  1474. var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
  1475. this.valueHasMutated();
  1476. // The native sort and reverse methods return a reference to the array, but it makes more sense to return the observable array instead.
  1477. return methodCallResult === underlyingArray ? this : methodCallResult;
  1478. };
  1479. });
  1480. // Populate ko.observableArray.fn with read-only functions from native arrays
  1481. ko.utils.arrayForEach(["slice"], function (methodName) {
  1482. ko.observableArray['fn'][methodName] = function () {
  1483. var underlyingArray = this();
  1484. return underlyingArray[methodName].apply(underlyingArray, arguments);
  1485. };
  1486. });
  1487. ko.exportSymbol('observableArray', ko.observableArray);
  1488. var arrayChangeEventName = 'arrayChange';
  1489. ko.extenders['trackArrayChanges'] = function(target, options) {
  1490. // Use the provided options--each call to trackArrayChanges overwrites the previously set options
  1491. target.compareArrayOptions = {};
  1492. if (options && typeof options == "object") {
  1493. ko.utils.extend(target.compareArrayOptions, options);
  1494. }
  1495. target.compareArrayOptions['sparse'] = true;
  1496. // Only modify the target observable once
  1497. if (target.cacheDiffForKnownOperation) {
  1498. return;
  1499. }
  1500. var trackingChanges = false,
  1501. cachedDiff = null,
  1502. arrayChangeSubscription,
  1503. pendingNotifications = 0,
  1504. underlyingNotifySubscribersFunction,
  1505. underlyingBeforeSubscriptionAddFunction = target.beforeSubscriptionAdd,
  1506. underlyingAfterSubscriptionRemoveFunction = target.afterSubscriptionRemove;
  1507. // Watch "subscribe" calls, and for array change events, ensure change tracking is enabled
  1508. target.beforeSubscriptionAdd = function (event) {
  1509. if (underlyingBeforeSubscriptionAddFunction)
  1510. underlyingBeforeSubscriptionAddFunction.call(target, event);
  1511. if (event === arrayChangeEventName) {
  1512. trackChanges();
  1513. }
  1514. };
  1515. // Watch "dispose" calls, and for array change events, ensure change tracking is disabled when all are disposed
  1516. target.afterSubscriptionRemove = function (event) {
  1517. if (underlyingAfterSubscriptionRemoveFunction)
  1518. underlyingAfterSubscriptionRemoveFunction.call(target, event);
  1519. if (event === arrayChangeEventName && !target.hasSubscriptionsForEvent(arrayChangeEventName)) {
  1520. if (underlyingNotifySubscribersFunction) {
  1521. target['notifySubscribers'] = underlyingNotifySubscribersFunction;
  1522. underlyingNotifySubscribersFunction = undefined;
  1523. }
  1524. arrayChangeSubscription.dispose();
  1525. trackingChanges = false;
  1526. }
  1527. };
  1528. function trackChanges() {
  1529. // Calling 'trackChanges' multiple times is the same as calling it once
  1530. if (trackingChanges) {
  1531. return;
  1532. }
  1533. trackingChanges = true;
  1534. // Intercept "notifySubscribers" to track how many times it was called.
  1535. underlyingNotifySubscribersFunction = target['notifySubscribers'];
  1536. target['notifySubscribers'] = function(valueToNotify, event) {
  1537. if (!event || event === defaultEvent) {
  1538. ++pendingNotifications;
  1539. }
  1540. return underlyingNotifySubscribersFunction.apply(this, arguments);
  1541. };
  1542. // Each time the array changes value, capture a clone so that on the next
  1543. // change it's possible to produce a diff
  1544. var previousContents = [].concat(target.peek() || []);
  1545. cachedDiff = null;
  1546. arrayChangeSubscription = target.subscribe(function(currentContents) {
  1547. // Make a copy of the current contents and ensure it's an array
  1548. currentContents = [].concat(currentContents || []);
  1549. // Compute the diff and issue notifications, but only if someone is listening
  1550. if (target.hasSubscriptionsForEvent(arrayChangeEventName)) {
  1551. var changes = getChanges(previousContents, currentContents);
  1552. }
  1553. // Eliminate references to the old, removed items, so they can be GCed
  1554. previousContents = currentContents;
  1555. cachedDiff = null;
  1556. pendingNotifications = 0;
  1557. if (changes && changes.length) {
  1558. target['notifySubscribers'](changes, arrayChangeEventName);
  1559. }
  1560. });
  1561. }
  1562. function getChanges(previousContents, currentContents) {
  1563. // We try to re-use cached diffs.
  1564. // The scenarios where pendingNotifications > 1 are when using rate-limiting or the Deferred Updates
  1565. // plugin, which without this check would not be compatible with arrayChange notifications. Normally,
  1566. // notifications are issued immediately so we wouldn't be queueing up more than one.
  1567. if (!cachedDiff || pendingNotifications > 1) {
  1568. cachedDiff = ko.utils.compareArrays(previousContents, currentContents, target.compareArrayOptions);
  1569. }
  1570. return cachedDiff;
  1571. }
  1572. target.cacheDiffForKnownOperation = function(rawArray, operationName, args) {
  1573. // Only run if we're currently tracking changes for this observable array
  1574. // and there aren't any pending deferred notifications.
  1575. if (!trackingChanges || pendingNotifications) {
  1576. return;
  1577. }
  1578. var diff = [],
  1579. arrayLength = rawArray.length,
  1580. argsLength = args.length,
  1581. offset = 0;
  1582. function pushDiff(status, value, index) {
  1583. return diff[diff.length] = { 'status': status, 'value': value, 'index': index };
  1584. }
  1585. switch (operationName) {
  1586. case 'push':
  1587. offset = arrayLength;
  1588. case 'unshift':
  1589. for (var index = 0; index < argsLength; index++) {
  1590. pushDiff('added', args[index], offset + index);
  1591. }
  1592. break;
  1593. case 'pop':
  1594. offset = arrayLength - 1;
  1595. case 'shift':
  1596. if (arrayLength) {
  1597. pushDiff('deleted', rawArray[offset], offset);
  1598. }
  1599. break;
  1600. case 'splice':
  1601. // Negative start index means 'from end of array'. After that we clamp to [0...arrayLength].
  1602. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
  1603. var startIndex = Math.min(Math.max(0, args[0] < 0 ? arrayLength + args[0] : args[0]), arrayLength),
  1604. endDeleteIndex = argsLength === 1 ? arrayLength : Math.min(startIndex + (args[1] || 0), arrayLength),
  1605. endAddIndex = startIndex + argsLength - 2,
  1606. endIndex = Math.max(endDeleteIndex, endAddIndex),
  1607. additions = [], deletions = [];
  1608. for (var index = startIndex, argsIndex = 2; index < endIndex; ++index, ++argsIndex) {
  1609. if (index < endDeleteIndex)
  1610. deletions.push(pushDiff('deleted', rawArray[index], index));
  1611. if (index < endAddIndex)
  1612. additions.push(pushDiff('added', args[argsIndex], index));
  1613. }
  1614. ko.utils.findMovesInArrayComparison(deletions, additions);
  1615. break;
  1616. default:
  1617. return;
  1618. }
  1619. cachedDiff = diff;
  1620. };
  1621. };
  1622. var computedState = ko.utils.createSymbolOrString('_state');
  1623. ko.computed = ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
  1624. if (typeof evaluatorFunctionOrOptions === "object") {
  1625. // Single-parameter syntax - everything is on this "options" param
  1626. options = evaluatorFunctionOrOptions;
  1627. } else {
  1628. // Multi-parameter syntax - construct the options according to the params passed
  1629. options = options || {};
  1630. if (evaluatorFunctionOrOptions) {
  1631. options["read"] = evaluatorFunctionOrOptions;
  1632. }
  1633. }
  1634. if (typeof options["read"] != "function")
  1635. throw Error("Pass a function that returns the value of the ko.computed");
  1636. var writeFunction = options["write"];
  1637. var state = {
  1638. latestValue: undefined,
  1639. isStale: true,
  1640. isDirty: true,
  1641. isBeingEvaluated: false,
  1642. suppressDisposalUntilDisposeWhenReturnsFalse: false,
  1643. isDisposed: false,
  1644. pure: false,
  1645. isSleeping: false,
  1646. readFunction: options["read"],
  1647. evaluatorFunctionTarget: evaluatorFunctionTarget || options["owner"],
  1648. disposeWhenNodeIsRemoved: options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
  1649. disposeWhen: options["disposeWhen"] || options.disposeWhen,
  1650. domNodeDisposalCallback: null,
  1651. dependencyTracking: {},
  1652. dependenciesCount: 0,
  1653. evaluationTimeoutInstance: null
  1654. };
  1655. function computedObservable() {
  1656. if (arguments.length > 0) {
  1657. if (typeof writeFunction === "function") {
  1658. // Writing a value
  1659. writeFunction.apply(state.evaluatorFunctionTarget, arguments);
  1660. } else {
  1661. throw new Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");
  1662. }
  1663. return this; // Permits chained assignments
  1664. } else {
  1665. // Reading the value
  1666. ko.dependencyDetection.registerDependency(computedObservable);
  1667. if (state.isDirty || (state.isSleeping && computedObservable.haveDependenciesChanged())) {
  1668. computedObservable.evaluateImmediate();
  1669. }
  1670. return state.latestValue;
  1671. }
  1672. }
  1673. computedObservable[computedState] = state;
  1674. computedObservable.hasWriteFunction = typeof writeFunction === "function";
  1675. // Inherit from 'subscribable'
  1676. if (!ko.utils.canSetPrototype) {
  1677. // 'subscribable' won't be on the prototype chain unless we put it there directly
  1678. ko.utils.extend(computedObservable, ko.subscribable['fn']);
  1679. }
  1680. ko.subscribable['fn'].init(computedObservable);
  1681. // Inherit from 'computed'
  1682. ko.utils.setPrototypeOfOrExtend(computedObservable, computedFn);
  1683. if (options['pure']) {
  1684. state.pure = true;
  1685. state.isSleeping = true; // Starts off sleeping; will awake on the first subscription
  1686. ko.utils.extend(computedObservable, pureComputedOverrides);
  1687. } else if (options['deferEvaluation']) {
  1688. ko.utils.extend(computedObservable, deferEvaluationOverrides);
  1689. }
  1690. if (ko.options['deferUpdates']) {
  1691. ko.extenders['deferred'](computedObservable, true);
  1692. }
  1693. if (DEBUG) {
  1694. // #1731 - Aid debugging by exposing the computed's options
  1695. computedObservable["_options"] = options;
  1696. }
  1697. if (state.disposeWhenNodeIsRemoved) {
  1698. // Since this computed is associated with a DOM node, and we don't want to dispose the computed
  1699. // until the DOM node is *removed* from the document (as opposed to never having been in the document),
  1700. // we'll prevent disposal until "disposeWhen" first returns false.
  1701. state.suppressDisposalUntilDisposeWhenReturnsFalse = true;
  1702. // disposeWhenNodeIsRemoved: true can be used to opt into the "only dispose after first false result"
  1703. // behaviour even if there's no specific node to watch. In that case, clear the option so we don't try
  1704. // to watch for a non-node's disposal. This technique is intended for KO's internal use only and shouldn't
  1705. // be documented or used by application code, as it's likely to change in a future version of KO.
  1706. if (!state.disposeWhenNodeIsRemoved.nodeType) {
  1707. state.disposeWhenNodeIsRemoved = null;
  1708. }
  1709. }
  1710. // Evaluate, unless sleeping or deferEvaluation is true
  1711. if (!state.isSleeping && !options['deferEvaluation']) {
  1712. computedObservable.evaluateImmediate();
  1713. }
  1714. // Attach a DOM node disposal callback so that the computed will be proactively disposed as soon as the node is
  1715. // removed using ko.removeNode. But skip if isActive is false (there will never be any dependencies to dispose).
  1716. if (state.disposeWhenNodeIsRemoved && computedObservable.isActive()) {
  1717. ko.utils.domNodeDisposal.addDisposeCallback(state.disposeWhenNodeIsRemoved, state.domNodeDisposalCallback = function () {
  1718. computedObservable.dispose();
  1719. });
  1720. }
  1721. return computedObservable;
  1722. };
  1723. // Utility function that disposes a given dependencyTracking entry
  1724. function computedDisposeDependencyCallback(id, entryToDispose) {
  1725. if (entryToDispose !== null && entryToDispose.dispose) {
  1726. entryToDispose.dispose();
  1727. }
  1728. }
  1729. // This function gets called each time a dependency is detected while evaluating a computed.
  1730. // It's factored out as a shared function to avoid creating unnecessary function instances during evaluation.
  1731. function computedBeginDependencyDetectionCallback(subscribable, id) {
  1732. var computedObservable = this.computedObservable,
  1733. state = computedObservable[computedState];
  1734. if (!state.isDisposed) {
  1735. if (this.disposalCount && this.disposalCandidates[id]) {
  1736. // Don't want to dispose this subscription, as it's still being used
  1737. computedObservable.addDependencyTracking(id, subscribable, this.disposalCandidates[id]);
  1738. this.disposalCandidates[id] = null; // No need to actually delete the property - disposalCandidates is a transient object anyway
  1739. --this.disposalCount;
  1740. } else if (!state.dependencyTracking[id]) {
  1741. // Brand new subscription - add it
  1742. computedObservable.addDependencyTracking(id, subscribable, state.isSleeping ? { _target: subscribable } : computedObservable.subscribeToDependency(subscribable));
  1743. }
  1744. // If the observable we've accessed has a pending notification, ensure we get notified of the actual final value (bypass equality checks)
  1745. if (subscribable._notificationIsPending) {
  1746. subscribable._notifyNextChangeIfValueIsDifferent();
  1747. }
  1748. }
  1749. }
  1750. var computedFn = {
  1751. "equalityComparer": valuesArePrimitiveAndEqual,
  1752. getDependenciesCount: function () {
  1753. return this[computedState].dependenciesCount;
  1754. },
  1755. addDependencyTracking: function (id, target, trackingObj) {
  1756. if (this[computedState].pure && target === this) {
  1757. throw Error("A 'pure' computed must not be called recursively");
  1758. }
  1759. this[computedState].dependencyTracking[id] = trackingObj;
  1760. trackingObj._order = this[computedState].dependenciesCount++;
  1761. trackingObj._version = target.getVersion();
  1762. },
  1763. haveDependenciesChanged: function () {
  1764. var id, dependency, dependencyTracking = this[computedState].dependencyTracking;
  1765. for (id in dependencyTracking) {
  1766. if (dependencyTracking.hasOwnProperty(id)) {
  1767. dependency = dependencyTracking[id];
  1768. if ((this._evalDelayed && dependency._target._notificationIsPending) || dependency._target.hasChanged(dependency._version)) {
  1769. return true;
  1770. }
  1771. }
  1772. }
  1773. },
  1774. markDirty: function () {
  1775. // Process "dirty" events if we can handle delayed notifications
  1776. if (this._evalDelayed && !this[computedState].isBeingEvaluated) {
  1777. this._evalDelayed(false /*isChange*/);
  1778. }
  1779. },
  1780. isActive: function () {
  1781. var state = this[computedState];
  1782. return state.isDirty || state.dependenciesCount > 0;
  1783. },
  1784. respondToChange: function () {
  1785. // Ignore "change" events if we've already scheduled a delayed notification
  1786. if (!this._notificationIsPending) {
  1787. this.evaluatePossiblyAsync();
  1788. } else if (this[computedState].isDirty) {
  1789. this[computedState].isStale = true;
  1790. }
  1791. },
  1792. subscribeToDependency: function (target) {
  1793. if (target._deferUpdates && !this[computedState].disposeWhenNodeIsRemoved) {
  1794. var dirtySub = target.subscribe(this.markDirty, this, 'dirty'),
  1795. changeSub = target.subscribe(this.respondToChange, this);
  1796. return {
  1797. _target: target,
  1798. dispose: function () {
  1799. dirtySub.dispose();
  1800. changeSub.dispose();
  1801. }
  1802. };
  1803. } else {
  1804. return target.subscribe(this.evaluatePossiblyAsync, this);
  1805. }
  1806. },
  1807. evaluatePossiblyAsync: function () {
  1808. var computedObservable = this,
  1809. throttleEvaluationTimeout = computedObservable['throttleEvaluation'];
  1810. if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
  1811. clearTimeout(this[computedState].evaluationTimeoutInstance);
  1812. this[computedState].evaluationTimeoutInstance = ko.utils.setTimeout(function () {
  1813. computedObservable.evaluateImmediate(true /*notifyChange*/);
  1814. }, throttleEvaluationTimeout);
  1815. } else if (computedObservable._evalDelayed) {
  1816. computedObservable._evalDelayed(true /*isChange*/);
  1817. } else {
  1818. computedObservable.evaluateImmediate(true /*notifyChange*/);
  1819. }
  1820. },
  1821. evaluateImmediate: function (notifyChange) {
  1822. var computedObservable = this,
  1823. state = computedObservable[computedState],
  1824. disposeWhen = state.disposeWhen,
  1825. changed = false;
  1826. if (state.isBeingEvaluated) {
  1827. // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
  1828. // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
  1829. // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
  1830. // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
  1831. return;
  1832. }
  1833. // Do not evaluate (and possibly capture new dependencies) if disposed
  1834. if (state.isDisposed) {
  1835. return;
  1836. }
  1837. if (state.disposeWhenNodeIsRemoved && !ko.utils.domNodeIsAttachedToDocument(state.disposeWhenNodeIsRemoved) || disposeWhen && disposeWhen()) {
  1838. // See comment above about suppressDisposalUntilDisposeWhenReturnsFalse
  1839. if (!state.suppressDisposalUntilDisposeWhenReturnsFalse) {
  1840. computedObservable.dispose();
  1841. return;
  1842. }
  1843. } else {
  1844. // It just did return false, so we can stop suppressing now
  1845. state.suppressDisposalUntilDisposeWhenReturnsFalse = false;
  1846. }
  1847. state.isBeingEvaluated = true;
  1848. try {
  1849. changed = this.evaluateImmediate_CallReadWithDependencyDetection(notifyChange);
  1850. } finally {
  1851. state.isBeingEvaluated = false;
  1852. }
  1853. if (!state.dependenciesCount) {
  1854. computedObservable.dispose();
  1855. }
  1856. return changed;
  1857. },
  1858. evaluateImmediate_CallReadWithDependencyDetection: function (notifyChange) {
  1859. // This function is really just part of the evaluateImmediate logic. You would never call it from anywhere else.
  1860. // Factoring it out into a separate function means it can be independent of the try/catch block in evaluateImmediate,
  1861. // which contributes to saving about 40% off the CPU overhead of computed evaluation (on V8 at least).
  1862. var computedObservable = this,
  1863. state = computedObservable[computedState],
  1864. changed = false;
  1865. // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
  1866. // Then, during evaluation, we cross off any that are in fact still being used.
  1867. var isInitial = state.pure ? undefined : !state.dependenciesCount, // If we're evaluating when there are no previous dependencies, it must be the first time
  1868. dependencyDetectionContext = {
  1869. computedObservable: computedObservable,
  1870. disposalCandidates: state.dependencyTracking,
  1871. disposalCount: state.dependenciesCount
  1872. };
  1873. ko.dependencyDetection.begin({
  1874. callbackTarget: dependencyDetectionContext,
  1875. callback: computedBeginDependencyDetectionCallback,
  1876. computed: computedObservable,
  1877. isInitial: isInitial
  1878. });
  1879. state.dependencyTracking = {};
  1880. state.dependenciesCount = 0;
  1881. var newValue = this.evaluateImmediate_CallReadThenEndDependencyDetection(state, dependencyDetectionContext);
  1882. if (computedObservable.isDifferent(state.latestValue, newValue)) {
  1883. if (!state.isSleeping) {
  1884. computedObservable["notifySubscribers"](state.latestValue, "beforeChange");
  1885. }
  1886. state.latestValue = newValue;
  1887. if (DEBUG) computedObservable._latestValue = newValue;
  1888. if (state.isSleeping) {
  1889. computedObservable.updateVersion();
  1890. } else if (notifyChange) {
  1891. computedObservable["notifySubscribers"](state.latestValue);
  1892. }
  1893. changed = true;
  1894. }
  1895. if (isInitial) {
  1896. computedObservable["notifySubscribers"](state.latestValue, "awake");
  1897. }
  1898. return changed;
  1899. },
  1900. evaluateImmediate_CallReadThenEndDependencyDetection: function (state, dependencyDetectionContext) {
  1901. // This function is really part of the evaluateImmediate_CallReadWithDependencyDetection logic.
  1902. // You'd never call it from anywhere else. Factoring it out means that evaluateImmediate_CallReadWithDependencyDetection
  1903. // can be independent of try/finally blocks, which contributes to saving about 40% off the CPU
  1904. // overhead of computed evaluation (on V8 at least).
  1905. try {
  1906. var readFunction = state.readFunction;
  1907. return state.evaluatorFunctionTarget ? readFunction.call(state.evaluatorFunctionTarget) : readFunction();
  1908. } finally {
  1909. ko.dependencyDetection.end();
  1910. // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
  1911. if (dependencyDetectionContext.disposalCount && !state.isSleeping) {
  1912. ko.utils.objectForEach(dependencyDetectionContext.disposalCandidates, computedDisposeDependencyCallback);
  1913. }
  1914. state.isStale = state.isDirty = false;
  1915. }
  1916. },
  1917. peek: function (evaluate) {
  1918. // By default, peek won't re-evaluate, except while the computed is sleeping or to get the initial value when "deferEvaluation" is set.
  1919. // Pass in true to evaluate if needed.
  1920. var state = this[computedState];
  1921. if ((state.isDirty && (evaluate || !state.dependenciesCount)) || (state.isSleeping && this.haveDependenciesChanged())) {
  1922. this.evaluateImmediate();
  1923. }
  1924. return state.latestValue;
  1925. },
  1926. limit: function (limitFunction) {
  1927. // Override the limit function with one that delays evaluation as well
  1928. ko.subscribable['fn'].limit.call(this, limitFunction);
  1929. this._evalIfChanged = function () {
  1930. if (this[computedState].isStale) {
  1931. this.evaluateImmediate();
  1932. } else {
  1933. this[computedState].isDirty = false;
  1934. }
  1935. return this[computedState].latestValue;
  1936. };
  1937. this._evalDelayed = function (isChange) {
  1938. this._limitBeforeChange(this[computedState].latestValue);
  1939. // Mark as dirty
  1940. this[computedState].isDirty = true;
  1941. if (isChange) {
  1942. this[computedState].isStale = true;
  1943. }
  1944. // Pass the observable to the "limit" code, which will evaluate it when
  1945. // it's time to do the notification.
  1946. this._limitChange(this);
  1947. };
  1948. },
  1949. dispose: function () {
  1950. var state = this[computedState];
  1951. if (!state.isSleeping && state.dependencyTracking) {
  1952. ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) {
  1953. if (dependency.dispose)
  1954. dependency.dispose();
  1955. });
  1956. }
  1957. if (state.disposeWhenNodeIsRemoved && state.domNodeDisposalCallback) {
  1958. ko.utils.domNodeDisposal.removeDisposeCallback(state.disposeWhenNodeIsRemoved, state.domNodeDisposalCallback);
  1959. }
  1960. state.dependencyTracking = null;
  1961. state.dependenciesCount = 0;
  1962. state.isDisposed = true;
  1963. state.isStale = false;
  1964. state.isDirty = false;
  1965. state.isSleeping = false;
  1966. state.disposeWhenNodeIsRemoved = null;
  1967. }
  1968. };
  1969. var pureComputedOverrides = {
  1970. beforeSubscriptionAdd: function (event) {
  1971. // If asleep, wake up the computed by subscribing to any dependencies.
  1972. var computedObservable = this,
  1973. state = computedObservable[computedState];
  1974. if (!state.isDisposed && state.isSleeping && event == 'change') {
  1975. state.isSleeping = false;
  1976. if (state.isStale || computedObservable.haveDependenciesChanged()) {
  1977. state.dependencyTracking = null;
  1978. state.dependenciesCount = 0;
  1979. if (computedObservable.evaluateImmediate()) {
  1980. computedObservable.updateVersion();
  1981. }
  1982. } else {
  1983. // First put the dependencies in order
  1984. var dependeciesOrder = [];
  1985. ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) {
  1986. dependeciesOrder[dependency._order] = id;
  1987. });
  1988. // Next, subscribe to each one
  1989. ko.utils.arrayForEach(dependeciesOrder, function (id, order) {
  1990. var dependency = state.dependencyTracking[id],
  1991. subscription = computedObservable.subscribeToDependency(dependency._target);
  1992. subscription._order = order;
  1993. subscription._version = dependency._version;
  1994. state.dependencyTracking[id] = subscription;
  1995. });
  1996. }
  1997. if (!state.isDisposed) { // test since evaluating could trigger disposal
  1998. computedObservable["notifySubscribers"](state.latestValue, "awake");
  1999. }
  2000. }
  2001. },
  2002. afterSubscriptionRemove: function (event) {
  2003. var state = this[computedState];
  2004. if (!state.isDisposed && event == 'change' && !this.hasSubscriptionsForEvent('change')) {
  2005. ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) {
  2006. if (dependency.dispose) {
  2007. state.dependencyTracking[id] = {
  2008. _target: dependency._target,
  2009. _order: dependency._order,
  2010. _version: dependency._version
  2011. };
  2012. dependency.dispose();
  2013. }
  2014. });
  2015. state.isSleeping = true;
  2016. this["notifySubscribers"](undefined, "asleep");
  2017. }
  2018. },
  2019. getVersion: function () {
  2020. // Because a pure computed is not automatically updated while it is sleeping, we can't
  2021. // simply return the version number. Instead, we check if any of the dependencies have
  2022. // changed and conditionally re-evaluate the computed observable.
  2023. var state = this[computedState];
  2024. if (state.isSleeping && (state.isStale || this.haveDependenciesChanged())) {
  2025. this.evaluateImmediate();
  2026. }
  2027. return ko.subscribable['fn'].getVersion.call(this);
  2028. }
  2029. };
  2030. var deferEvaluationOverrides = {
  2031. beforeSubscriptionAdd: function (event) {
  2032. // This will force a computed with deferEvaluation to evaluate when the first subscription is registered.
  2033. if (event == 'change' || event == 'beforeChange') {
  2034. this.peek();
  2035. }
  2036. }
  2037. };
  2038. // Note that for browsers that don't support proto assignment, the
  2039. // inheritance chain is created manually in the ko.computed constructor
  2040. if (ko.utils.canSetPrototype) {
  2041. ko.utils.setPrototypeOf(computedFn, ko.subscribable['fn']);
  2042. }
  2043. // Set the proto chain values for ko.hasPrototype
  2044. var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
  2045. ko.computed[protoProp] = ko.observable;
  2046. computedFn[protoProp] = ko.computed;
  2047. ko.isComputed = function (instance) {
  2048. return ko.hasPrototype(instance, ko.computed);
  2049. };
  2050. ko.isPureComputed = function (instance) {
  2051. return ko.hasPrototype(instance, ko.computed)
  2052. && instance[computedState] && instance[computedState].pure;
  2053. };
  2054. ko.exportSymbol('computed', ko.computed);
  2055. ko.exportSymbol('dependentObservable', ko.computed); // export ko.dependentObservable for backwards compatibility (1.x)
  2056. ko.exportSymbol('isComputed', ko.isComputed);
  2057. ko.exportSymbol('isPureComputed', ko.isPureComputed);
  2058. ko.exportSymbol('computed.fn', computedFn);
  2059. ko.exportProperty(computedFn, 'peek', computedFn.peek);
  2060. ko.exportProperty(computedFn, 'dispose', computedFn.dispose);
  2061. ko.exportProperty(computedFn, 'isActive', computedFn.isActive);
  2062. ko.exportProperty(computedFn, 'getDependenciesCount', computedFn.getDependenciesCount);
  2063. ko.pureComputed = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget) {
  2064. if (typeof evaluatorFunctionOrOptions === 'function') {
  2065. return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget, {'pure':true});
  2066. } else {
  2067. evaluatorFunctionOrOptions = ko.utils.extend({}, evaluatorFunctionOrOptions); // make a copy of the parameter object
  2068. evaluatorFunctionOrOptions['pure'] = true;
  2069. return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget);
  2070. }
  2071. }
  2072. ko.exportSymbol('pureComputed', ko.pureComputed);
  2073. (function() {
  2074. var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
  2075. ko.toJS = function(rootObject) {
  2076. if (arguments.length == 0)
  2077. throw new Error("When calling ko.toJS, pass the object you want to convert.");
  2078. // We just unwrap everything at every level in the object graph
  2079. return mapJsObjectGraph(rootObject, function(valueToMap) {
  2080. // Loop because an observable's value might in turn be another observable wrapper
  2081. for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
  2082. valueToMap = valueToMap();
  2083. return valueToMap;
  2084. });
  2085. };
  2086. ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
  2087. var plainJavaScriptObject = ko.toJS(rootObject);
  2088. return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
  2089. };
  2090. function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
  2091. visitedObjects = visitedObjects || new objectLookup();
  2092. rootObject = mapInputCallback(rootObject);
  2093. var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof RegExp)) && (!(rootObject instanceof Date)) && (!(rootObject instanceof String)) && (!(rootObject instanceof Number)) && (!(rootObject instanceof Boolean));
  2094. if (!canHaveProperties)
  2095. return rootObject;
  2096. var outputProperties = rootObject instanceof Array ? [] : {};
  2097. visitedObjects.save(rootObject, outputProperties);
  2098. visitPropertiesOrArrayEntries(rootObject, function(indexer) {
  2099. var propertyValue = mapInputCallback(rootObject[indexer]);
  2100. switch (typeof propertyValue) {
  2101. case "boolean":
  2102. case "number":
  2103. case "string":
  2104. case "function":
  2105. outputProperties[indexer] = propertyValue;
  2106. break;
  2107. case "object":
  2108. case "undefined":
  2109. var previouslyMappedValue = visitedObjects.get(propertyValue);
  2110. outputProperties[indexer] = (previouslyMappedValue !== undefined)
  2111. ? previouslyMappedValue
  2112. : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
  2113. break;
  2114. }
  2115. });
  2116. return outputProperties;
  2117. }
  2118. function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
  2119. if (rootObject instanceof Array) {
  2120. for (var i = 0; i < rootObject.length; i++)
  2121. visitorCallback(i);
  2122. // For arrays, also respect toJSON property for custom mappings (fixes #278)
  2123. if (typeof rootObject['toJSON'] == 'function')
  2124. visitorCallback('toJSON');
  2125. } else {
  2126. for (var propertyName in rootObject) {
  2127. visitorCallback(propertyName);
  2128. }
  2129. }
  2130. };
  2131. function objectLookup() {
  2132. this.keys = [];
  2133. this.values = [];
  2134. };
  2135. objectLookup.prototype = {
  2136. constructor: objectLookup,
  2137. save: function(key, value) {
  2138. var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
  2139. if (existingIndex >= 0)
  2140. this.values[existingIndex] = value;
  2141. else {
  2142. this.keys.push(key);
  2143. this.values.push(value);
  2144. }
  2145. },
  2146. get: function(key) {
  2147. var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
  2148. return (existingIndex >= 0) ? this.values[existingIndex] : undefined;
  2149. }
  2150. };
  2151. })();
  2152. ko.exportSymbol('toJS', ko.toJS);
  2153. ko.exportSymbol('toJSON', ko.toJSON);
  2154. (function () {
  2155. var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
  2156. // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
  2157. // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
  2158. // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
  2159. ko.selectExtensions = {
  2160. readValue : function(element) {
  2161. switch (ko.utils.tagNameLower(element)) {
  2162. case 'option':
  2163. if (element[hasDomDataExpandoProperty] === true)
  2164. return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
  2165. return ko.utils.ieVersion <= 7
  2166. ? (element.getAttributeNode('value') && element.getAttributeNode('value').specified ? element.value : element.text)
  2167. : element.value;
  2168. case 'select':
  2169. return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
  2170. default:
  2171. return element.value;
  2172. }
  2173. },
  2174. writeValue: function(element, value, allowUnset) {
  2175. switch (ko.utils.tagNameLower(element)) {
  2176. case 'option':
  2177. switch(typeof value) {
  2178. case "string":
  2179. ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
  2180. if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
  2181. delete element[hasDomDataExpandoProperty];
  2182. }
  2183. element.value = value;
  2184. break;
  2185. default:
  2186. // Store arbitrary object using DomData
  2187. ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
  2188. element[hasDomDataExpandoProperty] = true;
  2189. // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
  2190. element.value = typeof value === "number" ? value : "";
  2191. break;
  2192. }
  2193. break;
  2194. case 'select':
  2195. if (value === "" || value === null) // A blank string or null value will select the caption
  2196. value = undefined;
  2197. var selection = -1;
  2198. for (var i = 0, n = element.options.length, optionValue; i < n; ++i) {
  2199. optionValue = ko.selectExtensions.readValue(element.options[i]);
  2200. // Include special check to handle selecting a caption with a blank string value
  2201. if (optionValue == value || (optionValue == "" && value === undefined)) {
  2202. selection = i;
  2203. break;
  2204. }
  2205. }
  2206. if (allowUnset || selection >= 0 || (value === undefined && element.size > 1)) {
  2207. element.selectedIndex = selection;
  2208. }
  2209. break;
  2210. default:
  2211. if ((value === null) || (value === undefined))
  2212. value = "";
  2213. element.value = value;
  2214. break;
  2215. }
  2216. }
  2217. };
  2218. })();
  2219. ko.exportSymbol('selectExtensions', ko.selectExtensions);
  2220. ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
  2221. ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
  2222. ko.expressionRewriting = (function () {
  2223. var javaScriptReservedWords = ["true", "false", "null", "undefined"];
  2224. // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
  2225. // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
  2226. // This also will not properly handle nested brackets (e.g., obj1[obj2['prop']]; see #911).
  2227. var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
  2228. function getWriteableValue(expression) {
  2229. if (ko.utils.arrayIndexOf(javaScriptReservedWords, expression) >= 0)
  2230. return false;
  2231. var match = expression.match(javaScriptAssignmentTarget);
  2232. return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
  2233. }
  2234. // The following regular expressions will be used to split an object-literal string into tokens
  2235. // These two match strings, either with double quotes or single quotes
  2236. var stringDouble = '"(?:[^"\\\\]|\\\\.)*"',
  2237. stringSingle = "'(?:[^'\\\\]|\\\\.)*'",
  2238. // Matches a regular expression (text enclosed by slashes), but will also match sets of divisions
  2239. // as a regular expression (this is handled by the parsing loop below).
  2240. stringRegexp = '/(?:[^/\\\\]|\\\\.)*/\w*',
  2241. // These characters have special meaning to the parser and must not appear in the middle of a
  2242. // token, except as part of a string.
  2243. specials = ',"\'{}()/:[\\]',
  2244. // Match text (at least two characters) that does not contain any of the above special characters,
  2245. // although some of the special characters are allowed to start it (all but the colon and comma).
  2246. // The text can contain spaces, but leading or trailing spaces are skipped.
  2247. everyThingElse = '[^\\s:,/][^' + specials + ']*[^\\s' + specials + ']',
  2248. // Match any non-space character not matched already. This will match colons and commas, since they're
  2249. // not matched by "everyThingElse", but will also match any other single character that wasn't already
  2250. // matched (for example: in "a: 1, b: 2", each of the non-space characters will be matched by oneNotSpace).
  2251. oneNotSpace = '[^\\s]',
  2252. // Create the actual regular expression by or-ing the above strings. The order is important.
  2253. bindingToken = RegExp(stringDouble + '|' + stringSingle + '|' + stringRegexp + '|' + everyThingElse + '|' + oneNotSpace, 'g'),
  2254. // Match end of previous token to determine whether a slash is a division or regex.
  2255. divisionLookBehind = /[\])"'A-Za-z0-9_$]+$/,
  2256. keywordRegexLookBehind = {'in':1,'return':1,'typeof':1};
  2257. function parseObjectLiteral(objectLiteralString) {
  2258. // Trim leading and trailing spaces from the string
  2259. var str = ko.utils.stringTrim(objectLiteralString);
  2260. // Trim braces '{' surrounding the whole object literal
  2261. if (str.charCodeAt(0) === 123) str = str.slice(1, -1);
  2262. // Split into tokens
  2263. var result = [], toks = str.match(bindingToken), key, values = [], depth = 0;
  2264. if (toks) {
  2265. // Append a comma so that we don't need a separate code block to deal with the last item
  2266. toks.push(',');
  2267. for (var i = 0, tok; tok = toks[i]; ++i) {
  2268. var c = tok.charCodeAt(0);
  2269. // A comma signals the end of a key/value pair if depth is zero
  2270. if (c === 44) { // ","
  2271. if (depth <= 0) {
  2272. result.push((key && values.length) ? {key: key, value: values.join('')} : {'unknown': key || values.join('')});
  2273. key = depth = 0;
  2274. values = [];
  2275. continue;
  2276. }
  2277. // Simply skip the colon that separates the name and value
  2278. } else if (c === 58) { // ":"
  2279. if (!depth && !key && values.length === 1) {
  2280. key = values.pop();
  2281. continue;
  2282. }
  2283. // A set of slashes is initially matched as a regular expression, but could be division
  2284. } else if (c === 47 && i && tok.length > 1) { // "/"
  2285. // Look at the end of the previous token to determine if the slash is actually division
  2286. var match = toks[i-1].match(divisionLookBehind);
  2287. if (match && !keywordRegexLookBehind[match[0]]) {
  2288. // The slash is actually a division punctuator; re-parse the remainder of the string (not including the slash)
  2289. str = str.substr(str.indexOf(tok) + 1);
  2290. toks = str.match(bindingToken);
  2291. toks.push(',');
  2292. i = -1;
  2293. // Continue with just the slash
  2294. tok = '/';
  2295. }
  2296. // Increment depth for parentheses, braces, and brackets so that interior commas are ignored
  2297. } else if (c === 40 || c === 123 || c === 91) { // '(', '{', '['
  2298. ++depth;
  2299. } else if (c === 41 || c === 125 || c === 93) { // ')', '}', ']'
  2300. --depth;
  2301. // The key will be the first token; if it's a string, trim the quotes
  2302. } else if (!key && !values.length && (c === 34 || c === 39)) { // '"', "'"
  2303. tok = tok.slice(1, -1);
  2304. }
  2305. values.push(tok);
  2306. }
  2307. }
  2308. return result;
  2309. }
  2310. // Two-way bindings include a write function that allow the handler to update the value even if it's not an observable.
  2311. var twoWayBindings = {};
  2312. function preProcessBindings(bindingsStringOrKeyValueArray, bindingOptions) {
  2313. bindingOptions = bindingOptions || {};
  2314. function processKeyValue(key, val) {
  2315. var writableVal;
  2316. function callPreprocessHook(obj) {
  2317. return (obj && obj['preprocess']) ? (val = obj['preprocess'](val, key, processKeyValue)) : true;
  2318. }
  2319. if (!bindingParams) {
  2320. if (!callPreprocessHook(ko['getBindingHandler'](key)))
  2321. return;
  2322. if (twoWayBindings[key] && (writableVal = getWriteableValue(val))) {
  2323. // For two-way bindings, provide a write method in case the value
  2324. // isn't a writable observable.
  2325. propertyAccessorResultStrings.push("'" + key + "':function(_z){" + writableVal + "=_z}");
  2326. }
  2327. }
  2328. // Values are wrapped in a function so that each value can be accessed independently
  2329. if (makeValueAccessors) {
  2330. val = 'function(){return ' + val + ' }';
  2331. }
  2332. resultStrings.push("'" + key + "':" + val);
  2333. }
  2334. var resultStrings = [],
  2335. propertyAccessorResultStrings = [],
  2336. makeValueAccessors = bindingOptions['valueAccessors'],
  2337. bindingParams = bindingOptions['bindingParams'],
  2338. keyValueArray = typeof bindingsStringOrKeyValueArray === "string" ?
  2339. parseObjectLiteral(bindingsStringOrKeyValueArray) : bindingsStringOrKeyValueArray;
  2340. ko.utils.arrayForEach(keyValueArray, function(keyValue) {
  2341. processKeyValue(keyValue.key || keyValue['unknown'], keyValue.value);
  2342. });
  2343. if (propertyAccessorResultStrings.length)
  2344. processKeyValue('_ko_property_writers', "{" + propertyAccessorResultStrings.join(",") + " }");
  2345. return resultStrings.join(",");
  2346. }
  2347. return {
  2348. bindingRewriteValidators: [],
  2349. twoWayBindings: twoWayBindings,
  2350. parseObjectLiteral: parseObjectLiteral,
  2351. preProcessBindings: preProcessBindings,
  2352. keyValueArrayContainsKey: function(keyValueArray, key) {
  2353. for (var i = 0; i < keyValueArray.length; i++)
  2354. if (keyValueArray[i]['key'] == key)
  2355. return true;
  2356. return false;
  2357. },
  2358. // Internal, private KO utility for updating model properties from within bindings
  2359. // property: If the property being updated is (or might be) an observable, pass it here
  2360. // If it turns out to be a writable observable, it will be written to directly
  2361. // allBindings: An object with a get method to retrieve bindings in the current execution context.
  2362. // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
  2363. // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
  2364. // value: The value to be written
  2365. // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
  2366. // it is !== existing value on that writable observable
  2367. writeValueToProperty: function(property, allBindings, key, value, checkIfDifferent) {
  2368. if (!property || !ko.isObservable(property)) {
  2369. var propWriters = allBindings.get('_ko_property_writers');
  2370. if (propWriters && propWriters[key])
  2371. propWriters[key](value);
  2372. } else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {
  2373. property(value);
  2374. }
  2375. }
  2376. };
  2377. })();
  2378. ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
  2379. ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
  2380. ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
  2381. ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
  2382. // Making bindings explicitly declare themselves as "two way" isn't ideal in the long term (it would be better if
  2383. // all bindings could use an official 'property writer' API without needing to declare that they might). However,
  2384. // since this is not, and has never been, a public API (_ko_property_writers was never documented), it's acceptable
  2385. // as an internal implementation detail in the short term.
  2386. // For those developers who rely on _ko_property_writers in their custom bindings, we expose _twoWayBindings as an
  2387. // undocumented feature that makes it relatively easy to upgrade to KO 3.0. However, this is still not an official
  2388. // public API, and we reserve the right to remove it at any time if we create a real public property writers API.
  2389. ko.exportSymbol('expressionRewriting._twoWayBindings', ko.expressionRewriting.twoWayBindings);
  2390. // For backward compatibility, define the following aliases. (Previously, these function names were misleading because
  2391. // they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
  2392. ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
  2393. ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);
  2394. (function() {
  2395. // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
  2396. // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
  2397. // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
  2398. // of that virtual hierarchy
  2399. //
  2400. // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
  2401. // without having to scatter special cases all over the binding and templating code.
  2402. // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
  2403. // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
  2404. // So, use node.text where available, and node.nodeValue elsewhere
  2405. var commentNodesHaveTextProperty = document && document.createComment("test").text === "<!--test-->";
  2406. var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/;
  2407. var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
  2408. var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
  2409. function isStartComment(node) {
  2410. return (node.nodeType == 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
  2411. }
  2412. function isEndComment(node) {
  2413. return (node.nodeType == 8) && endCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
  2414. }
  2415. function getVirtualChildren(startComment, allowUnbalanced) {
  2416. var currentNode = startComment;
  2417. var depth = 1;
  2418. var children = [];
  2419. while (currentNode = currentNode.nextSibling) {
  2420. if (isEndComment(currentNode)) {
  2421. depth--;
  2422. if (depth === 0)
  2423. return children;
  2424. }
  2425. children.push(currentNode);
  2426. if (isStartComment(currentNode))
  2427. depth++;
  2428. }
  2429. if (!allowUnbalanced)
  2430. throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
  2431. return null;
  2432. }
  2433. function getMatchingEndComment(startComment, allowUnbalanced) {
  2434. var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
  2435. if (allVirtualChildren) {
  2436. if (allVirtualChildren.length > 0)
  2437. return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
  2438. return startComment.nextSibling;
  2439. } else
  2440. return null; // Must have no matching end comment, and allowUnbalanced is true
  2441. }
  2442. function getUnbalancedChildTags(node) {
  2443. // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
  2444. // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
  2445. var childNode = node.firstChild, captureRemaining = null;
  2446. if (childNode) {
  2447. do {
  2448. if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
  2449. captureRemaining.push(childNode);
  2450. else if (isStartComment(childNode)) {
  2451. var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
  2452. if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
  2453. childNode = matchingEndComment;
  2454. else
  2455. captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
  2456. } else if (isEndComment(childNode)) {
  2457. captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
  2458. }
  2459. } while (childNode = childNode.nextSibling);
  2460. }
  2461. return captureRemaining;
  2462. }
  2463. ko.virtualElements = {
  2464. allowedBindings: {},
  2465. childNodes: function(node) {
  2466. return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
  2467. },
  2468. emptyNode: function(node) {
  2469. if (!isStartComment(node))
  2470. ko.utils.emptyDomNode(node);
  2471. else {
  2472. var virtualChildren = ko.virtualElements.childNodes(node);
  2473. for (var i = 0, j = virtualChildren.length; i < j; i++)
  2474. ko.removeNode(virtualChildren[i]);
  2475. }
  2476. },
  2477. setDomNodeChildren: function(node, childNodes) {
  2478. if (!isStartComment(node))
  2479. ko.utils.setDomNodeChildren(node, childNodes);
  2480. else {
  2481. ko.virtualElements.emptyNode(node);
  2482. var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
  2483. for (var i = 0, j = childNodes.length; i < j; i++)
  2484. endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
  2485. }
  2486. },
  2487. prepend: function(containerNode, nodeToPrepend) {
  2488. if (!isStartComment(containerNode)) {
  2489. if (containerNode.firstChild)
  2490. containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
  2491. else
  2492. containerNode.appendChild(nodeToPrepend);
  2493. } else {
  2494. // Start comments must always have a parent and at least one following sibling (the end comment)
  2495. containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
  2496. }
  2497. },
  2498. insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
  2499. if (!insertAfterNode) {
  2500. ko.virtualElements.prepend(containerNode, nodeToInsert);
  2501. } else if (!isStartComment(containerNode)) {
  2502. // Insert after insertion point
  2503. if (insertAfterNode.nextSibling)
  2504. containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
  2505. else
  2506. containerNode.appendChild(nodeToInsert);
  2507. } else {
  2508. // Children of start comments must always have a parent and at least one following sibling (the end comment)
  2509. containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
  2510. }
  2511. },
  2512. firstChild: function(node) {
  2513. if (!isStartComment(node))
  2514. return node.firstChild;
  2515. if (!node.nextSibling || isEndComment(node.nextSibling))
  2516. return null;
  2517. return node.nextSibling;
  2518. },
  2519. nextSibling: function(node) {
  2520. if (isStartComment(node))
  2521. node = getMatchingEndComment(node);
  2522. if (node.nextSibling && isEndComment(node.nextSibling))
  2523. return null;
  2524. return node.nextSibling;
  2525. },
  2526. hasBindingValue: isStartComment,
  2527. virtualNodeBindingValue: function(node) {
  2528. var regexMatch = (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
  2529. return regexMatch ? regexMatch[1] : null;
  2530. },
  2531. normaliseVirtualElementDomStructure: function(elementVerified) {
  2532. // Workaround for https://github.com/SteveSanderson/knockout/issues/155
  2533. // (IE <= 8 or IE 9 quirks mode parses your HTML weirdly, treating closing </li> tags as if they don't exist, thereby moving comment nodes
  2534. // that are direct descendants of <ul> into the preceding <li>)
  2535. if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
  2536. return;
  2537. // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
  2538. // must be intended to appear *after* that child, so move them there.
  2539. var childNode = elementVerified.firstChild;
  2540. if (childNode) {
  2541. do {
  2542. if (childNode.nodeType === 1) {
  2543. var unbalancedTags = getUnbalancedChildTags(childNode);
  2544. if (unbalancedTags) {
  2545. // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
  2546. var nodeToInsertBefore = childNode.nextSibling;
  2547. for (var i = 0; i < unbalancedTags.length; i++) {
  2548. if (nodeToInsertBefore)
  2549. elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
  2550. else
  2551. elementVerified.appendChild(unbalancedTags[i]);
  2552. }
  2553. }
  2554. }
  2555. } while (childNode = childNode.nextSibling);
  2556. }
  2557. }
  2558. };
  2559. })();
  2560. ko.exportSymbol('virtualElements', ko.virtualElements);
  2561. ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
  2562. ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
  2563. //ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
  2564. ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
  2565. //ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
  2566. ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
  2567. ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
  2568. (function() {
  2569. var defaultBindingAttributeName = "data-bind";
  2570. ko.bindingProvider = function() {
  2571. this.bindingCache = {};
  2572. };
  2573. ko.utils.extend(ko.bindingProvider.prototype, {
  2574. 'nodeHasBindings': function(node) {
  2575. switch (node.nodeType) {
  2576. case 1: // Element
  2577. return node.getAttribute(defaultBindingAttributeName) != null
  2578. || ko.components['getComponentNameForNode'](node);
  2579. case 8: // Comment node
  2580. return ko.virtualElements.hasBindingValue(node);
  2581. default: return false;
  2582. }
  2583. },
  2584. 'getBindings': function(node, bindingContext) {
  2585. var bindingsString = this['getBindingsString'](node, bindingContext),
  2586. parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
  2587. return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ false);
  2588. },
  2589. 'getBindingAccessors': function(node, bindingContext) {
  2590. var bindingsString = this['getBindingsString'](node, bindingContext),
  2591. parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node, { 'valueAccessors': true }) : null;
  2592. return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ true);
  2593. },
  2594. // The following function is only used internally by this default provider.
  2595. // It's not part of the interface definition for a general binding provider.
  2596. 'getBindingsString': function(node, bindingContext) {
  2597. switch (node.nodeType) {
  2598. case 1: return node.getAttribute(defaultBindingAttributeName); // Element
  2599. case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
  2600. default: return null;
  2601. }
  2602. },
  2603. // The following function is only used internally by this default provider.
  2604. // It's not part of the interface definition for a general binding provider.
  2605. 'parseBindingsString': function(bindingsString, bindingContext, node, options) {
  2606. try {
  2607. var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache, options);
  2608. return bindingFunction(bindingContext, node);
  2609. } catch (ex) {
  2610. ex.message = "Unable to parse bindings.\nBindings value: " + bindingsString + "\nMessage: " + ex.message;
  2611. throw ex;
  2612. }
  2613. }
  2614. });
  2615. ko.bindingProvider['instance'] = new ko.bindingProvider();
  2616. function createBindingsStringEvaluatorViaCache(bindingsString, cache, options) {
  2617. var cacheKey = bindingsString + (options && options['valueAccessors'] || '');
  2618. return cache[cacheKey]
  2619. || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, options));
  2620. }
  2621. function createBindingsStringEvaluator(bindingsString, options) {
  2622. // Build the source for a function that evaluates "expression"
  2623. // For each scope variable, add an extra level of "with" nesting
  2624. // Example result: with(sc1) { with(sc0) { return (expression) } }
  2625. var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString, options),
  2626. functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
  2627. return new Function("$context", "$element", functionBody);
  2628. }
  2629. })();
  2630. ko.exportSymbol('bindingProvider', ko.bindingProvider);
  2631. (function () {
  2632. ko.bindingHandlers = {};
  2633. // The following element types will not be recursed into during binding.
  2634. var bindingDoesNotRecurseIntoElementTypes = {
  2635. // Don't want bindings that operate on text nodes to mutate <script> and <textarea> contents,
  2636. // because it's unexpected and a potential XSS issue.
  2637. // Also bindings should not operate on <template> elements since this breaks in Internet Explorer
  2638. // and because such elements' contents are always intended to be bound in a different context
  2639. // from where they appear in the document.
  2640. 'script': true,
  2641. 'textarea': true,
  2642. 'template': true
  2643. };
  2644. // Use an overridable method for retrieving binding handlers so that a plugins may support dynamically created handlers
  2645. ko['getBindingHandler'] = function(bindingKey) {
  2646. return ko.bindingHandlers[bindingKey];
  2647. };
  2648. // The ko.bindingContext constructor is only called directly to create the root context. For child
  2649. // contexts, use bindingContext.createChildContext or bindingContext.extend.
  2650. ko.bindingContext = function(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback, options) {
  2651. // The binding context object includes static properties for the current, parent, and root view models.
  2652. // If a view model is actually stored in an observable, the corresponding binding context object, and
  2653. // any child contexts, must be updated when the view model is changed.
  2654. function updateContext() {
  2655. // Most of the time, the context will directly get a view model object, but if a function is given,
  2656. // we call the function to retrieve the view model. If the function accesses any observables or returns
  2657. // an observable, the dependency is tracked, and those observables can later cause the binding
  2658. // context to be updated.
  2659. var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
  2660. dataItem = ko.utils.unwrapObservable(dataItemOrObservable);
  2661. if (parentContext) {
  2662. // When a "parent" context is given, register a dependency on the parent context. Thus whenever the
  2663. // parent context is updated, this context will also be updated.
  2664. if (parentContext._subscribable)
  2665. parentContext._subscribable();
  2666. // Copy $root and any custom properties from the parent context
  2667. ko.utils.extend(self, parentContext);
  2668. // Because the above copy overwrites our own properties, we need to reset them.
  2669. self._subscribable = subscribable;
  2670. } else {
  2671. self['$parents'] = [];
  2672. self['$root'] = dataItem;
  2673. // Export 'ko' in the binding context so it will be available in bindings and templates
  2674. // even if 'ko' isn't exported as a global, such as when using an AMD loader.
  2675. // See https://github.com/SteveSanderson/knockout/issues/490
  2676. self['ko'] = ko;
  2677. }
  2678. self['$rawData'] = dataItemOrObservable;
  2679. self['$data'] = dataItem;
  2680. if (dataItemAlias)
  2681. self[dataItemAlias] = dataItem;
  2682. // The extendCallback function is provided when creating a child context or extending a context.
  2683. // It handles the specific actions needed to finish setting up the binding context. Actions in this
  2684. // function could also add dependencies to this binding context.
  2685. if (extendCallback)
  2686. extendCallback(self, parentContext, dataItem);
  2687. return self['$data'];
  2688. }
  2689. function disposeWhen() {
  2690. return nodes && !ko.utils.anyDomNodeIsAttachedToDocument(nodes);
  2691. }
  2692. var self = this,
  2693. isFunc = typeof(dataItemOrAccessor) == "function" && !ko.isObservable(dataItemOrAccessor),
  2694. nodes,
  2695. subscribable;
  2696. if (options && options['exportDependencies']) {
  2697. // The "exportDependencies" option means that the calling code will track any dependencies and re-create
  2698. // the binding context when they change.
  2699. updateContext();
  2700. } else {
  2701. subscribable = ko.dependentObservable(updateContext, null, { disposeWhen: disposeWhen, disposeWhenNodeIsRemoved: true });
  2702. // At this point, the binding context has been initialized, and the "subscribable" computed observable is
  2703. // subscribed to any observables that were accessed in the process. If there is nothing to track, the
  2704. // computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
  2705. // the context object.
  2706. if (subscribable.isActive()) {
  2707. self._subscribable = subscribable;
  2708. // Always notify because even if the model ($data) hasn't changed, other context properties might have changed
  2709. subscribable['equalityComparer'] = null;
  2710. // We need to be able to dispose of this computed observable when it's no longer needed. This would be
  2711. // easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
  2712. // we cannot assume that those nodes have any relation to each other. So instead we track any node that
  2713. // the context is attached to, and dispose the computed when all of those nodes have been cleaned.
  2714. // Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
  2715. nodes = [];
  2716. subscribable._addNode = function(node) {
  2717. nodes.push(node);
  2718. ko.utils.domNodeDisposal.addDisposeCallback(node, function(node) {
  2719. ko.utils.arrayRemoveItem(nodes, node);
  2720. if (!nodes.length) {
  2721. subscribable.dispose();
  2722. self._subscribable = subscribable = undefined;
  2723. }
  2724. });
  2725. };
  2726. }
  2727. }
  2728. }
  2729. // Extend the binding context hierarchy with a new view model object. If the parent context is watching
  2730. // any observables, the new child context will automatically get a dependency on the parent context.
  2731. // But this does not mean that the $data value of the child context will also get updated. If the child
  2732. // view model also depends on the parent view model, you must provide a function that returns the correct
  2733. // view model on each update.
  2734. ko.bindingContext.prototype['createChildContext'] = function (dataItemOrAccessor, dataItemAlias, extendCallback, options) {
  2735. return new ko.bindingContext(dataItemOrAccessor, this, dataItemAlias, function(self, parentContext) {
  2736. // Extend the context hierarchy by setting the appropriate pointers
  2737. self['$parentContext'] = parentContext;
  2738. self['$parent'] = parentContext['$data'];
  2739. self['$parents'] = (parentContext['$parents'] || []).slice(0);
  2740. self['$parents'].unshift(self['$parent']);
  2741. if (extendCallback)
  2742. extendCallback(self);
  2743. }, options);
  2744. };
  2745. // Extend the binding context with new custom properties. This doesn't change the context hierarchy.
  2746. // Similarly to "child" contexts, provide a function here to make sure that the correct values are set
  2747. // when an observable view model is updated.
  2748. ko.bindingContext.prototype['extend'] = function(properties) {
  2749. // If the parent context references an observable view model, "_subscribable" will always be the
  2750. // latest view model object. If not, "_subscribable" isn't set, and we can use the static "$data" value.
  2751. return new ko.bindingContext(this._subscribable || this['$data'], this, null, function(self, parentContext) {
  2752. // This "child" context doesn't directly track a parent observable view model,
  2753. // so we need to manually set the $rawData value to match the parent.
  2754. self['$rawData'] = parentContext['$rawData'];
  2755. ko.utils.extend(self, typeof(properties) == "function" ? properties() : properties);
  2756. });
  2757. };
  2758. ko.bindingContext.prototype.createStaticChildContext = function (dataItemOrAccessor, dataItemAlias) {
  2759. return this['createChildContext'](dataItemOrAccessor, dataItemAlias, null, { "exportDependencies": true });
  2760. };
  2761. // Returns the valueAccesor function for a binding value
  2762. function makeValueAccessor(value) {
  2763. return function() {
  2764. return value;
  2765. };
  2766. }
  2767. // Returns the value of a valueAccessor function
  2768. function evaluateValueAccessor(valueAccessor) {
  2769. return valueAccessor();
  2770. }
  2771. // Given a function that returns bindings, create and return a new object that contains
  2772. // binding value-accessors functions. Each accessor function calls the original function
  2773. // so that it always gets the latest value and all dependencies are captured. This is used
  2774. // by ko.applyBindingsToNode and getBindingsAndMakeAccessors.
  2775. function makeAccessorsFromFunction(callback) {
  2776. return ko.utils.objectMap(ko.dependencyDetection.ignore(callback), function(value, key) {
  2777. return function() {
  2778. return callback()[key];
  2779. };
  2780. });
  2781. }
  2782. // Given a bindings function or object, create and return a new object that contains
  2783. // binding value-accessors functions. This is used by ko.applyBindingsToNode.
  2784. function makeBindingAccessors(bindings, context, node) {
  2785. if (typeof bindings === 'function') {
  2786. return makeAccessorsFromFunction(bindings.bind(null, context, node));
  2787. } else {
  2788. return ko.utils.objectMap(bindings, makeValueAccessor);
  2789. }
  2790. }
  2791. // This function is used if the binding provider doesn't include a getBindingAccessors function.
  2792. // It must be called with 'this' set to the provider instance.
  2793. function getBindingsAndMakeAccessors(node, context) {
  2794. return makeAccessorsFromFunction(this['getBindings'].bind(this, node, context));
  2795. }
  2796. function validateThatBindingIsAllowedForVirtualElements(bindingName) {
  2797. var validator = ko.virtualElements.allowedBindings[bindingName];
  2798. if (!validator)
  2799. throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
  2800. }
  2801. function applyBindingsToDescendantsInternal (bindingContext, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
  2802. var currentChild,
  2803. nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement),
  2804. provider = ko.bindingProvider['instance'],
  2805. preprocessNode = provider['preprocessNode'];
  2806. // Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's
  2807. // possible to insert new siblings after it, and/or replace the node with a different one. This can be used to
  2808. // implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that
  2809. // trigger insertion of <template> contents at that point in the document.
  2810. if (preprocessNode) {
  2811. while (currentChild = nextInQueue) {
  2812. nextInQueue = ko.virtualElements.nextSibling(currentChild);
  2813. preprocessNode.call(provider, currentChild);
  2814. }
  2815. // Reset nextInQueue for the next loop
  2816. nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
  2817. }
  2818. while (currentChild = nextInQueue) {
  2819. // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
  2820. nextInQueue = ko.virtualElements.nextSibling(currentChild);
  2821. applyBindingsToNodeAndDescendantsInternal(bindingContext, currentChild, bindingContextsMayDifferFromDomParentElement);
  2822. }
  2823. }
  2824. function applyBindingsToNodeAndDescendantsInternal (bindingContext, nodeVerified, bindingContextMayDifferFromDomParentElement) {
  2825. var shouldBindDescendants = true;
  2826. // Perf optimisation: Apply bindings only if...
  2827. // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
  2828. // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
  2829. // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
  2830. var isElement = (nodeVerified.nodeType === 1);
  2831. if (isElement) // Workaround IE <= 8 HTML parsing weirdness
  2832. ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
  2833. var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
  2834. || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
  2835. if (shouldApplyBindings)
  2836. shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, bindingContext, bindingContextMayDifferFromDomParentElement)['shouldBindDescendants'];
  2837. if (shouldBindDescendants && !bindingDoesNotRecurseIntoElementTypes[ko.utils.tagNameLower(nodeVerified)]) {
  2838. // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
  2839. // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
  2840. // hence bindingContextsMayDifferFromDomParentElement is false
  2841. // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
  2842. // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
  2843. // hence bindingContextsMayDifferFromDomParentElement is true
  2844. applyBindingsToDescendantsInternal(bindingContext, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
  2845. }
  2846. }
  2847. var boundElementDomDataKey = ko.utils.domData.nextKey();
  2848. function topologicalSortBindings(bindings) {
  2849. // Depth-first sort
  2850. var result = [], // The list of key/handler pairs that we will return
  2851. bindingsConsidered = {}, // A temporary record of which bindings are already in 'result'
  2852. cyclicDependencyStack = []; // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it
  2853. ko.utils.objectForEach(bindings, function pushBinding(bindingKey) {
  2854. if (!bindingsConsidered[bindingKey]) {
  2855. var binding = ko['getBindingHandler'](bindingKey);
  2856. if (binding) {
  2857. // First add dependencies (if any) of the current binding
  2858. if (binding['after']) {
  2859. cyclicDependencyStack.push(bindingKey);
  2860. ko.utils.arrayForEach(binding['after'], function(bindingDependencyKey) {
  2861. if (bindings[bindingDependencyKey]) {
  2862. if (ko.utils.arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) {
  2863. throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + cyclicDependencyStack.join(", "));
  2864. } else {
  2865. pushBinding(bindingDependencyKey);
  2866. }
  2867. }
  2868. });
  2869. cyclicDependencyStack.length--;
  2870. }
  2871. // Next add the current binding
  2872. result.push({ key: bindingKey, handler: binding });
  2873. }
  2874. bindingsConsidered[bindingKey] = true;
  2875. }
  2876. });
  2877. return result;
  2878. }
  2879. function applyBindingsToNodeInternal(node, sourceBindings, bindingContext, bindingContextMayDifferFromDomParentElement) {
  2880. // Prevent multiple applyBindings calls for the same node, except when a binding value is specified
  2881. var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
  2882. if (!sourceBindings) {
  2883. if (alreadyBound) {
  2884. throw Error("You cannot apply bindings multiple times to the same element.");
  2885. }
  2886. ko.utils.domData.set(node, boundElementDomDataKey, true);
  2887. }
  2888. // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
  2889. // we can easily recover it just by scanning up the node's ancestors in the DOM
  2890. // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
  2891. if (!alreadyBound && bindingContextMayDifferFromDomParentElement)
  2892. ko.storedBindingContextForNode(node, bindingContext);
  2893. // Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings
  2894. var bindings;
  2895. if (sourceBindings && typeof sourceBindings !== 'function') {
  2896. bindings = sourceBindings;
  2897. } else {
  2898. var provider = ko.bindingProvider['instance'],
  2899. getBindings = provider['getBindingAccessors'] || getBindingsAndMakeAccessors;
  2900. // Get the binding from the provider within a computed observable so that we can update the bindings whenever
  2901. // the binding context is updated or if the binding provider accesses observables.
  2902. var bindingsUpdater = ko.dependentObservable(
  2903. function() {
  2904. bindings = sourceBindings ? sourceBindings(bindingContext, node) : getBindings.call(provider, node, bindingContext);
  2905. // Register a dependency on the binding context to support observable view models.
  2906. if (bindings && bindingContext._subscribable)
  2907. bindingContext._subscribable();
  2908. return bindings;
  2909. },
  2910. null, { disposeWhenNodeIsRemoved: node }
  2911. );
  2912. if (!bindings || !bindingsUpdater.isActive())
  2913. bindingsUpdater = null;
  2914. }
  2915. var bindingHandlerThatControlsDescendantBindings;
  2916. if (bindings) {
  2917. // Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding
  2918. // context update), just return the value accessor from the binding. Otherwise, return a function that always gets
  2919. // the latest binding value and registers a dependency on the binding updater.
  2920. var getValueAccessor = bindingsUpdater
  2921. ? function(bindingKey) {
  2922. return function() {
  2923. return evaluateValueAccessor(bindingsUpdater()[bindingKey]);
  2924. };
  2925. } : function(bindingKey) {
  2926. return bindings[bindingKey];
  2927. };
  2928. // Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated
  2929. function allBindings() {
  2930. return ko.utils.objectMap(bindingsUpdater ? bindingsUpdater() : bindings, evaluateValueAccessor);
  2931. }
  2932. // The following is the 3.x allBindings API
  2933. allBindings['get'] = function(key) {
  2934. return bindings[key] && evaluateValueAccessor(getValueAccessor(key));
  2935. };
  2936. allBindings['has'] = function(key) {
  2937. return key in bindings;
  2938. };
  2939. // First put the bindings into the right order
  2940. var orderedBindings = topologicalSortBindings(bindings);
  2941. // Go through the sorted bindings, calling init and update for each
  2942. ko.utils.arrayForEach(orderedBindings, function(bindingKeyAndHandler) {
  2943. // Note that topologicalSortBindings has already filtered out any nonexistent binding handlers,
  2944. // so bindingKeyAndHandler.handler will always be nonnull.
  2945. var handlerInitFn = bindingKeyAndHandler.handler["init"],
  2946. handlerUpdateFn = bindingKeyAndHandler.handler["update"],
  2947. bindingKey = bindingKeyAndHandler.key;
  2948. if (node.nodeType === 8) {
  2949. validateThatBindingIsAllowedForVirtualElements(bindingKey);
  2950. }
  2951. try {
  2952. // Run init, ignoring any dependencies
  2953. if (typeof handlerInitFn == "function") {
  2954. ko.dependencyDetection.ignore(function() {
  2955. var initResult = handlerInitFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
  2956. // If this binding handler claims to control descendant bindings, make a note of this
  2957. if (initResult && initResult['controlsDescendantBindings']) {
  2958. if (bindingHandlerThatControlsDescendantBindings !== undefined)
  2959. throw new Error("Multiple bindings (" + bindingHandlerThatControlsDescendantBindings + " and " + bindingKey + ") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");
  2960. bindingHandlerThatControlsDescendantBindings = bindingKey;
  2961. }
  2962. });
  2963. }
  2964. // Run update in its own computed wrapper
  2965. if (typeof handlerUpdateFn == "function") {
  2966. ko.dependentObservable(
  2967. function() {
  2968. handlerUpdateFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
  2969. },
  2970. null,
  2971. { disposeWhenNodeIsRemoved: node }
  2972. );
  2973. }
  2974. } catch (ex) {
  2975. ex.message = "Unable to process binding \"" + bindingKey + ": " + bindings[bindingKey] + "\"\nMessage: " + ex.message;
  2976. throw ex;
  2977. }
  2978. });
  2979. }
  2980. return {
  2981. 'shouldBindDescendants': bindingHandlerThatControlsDescendantBindings === undefined
  2982. };
  2983. };
  2984. var storedBindingContextDomDataKey = ko.utils.domData.nextKey();
  2985. ko.storedBindingContextForNode = function (node, bindingContext) {
  2986. if (arguments.length == 2) {
  2987. ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
  2988. if (bindingContext._subscribable)
  2989. bindingContext._subscribable._addNode(node);
  2990. } else {
  2991. return ko.utils.domData.get(node, storedBindingContextDomDataKey);
  2992. }
  2993. }
  2994. function getBindingContext(viewModelOrBindingContext) {
  2995. return viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
  2996. ? viewModelOrBindingContext
  2997. : new ko.bindingContext(viewModelOrBindingContext);
  2998. }
  2999. ko.applyBindingAccessorsToNode = function (node, bindings, viewModelOrBindingContext) {
  3000. if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
  3001. ko.virtualElements.normaliseVirtualElementDomStructure(node);
  3002. return applyBindingsToNodeInternal(node, bindings, getBindingContext(viewModelOrBindingContext), true);
  3003. };
  3004. ko.applyBindingsToNode = function (node, bindings, viewModelOrBindingContext) {
  3005. var context = getBindingContext(viewModelOrBindingContext);
  3006. return ko.applyBindingAccessorsToNode(node, makeBindingAccessors(bindings, context, node), context);
  3007. };
  3008. ko.applyBindingsToDescendants = function(viewModelOrBindingContext, rootNode) {
  3009. if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
  3010. applyBindingsToDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
  3011. };
  3012. ko.applyBindings = function (viewModelOrBindingContext, rootNode) {
  3013. // If jQuery is loaded after Knockout, we won't initially have access to it. So save it here.
  3014. if (!jQueryInstance && window['jQuery']) {
  3015. jQueryInstance = window['jQuery'];
  3016. }
  3017. if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
  3018. throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
  3019. rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
  3020. applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
  3021. };
  3022. // Retrieving binding context from arbitrary nodes
  3023. ko.contextFor = function(node) {
  3024. // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
  3025. switch (node.nodeType) {
  3026. case 1:
  3027. case 8:
  3028. var context = ko.storedBindingContextForNode(node);
  3029. if (context) return context;
  3030. if (node.parentNode) return ko.contextFor(node.parentNode);
  3031. break;
  3032. }
  3033. return undefined;
  3034. };
  3035. ko.dataFor = function(node) {
  3036. var context = ko.contextFor(node);
  3037. return context ? context['$data'] : undefined;
  3038. };
  3039. ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
  3040. ko.exportSymbol('applyBindings', ko.applyBindings);
  3041. ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
  3042. ko.exportSymbol('applyBindingAccessorsToNode', ko.applyBindingAccessorsToNode);
  3043. ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
  3044. ko.exportSymbol('contextFor', ko.contextFor);
  3045. ko.exportSymbol('dataFor', ko.dataFor);
  3046. })();
  3047. (function(undefined) {
  3048. var loadingSubscribablesCache = {}, // Tracks component loads that are currently in flight
  3049. loadedDefinitionsCache = {}; // Tracks component loads that have already completed
  3050. ko.components = {
  3051. get: function(componentName, callback) {
  3052. var cachedDefinition = getObjectOwnProperty(loadedDefinitionsCache, componentName);
  3053. if (cachedDefinition) {
  3054. // It's already loaded and cached. Reuse the same definition object.
  3055. // Note that for API consistency, even cache hits complete asynchronously by default.
  3056. // You can bypass this by putting synchronous:true on your component config.
  3057. if (cachedDefinition.isSynchronousComponent) {
  3058. ko.dependencyDetection.ignore(function() { // See comment in loaderRegistryBehaviors.js for reasoning
  3059. callback(cachedDefinition.definition);
  3060. });
  3061. } else {
  3062. ko.tasks.schedule(function() { callback(cachedDefinition.definition); });
  3063. }
  3064. } else {
  3065. // Join the loading process that is already underway, or start a new one.
  3066. loadComponentAndNotify(componentName, callback);
  3067. }
  3068. },
  3069. clearCachedDefinition: function(componentName) {
  3070. delete loadedDefinitionsCache[componentName];
  3071. },
  3072. _getFirstResultFromLoaders: getFirstResultFromLoaders
  3073. };
  3074. function getObjectOwnProperty(obj, propName) {
  3075. return obj.hasOwnProperty(propName) ? obj[propName] : undefined;
  3076. }
  3077. function loadComponentAndNotify(componentName, callback) {
  3078. var subscribable = getObjectOwnProperty(loadingSubscribablesCache, componentName),
  3079. completedAsync;
  3080. if (!subscribable) {
  3081. // It's not started loading yet. Start loading, and when it's done, move it to loadedDefinitionsCache.
  3082. subscribable = loadingSubscribablesCache[componentName] = new ko.subscribable();
  3083. subscribable.subscribe(callback);
  3084. beginLoadingComponent(componentName, function(definition, config) {
  3085. var isSynchronousComponent = !!(config && config['synchronous']);
  3086. loadedDefinitionsCache[componentName] = { definition: definition, isSynchronousComponent: isSynchronousComponent };
  3087. delete loadingSubscribablesCache[componentName];
  3088. // For API consistency, all loads complete asynchronously. However we want to avoid
  3089. // adding an extra task schedule if it's unnecessary (i.e., the completion is already
  3090. // async).
  3091. //
  3092. // You can bypass the 'always asynchronous' feature by putting the synchronous:true
  3093. // flag on your component configuration when you register it.
  3094. if (completedAsync || isSynchronousComponent) {
  3095. // Note that notifySubscribers ignores any dependencies read within the callback.
  3096. // See comment in loaderRegistryBehaviors.js for reasoning
  3097. subscribable['notifySubscribers'](definition);
  3098. } else {
  3099. ko.tasks.schedule(function() {
  3100. subscribable['notifySubscribers'](definition);
  3101. });
  3102. }
  3103. });
  3104. completedAsync = true;
  3105. } else {
  3106. subscribable.subscribe(callback);
  3107. }
  3108. }
  3109. function beginLoadingComponent(componentName, callback) {
  3110. getFirstResultFromLoaders('getConfig', [componentName], function(config) {
  3111. if (config) {
  3112. // We have a config, so now load its definition
  3113. getFirstResultFromLoaders('loadComponent', [componentName, config], function(definition) {
  3114. callback(definition, config);
  3115. });
  3116. } else {
  3117. // The component has no config - it's unknown to all the loaders.
  3118. // Note that this is not an error (e.g., a module loading error) - that would abort the
  3119. // process and this callback would not run. For this callback to run, all loaders must
  3120. // have confirmed they don't know about this component.
  3121. callback(null, null);
  3122. }
  3123. });
  3124. }
  3125. function getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders) {
  3126. // On the first call in the stack, start with the full set of loaders
  3127. if (!candidateLoaders) {
  3128. candidateLoaders = ko.components['loaders'].slice(0); // Use a copy, because we'll be mutating this array
  3129. }
  3130. // Try the next candidate
  3131. var currentCandidateLoader = candidateLoaders.shift();
  3132. if (currentCandidateLoader) {
  3133. var methodInstance = currentCandidateLoader[methodName];
  3134. if (methodInstance) {
  3135. var wasAborted = false,
  3136. synchronousReturnValue = methodInstance.apply(currentCandidateLoader, argsExceptCallback.concat(function(result) {
  3137. if (wasAborted) {
  3138. callback(null);
  3139. } else if (result !== null) {
  3140. // This candidate returned a value. Use it.
  3141. callback(result);
  3142. } else {
  3143. // Try the next candidate
  3144. getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);
  3145. }
  3146. }));
  3147. // Currently, loaders may not return anything synchronously. This leaves open the possibility
  3148. // that we'll extend the API to support synchronous return values in the future. It won't be
  3149. // a breaking change, because currently no loader is allowed to return anything except undefined.
  3150. if (synchronousReturnValue !== undefined) {
  3151. wasAborted = true;
  3152. // Method to suppress exceptions will remain undocumented. This is only to keep
  3153. // KO's specs running tidily, since we can observe the loading got aborted without
  3154. // having exceptions cluttering up the console too.
  3155. if (!currentCandidateLoader['suppressLoaderExceptions']) {
  3156. throw new Error('Component loaders must supply values by invoking the callback, not by returning values synchronously.');
  3157. }
  3158. }
  3159. } else {
  3160. // This candidate doesn't have the relevant handler. Synchronously move on to the next one.
  3161. getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);
  3162. }
  3163. } else {
  3164. // No candidates returned a value
  3165. callback(null);
  3166. }
  3167. }
  3168. // Reference the loaders via string name so it's possible for developers
  3169. // to replace the whole array by assigning to ko.components.loaders
  3170. ko.components['loaders'] = [];
  3171. ko.exportSymbol('components', ko.components);
  3172. ko.exportSymbol('components.get', ko.components.get);
  3173. ko.exportSymbol('components.clearCachedDefinition', ko.components.clearCachedDefinition);
  3174. })();
  3175. (function(undefined) {
  3176. // The default loader is responsible for two things:
  3177. // 1. Maintaining the default in-memory registry of component configuration objects
  3178. // (i.e., the thing you're writing to when you call ko.components.register(someName, ...))
  3179. // 2. Answering requests for components by fetching configuration objects
  3180. // from that default in-memory registry and resolving them into standard
  3181. // component definition objects (of the form { createViewModel: ..., template: ... })
  3182. // Custom loaders may override either of these facilities, i.e.,
  3183. // 1. To supply configuration objects from some other source (e.g., conventions)
  3184. // 2. Or, to resolve configuration objects by loading viewmodels/templates via arbitrary logic.
  3185. var defaultConfigRegistry = {};
  3186. ko.components.register = function(componentName, config) {
  3187. if (!config) {
  3188. throw new Error('Invalid configuration for ' + componentName);
  3189. }
  3190. if (ko.components.isRegistered(componentName)) {
  3191. throw new Error('Component ' + componentName + ' is already registered');
  3192. }
  3193. defaultConfigRegistry[componentName] = config;
  3194. };
  3195. ko.components.isRegistered = function(componentName) {
  3196. return defaultConfigRegistry.hasOwnProperty(componentName);
  3197. };
  3198. ko.components.unregister = function(componentName) {
  3199. delete defaultConfigRegistry[componentName];
  3200. ko.components.clearCachedDefinition(componentName);
  3201. };
  3202. ko.components.defaultLoader = {
  3203. 'getConfig': function(componentName, callback) {
  3204. var result = defaultConfigRegistry.hasOwnProperty(componentName)
  3205. ? defaultConfigRegistry[componentName]
  3206. : null;
  3207. callback(result);
  3208. },
  3209. 'loadComponent': function(componentName, config, callback) {
  3210. var errorCallback = makeErrorCallback(componentName);
  3211. possiblyGetConfigFromAmd(errorCallback, config, function(loadedConfig) {
  3212. resolveConfig(componentName, errorCallback, loadedConfig, callback);
  3213. });
  3214. },
  3215. 'loadTemplate': function(componentName, templateConfig, callback) {
  3216. resolveTemplate(makeErrorCallback(componentName), templateConfig, callback);
  3217. },
  3218. 'loadViewModel': function(componentName, viewModelConfig, callback) {
  3219. resolveViewModel(makeErrorCallback(componentName), viewModelConfig, callback);
  3220. }
  3221. };
  3222. var createViewModelKey = 'createViewModel';
  3223. // Takes a config object of the form { template: ..., viewModel: ... }, and asynchronously convert it
  3224. // into the standard component definition format:
  3225. // { template: <ArrayOfDomNodes>, createViewModel: function(params, componentInfo) { ... } }.
  3226. // Since both template and viewModel may need to be resolved asynchronously, both tasks are performed
  3227. // in parallel, and the results joined when both are ready. We don't depend on any promises infrastructure,
  3228. // so this is implemented manually below.
  3229. function resolveConfig(componentName, errorCallback, config, callback) {
  3230. var result = {},
  3231. makeCallBackWhenZero = 2,
  3232. tryIssueCallback = function() {
  3233. if (--makeCallBackWhenZero === 0) {
  3234. callback(result);
  3235. }
  3236. },
  3237. templateConfig = config['template'],
  3238. viewModelConfig = config['viewModel'];
  3239. if (templateConfig) {
  3240. possiblyGetConfigFromAmd(errorCallback, templateConfig, function(loadedConfig) {
  3241. ko.components._getFirstResultFromLoaders('loadTemplate', [componentName, loadedConfig], function(resolvedTemplate) {
  3242. result['template'] = resolvedTemplate;
  3243. tryIssueCallback();
  3244. });
  3245. });
  3246. } else {
  3247. tryIssueCallback();
  3248. }
  3249. if (viewModelConfig) {
  3250. possiblyGetConfigFromAmd(errorCallback, viewModelConfig, function(loadedConfig) {
  3251. ko.components._getFirstResultFromLoaders('loadViewModel', [componentName, loadedConfig], function(resolvedViewModel) {
  3252. result[createViewModelKey] = resolvedViewModel;
  3253. tryIssueCallback();
  3254. });
  3255. });
  3256. } else {
  3257. tryIssueCallback();
  3258. }
  3259. }
  3260. function resolveTemplate(errorCallback, templateConfig, callback) {
  3261. if (typeof templateConfig === 'string') {
  3262. // Markup - parse it
  3263. callback(ko.utils.parseHtmlFragment(templateConfig));
  3264. } else if (templateConfig instanceof Array) {
  3265. // Assume already an array of DOM nodes - pass through unchanged
  3266. callback(templateConfig);
  3267. } else if (isDocumentFragment(templateConfig)) {
  3268. // Document fragment - use its child nodes
  3269. callback(ko.utils.makeArray(templateConfig.childNodes));
  3270. } else if (templateConfig['element']) {
  3271. var element = templateConfig['element'];
  3272. if (isDomElement(element)) {
  3273. // Element instance - copy its child nodes
  3274. callback(cloneNodesFromTemplateSourceElement(element));
  3275. } else if (typeof element === 'string') {
  3276. // Element ID - find it, then copy its child nodes
  3277. var elemInstance = document.getElementById(element);
  3278. if (elemInstance) {
  3279. callback(cloneNodesFromTemplateSourceElement(elemInstance));
  3280. } else {
  3281. errorCallback('Cannot find element with ID ' + element);
  3282. }
  3283. } else {
  3284. errorCallback('Unknown element type: ' + element);
  3285. }
  3286. } else {
  3287. errorCallback('Unknown template value: ' + templateConfig);
  3288. }
  3289. }
  3290. function resolveViewModel(errorCallback, viewModelConfig, callback) {
  3291. if (typeof viewModelConfig === 'function') {
  3292. // Constructor - convert to standard factory function format
  3293. // By design, this does *not* supply componentInfo to the constructor, as the intent is that
  3294. // componentInfo contains non-viewmodel data (e.g., the component's element) that should only
  3295. // be used in factory functions, not viewmodel constructors.
  3296. callback(function (params /*, componentInfo */) {
  3297. return new viewModelConfig(params);
  3298. });
  3299. } else if (typeof viewModelConfig[createViewModelKey] === 'function') {
  3300. // Already a factory function - use it as-is
  3301. callback(viewModelConfig[createViewModelKey]);
  3302. } else if ('instance' in viewModelConfig) {
  3303. // Fixed object instance - promote to createViewModel format for API consistency
  3304. var fixedInstance = viewModelConfig['instance'];
  3305. callback(function (params, componentInfo) {
  3306. return fixedInstance;
  3307. });
  3308. } else if ('viewModel' in viewModelConfig) {
  3309. // Resolved AMD module whose value is of the form { viewModel: ... }
  3310. resolveViewModel(errorCallback, viewModelConfig['viewModel'], callback);
  3311. } else {
  3312. errorCallback('Unknown viewModel value: ' + viewModelConfig);
  3313. }
  3314. }
  3315. function cloneNodesFromTemplateSourceElement(elemInstance) {
  3316. switch (ko.utils.tagNameLower(elemInstance)) {
  3317. case 'script':
  3318. return ko.utils.parseHtmlFragment(elemInstance.text);
  3319. case 'textarea':
  3320. return ko.utils.parseHtmlFragment(elemInstance.value);
  3321. case 'template':
  3322. // For browsers with proper <template> element support (i.e., where the .content property
  3323. // gives a document fragment), use that document fragment.
  3324. if (isDocumentFragment(elemInstance.content)) {
  3325. return ko.utils.cloneNodes(elemInstance.content.childNodes);
  3326. }
  3327. }
  3328. // Regular elements such as <div>, and <template> elements on old browsers that don't really
  3329. // understand <template> and just treat it as a regular container
  3330. return ko.utils.cloneNodes(elemInstance.childNodes);
  3331. }
  3332. function isDomElement(obj) {
  3333. if (window['HTMLElement']) {
  3334. return obj instanceof HTMLElement;
  3335. } else {
  3336. return obj && obj.tagName && obj.nodeType === 1;
  3337. }
  3338. }
  3339. function isDocumentFragment(obj) {
  3340. if (window['DocumentFragment']) {
  3341. return obj instanceof DocumentFragment;
  3342. } else {
  3343. return obj && obj.nodeType === 11;
  3344. }
  3345. }
  3346. function possiblyGetConfigFromAmd(errorCallback, config, callback) {
  3347. if (typeof config['require'] === 'string') {
  3348. // The config is the value of an AMD module
  3349. if (amdRequire || window['require']) {
  3350. (amdRequire || window['require'])([config['require']], callback);
  3351. } else {
  3352. errorCallback('Uses require, but no AMD loader is present');
  3353. }
  3354. } else {
  3355. callback(config);
  3356. }
  3357. }
  3358. function makeErrorCallback(componentName) {
  3359. return function (message) {
  3360. throw new Error('Component \'' + componentName + '\': ' + message);
  3361. };
  3362. }
  3363. ko.exportSymbol('components.register', ko.components.register);
  3364. ko.exportSymbol('components.isRegistered', ko.components.isRegistered);
  3365. ko.exportSymbol('components.unregister', ko.components.unregister);
  3366. // Expose the default loader so that developers can directly ask it for configuration
  3367. // or to resolve configuration
  3368. ko.exportSymbol('components.defaultLoader', ko.components.defaultLoader);
  3369. // By default, the default loader is the only registered component loader
  3370. ko.components['loaders'].push(ko.components.defaultLoader);
  3371. // Privately expose the underlying config registry for use in old-IE shim
  3372. ko.components._allRegisteredComponents = defaultConfigRegistry;
  3373. })();
  3374. (function (undefined) {
  3375. // Overridable API for determining which component name applies to a given node. By overriding this,
  3376. // you can for example map specific tagNames to components that are not preregistered.
  3377. ko.components['getComponentNameForNode'] = function(node) {
  3378. var tagNameLower = ko.utils.tagNameLower(node);
  3379. if (ko.components.isRegistered(tagNameLower)) {
  3380. // Try to determine that this node can be considered a *custom* element; see https://github.com/knockout/knockout/issues/1603
  3381. if (tagNameLower.indexOf('-') != -1 || ('' + node) == "[object HTMLUnknownElement]" || (ko.utils.ieVersion <= 8 && node.tagName === tagNameLower)) {
  3382. return tagNameLower;
  3383. }
  3384. }
  3385. };
  3386. ko.components.addBindingsForCustomElement = function(allBindings, node, bindingContext, valueAccessors) {
  3387. // Determine if it's really a custom element matching a component
  3388. if (node.nodeType === 1) {
  3389. var componentName = ko.components['getComponentNameForNode'](node);
  3390. if (componentName) {
  3391. // It does represent a component, so add a component binding for it
  3392. allBindings = allBindings || {};
  3393. if (allBindings['component']) {
  3394. // Avoid silently overwriting some other 'component' binding that may already be on the element
  3395. throw new Error('Cannot use the "component" binding on a custom element matching a component');
  3396. }
  3397. var componentBindingValue = { 'name': componentName, 'params': getComponentParamsFromCustomElement(node, bindingContext) };
  3398. allBindings['component'] = valueAccessors
  3399. ? function() { return componentBindingValue; }
  3400. : componentBindingValue;
  3401. }
  3402. }
  3403. return allBindings;
  3404. }
  3405. var nativeBindingProviderInstance = new ko.bindingProvider();
  3406. function getComponentParamsFromCustomElement(elem, bindingContext) {
  3407. var paramsAttribute = elem.getAttribute('params');
  3408. if (paramsAttribute) {
  3409. var params = nativeBindingProviderInstance['parseBindingsString'](paramsAttribute, bindingContext, elem, { 'valueAccessors': true, 'bindingParams': true }),
  3410. rawParamComputedValues = ko.utils.objectMap(params, function(paramValue, paramName) {
  3411. return ko.computed(paramValue, null, { disposeWhenNodeIsRemoved: elem });
  3412. }),
  3413. result = ko.utils.objectMap(rawParamComputedValues, function(paramValueComputed, paramName) {
  3414. var paramValue = paramValueComputed.peek();
  3415. // Does the evaluation of the parameter value unwrap any observables?
  3416. if (!paramValueComputed.isActive()) {
  3417. // No it doesn't, so there's no need for any computed wrapper. Just pass through the supplied value directly.
  3418. // Example: "someVal: firstName, age: 123" (whether or not firstName is an observable/computed)
  3419. return paramValue;
  3420. } else {
  3421. // Yes it does. Supply a computed property that unwraps both the outer (binding expression)
  3422. // level of observability, and any inner (resulting model value) level of observability.
  3423. // This means the component doesn't have to worry about multiple unwrapping. If the value is a
  3424. // writable observable, the computed will also be writable and pass the value on to the observable.
  3425. return ko.computed({
  3426. 'read': function() {
  3427. return ko.utils.unwrapObservable(paramValueComputed());
  3428. },
  3429. 'write': ko.isWriteableObservable(paramValue) && function(value) {
  3430. paramValueComputed()(value);
  3431. },
  3432. disposeWhenNodeIsRemoved: elem
  3433. });
  3434. }
  3435. });
  3436. // Give access to the raw computeds, as long as that wouldn't overwrite any custom param also called '$raw'
  3437. // This is in case the developer wants to react to outer (binding) observability separately from inner
  3438. // (model value) observability, or in case the model value observable has subobservables.
  3439. if (!result.hasOwnProperty('$raw')) {
  3440. result['$raw'] = rawParamComputedValues;
  3441. }
  3442. return result;
  3443. } else {
  3444. // For consistency, absence of a "params" attribute is treated the same as the presence of
  3445. // any empty one. Otherwise component viewmodels need special code to check whether or not
  3446. // 'params' or 'params.$raw' is null/undefined before reading subproperties, which is annoying.
  3447. return { '$raw': {} };
  3448. }
  3449. }
  3450. // --------------------------------------------------------------------------------
  3451. // Compatibility code for older (pre-HTML5) IE browsers
  3452. if (ko.utils.ieVersion < 9) {
  3453. // Whenever you preregister a component, enable it as a custom element in the current document
  3454. ko.components['register'] = (function(originalFunction) {
  3455. return function(componentName) {
  3456. document.createElement(componentName); // Allows IE<9 to parse markup containing the custom element
  3457. return originalFunction.apply(this, arguments);
  3458. }
  3459. })(ko.components['register']);
  3460. // Whenever you create a document fragment, enable all preregistered component names as custom elements
  3461. // This is needed to make innerShiv/jQuery HTML parsing correctly handle the custom elements
  3462. document.createDocumentFragment = (function(originalFunction) {
  3463. return function() {
  3464. var newDocFrag = originalFunction(),
  3465. allComponents = ko.components._allRegisteredComponents;
  3466. for (var componentName in allComponents) {
  3467. if (allComponents.hasOwnProperty(componentName)) {
  3468. newDocFrag.createElement(componentName);
  3469. }
  3470. }
  3471. return newDocFrag;
  3472. };
  3473. })(document.createDocumentFragment);
  3474. }
  3475. })();(function(undefined) {
  3476. var componentLoadingOperationUniqueId = 0;
  3477. ko.bindingHandlers['component'] = {
  3478. 'init': function(element, valueAccessor, ignored1, ignored2, bindingContext) {
  3479. var currentViewModel,
  3480. currentLoadingOperationId,
  3481. disposeAssociatedComponentViewModel = function () {
  3482. var currentViewModelDispose = currentViewModel && currentViewModel['dispose'];
  3483. if (typeof currentViewModelDispose === 'function') {
  3484. currentViewModelDispose.call(currentViewModel);
  3485. }
  3486. currentViewModel = null;
  3487. // Any in-flight loading operation is no longer relevant, so make sure we ignore its completion
  3488. currentLoadingOperationId = null;
  3489. },
  3490. originalChildNodes = ko.utils.makeArray(ko.virtualElements.childNodes(element));
  3491. ko.utils.domNodeDisposal.addDisposeCallback(element, disposeAssociatedComponentViewModel);
  3492. ko.computed(function () {
  3493. var value = ko.utils.unwrapObservable(valueAccessor()),
  3494. componentName, componentParams;
  3495. if (typeof value === 'string') {
  3496. componentName = value;
  3497. } else {
  3498. componentName = ko.utils.unwrapObservable(value['name']);
  3499. componentParams = ko.utils.unwrapObservable(value['params']);
  3500. }
  3501. if (!componentName) {
  3502. throw new Error('No component name specified');
  3503. }
  3504. var loadingOperationId = currentLoadingOperationId = ++componentLoadingOperationUniqueId;
  3505. ko.components.get(componentName, function(componentDefinition) {
  3506. // If this is not the current load operation for this element, ignore it.
  3507. if (currentLoadingOperationId !== loadingOperationId) {
  3508. return;
  3509. }
  3510. // Clean up previous state
  3511. disposeAssociatedComponentViewModel();
  3512. // Instantiate and bind new component. Implicitly this cleans any old DOM nodes.
  3513. if (!componentDefinition) {
  3514. throw new Error('Unknown component \'' + componentName + '\'');
  3515. }
  3516. cloneTemplateIntoElement(componentName, componentDefinition, element);
  3517. var componentViewModel = createViewModel(componentDefinition, element, originalChildNodes, componentParams),
  3518. childBindingContext = bindingContext['createChildContext'](componentViewModel, /* dataItemAlias */ undefined, function(ctx) {
  3519. ctx['$component'] = componentViewModel;
  3520. ctx['$componentTemplateNodes'] = originalChildNodes;
  3521. });
  3522. currentViewModel = componentViewModel;
  3523. ko.applyBindingsToDescendants(childBindingContext, element);
  3524. });
  3525. }, null, { disposeWhenNodeIsRemoved: element });
  3526. return { 'controlsDescendantBindings': true };
  3527. }
  3528. };
  3529. ko.virtualElements.allowedBindings['component'] = true;
  3530. function cloneTemplateIntoElement(componentName, componentDefinition, element) {
  3531. var template = componentDefinition['template'];
  3532. if (!template) {
  3533. throw new Error('Component \'' + componentName + '\' has no template');
  3534. }
  3535. var clonedNodesArray = ko.utils.cloneNodes(template);
  3536. ko.virtualElements.setDomNodeChildren(element, clonedNodesArray);
  3537. }
  3538. function createViewModel(componentDefinition, element, originalChildNodes, componentParams) {
  3539. var componentViewModelFactory = componentDefinition['createViewModel'];
  3540. return componentViewModelFactory
  3541. ? componentViewModelFactory.call(componentDefinition, componentParams, { 'element': element, 'templateNodes': originalChildNodes })
  3542. : componentParams; // Template-only component
  3543. }
  3544. })();
  3545. var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
  3546. ko.bindingHandlers['attr'] = {
  3547. 'update': function(element, valueAccessor, allBindings) {
  3548. var value = ko.utils.unwrapObservable(valueAccessor()) || {};
  3549. ko.utils.objectForEach(value, function(attrName, attrValue) {
  3550. attrValue = ko.utils.unwrapObservable(attrValue);
  3551. // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
  3552. // when someProp is a "no value"-like value (strictly null, false, or undefined)
  3553. // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
  3554. var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
  3555. if (toRemove)
  3556. element.removeAttribute(attrName);
  3557. // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
  3558. // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
  3559. // but instead of figuring out the mode, we'll just set the attribute through the Javascript
  3560. // property for IE <= 8.
  3561. if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
  3562. attrName = attrHtmlToJavascriptMap[attrName];
  3563. if (toRemove)
  3564. element.removeAttribute(attrName);
  3565. else
  3566. element[attrName] = attrValue;
  3567. } else if (!toRemove) {
  3568. element.setAttribute(attrName, attrValue.toString());
  3569. }
  3570. // Treat "name" specially - although you can think of it as an attribute, it also needs
  3571. // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
  3572. // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
  3573. // entirely, and there's no strong reason to allow for such casing in HTML.
  3574. if (attrName === "name") {
  3575. ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
  3576. }
  3577. });
  3578. }
  3579. };
  3580. (function() {
  3581. ko.bindingHandlers['checked'] = {
  3582. 'after': ['value', 'attr'],
  3583. 'init': function (element, valueAccessor, allBindings) {
  3584. var checkedValue = ko.pureComputed(function() {
  3585. // Treat "value" like "checkedValue" when it is included with "checked" binding
  3586. if (allBindings['has']('checkedValue')) {
  3587. return ko.utils.unwrapObservable(allBindings.get('checkedValue'));
  3588. } else if (allBindings['has']('value')) {
  3589. return ko.utils.unwrapObservable(allBindings.get('value'));
  3590. }
  3591. return element.value;
  3592. });
  3593. function updateModel() {
  3594. // This updates the model value from the view value.
  3595. // It runs in response to DOM events (click) and changes in checkedValue.
  3596. var isChecked = element.checked,
  3597. elemValue = useCheckedValue ? checkedValue() : isChecked;
  3598. // When we're first setting up this computed, don't change any model state.
  3599. if (ko.computedContext.isInitial()) {
  3600. return;
  3601. }
  3602. // We can ignore unchecked radio buttons, because some other radio
  3603. // button will be getting checked, and that one can take care of updating state.
  3604. if (isRadio && !isChecked) {
  3605. return;
  3606. }
  3607. var modelValue = ko.dependencyDetection.ignore(valueAccessor);
  3608. if (valueIsArray) {
  3609. var writableValue = rawValueIsNonArrayObservable ? modelValue.peek() : modelValue;
  3610. if (oldElemValue !== elemValue) {
  3611. // When we're responding to the checkedValue changing, and the element is
  3612. // currently checked, replace the old elem value with the new elem value
  3613. // in the model array.
  3614. if (isChecked) {
  3615. ko.utils.addOrRemoveItem(writableValue, elemValue, true);
  3616. ko.utils.addOrRemoveItem(writableValue, oldElemValue, false);
  3617. }
  3618. oldElemValue = elemValue;
  3619. } else {
  3620. // When we're responding to the user having checked/unchecked a checkbox,
  3621. // add/remove the element value to the model array.
  3622. ko.utils.addOrRemoveItem(writableValue, elemValue, isChecked);
  3623. }
  3624. if (rawValueIsNonArrayObservable && ko.isWriteableObservable(modelValue)) {
  3625. modelValue(writableValue);
  3626. }
  3627. } else {
  3628. ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'checked', elemValue, true);
  3629. }
  3630. };
  3631. function updateView() {
  3632. // This updates the view value from the model value.
  3633. // It runs in response to changes in the bound (checked) value.
  3634. var modelValue = ko.utils.unwrapObservable(valueAccessor());
  3635. if (valueIsArray) {
  3636. // When a checkbox is bound to an array, being checked represents its value being present in that array
  3637. element.checked = ko.utils.arrayIndexOf(modelValue, checkedValue()) >= 0;
  3638. } else if (isCheckbox) {
  3639. // When a checkbox is bound to any other value (not an array), being checked represents the value being trueish
  3640. element.checked = modelValue;
  3641. } else {
  3642. // For radio buttons, being checked means that the radio button's value corresponds to the model value
  3643. element.checked = (checkedValue() === modelValue);
  3644. }
  3645. };
  3646. var isCheckbox = element.type == "checkbox",
  3647. isRadio = element.type == "radio";
  3648. // Only bind to check boxes and radio buttons
  3649. if (!isCheckbox && !isRadio) {
  3650. return;
  3651. }
  3652. var rawValue = valueAccessor(),
  3653. valueIsArray = isCheckbox && (ko.utils.unwrapObservable(rawValue) instanceof Array),
  3654. rawValueIsNonArrayObservable = !(valueIsArray && rawValue.push && rawValue.splice),
  3655. oldElemValue = valueIsArray ? checkedValue() : undefined,
  3656. useCheckedValue = isRadio || valueIsArray;
  3657. // IE 6 won't allow radio buttons to be selected unless they have a name
  3658. if (isRadio && !element.name)
  3659. ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
  3660. // Set up two computeds to update the binding:
  3661. // The first responds to changes in the checkedValue value and to element clicks
  3662. ko.computed(updateModel, null, { disposeWhenNodeIsRemoved: element });
  3663. ko.utils.registerEventHandler(element, "click", updateModel);
  3664. // The second responds to changes in the model value (the one associated with the checked binding)
  3665. ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
  3666. rawValue = undefined;
  3667. }
  3668. };
  3669. ko.expressionRewriting.twoWayBindings['checked'] = true;
  3670. ko.bindingHandlers['checkedValue'] = {
  3671. 'update': function (element, valueAccessor) {
  3672. element.value = ko.utils.unwrapObservable(valueAccessor());
  3673. }
  3674. };
  3675. })();var classesWrittenByBindingKey = '__ko__cssValue';
  3676. ko.bindingHandlers['css'] = {
  3677. 'update': function (element, valueAccessor) {
  3678. var value = ko.utils.unwrapObservable(valueAccessor());
  3679. if (value !== null && typeof value == "object") {
  3680. ko.utils.objectForEach(value, function(className, shouldHaveClass) {
  3681. shouldHaveClass = ko.utils.unwrapObservable(shouldHaveClass);
  3682. ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
  3683. });
  3684. } else {
  3685. value = ko.utils.stringTrim(String(value || '')); // Make sure we don't try to store or set a non-string value
  3686. ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
  3687. element[classesWrittenByBindingKey] = value;
  3688. ko.utils.toggleDomNodeCssClass(element, value, true);
  3689. }
  3690. }
  3691. };
  3692. ko.bindingHandlers['enable'] = {
  3693. 'update': function (element, valueAccessor) {
  3694. var value = ko.utils.unwrapObservable(valueAccessor());
  3695. if (value && element.disabled)
  3696. element.removeAttribute("disabled");
  3697. else if ((!value) && (!element.disabled))
  3698. element.disabled = true;
  3699. }
  3700. };
  3701. ko.bindingHandlers['disable'] = {
  3702. 'update': function (element, valueAccessor) {
  3703. ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
  3704. }
  3705. };
  3706. // For certain common events (currently just 'click'), allow a simplified data-binding syntax
  3707. // e.g. click:handler instead of the usual full-length event:{click:handler}
  3708. function makeEventHandlerShortcut(eventName) {
  3709. ko.bindingHandlers[eventName] = {
  3710. 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  3711. var newValueAccessor = function () {
  3712. var result = {};
  3713. result[eventName] = valueAccessor();
  3714. return result;
  3715. };
  3716. return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindings, viewModel, bindingContext);
  3717. }
  3718. }
  3719. }
  3720. ko.bindingHandlers['event'] = {
  3721. 'init' : function (element, valueAccessor, allBindings, viewModel, bindingContext) {
  3722. var eventsToHandle = valueAccessor() || {};
  3723. ko.utils.objectForEach(eventsToHandle, function(eventName) {
  3724. if (typeof eventName == "string") {
  3725. ko.utils.registerEventHandler(element, eventName, function (event) {
  3726. var handlerReturnValue;
  3727. var handlerFunction = valueAccessor()[eventName];
  3728. if (!handlerFunction)
  3729. return;
  3730. try {
  3731. // Take all the event args, and prefix with the viewmodel
  3732. var argsForHandler = ko.utils.makeArray(arguments);
  3733. viewModel = bindingContext['$data'];
  3734. argsForHandler.unshift(viewModel);
  3735. handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
  3736. } finally {
  3737. if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
  3738. if (event.preventDefault)
  3739. event.preventDefault();
  3740. else
  3741. event.returnValue = false;
  3742. }
  3743. }
  3744. var bubble = allBindings.get(eventName + 'Bubble') !== false;
  3745. if (!bubble) {
  3746. event.cancelBubble = true;
  3747. if (event.stopPropagation)
  3748. event.stopPropagation();
  3749. }
  3750. });
  3751. }
  3752. });
  3753. }
  3754. };
  3755. // "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
  3756. // "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
  3757. ko.bindingHandlers['foreach'] = {
  3758. makeTemplateValueAccessor: function(valueAccessor) {
  3759. return function() {
  3760. var modelValue = valueAccessor(),
  3761. unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
  3762. // If unwrappedValue is the array, pass in the wrapped value on its own
  3763. // The value will be unwrapped and tracked within the template binding
  3764. // (See https://github.com/SteveSanderson/knockout/issues/523)
  3765. if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
  3766. return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
  3767. // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
  3768. ko.utils.unwrapObservable(modelValue);
  3769. return {
  3770. 'foreach': unwrappedValue['data'],
  3771. 'as': unwrappedValue['as'],
  3772. 'includeDestroyed': unwrappedValue['includeDestroyed'],
  3773. 'afterAdd': unwrappedValue['afterAdd'],
  3774. 'beforeRemove': unwrappedValue['beforeRemove'],
  3775. 'afterRender': unwrappedValue['afterRender'],
  3776. 'beforeMove': unwrappedValue['beforeMove'],
  3777. 'afterMove': unwrappedValue['afterMove'],
  3778. 'templateEngine': ko.nativeTemplateEngine.instance
  3779. };
  3780. };
  3781. },
  3782. 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  3783. return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
  3784. },
  3785. 'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  3786. return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindings, viewModel, bindingContext);
  3787. }
  3788. };
  3789. ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
  3790. ko.virtualElements.allowedBindings['foreach'] = true;
  3791. var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
  3792. var hasfocusLastValue = '__ko_hasfocusLastValue';
  3793. ko.bindingHandlers['hasfocus'] = {
  3794. 'init': function(element, valueAccessor, allBindings) {
  3795. var handleElementFocusChange = function(isFocused) {
  3796. // Where possible, ignore which event was raised and determine focus state using activeElement,
  3797. // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
  3798. // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
  3799. // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
  3800. // from calling 'blur()' on the element when it loses focus.
  3801. // Discussion at https://github.com/SteveSanderson/knockout/pull/352
  3802. element[hasfocusUpdatingProperty] = true;
  3803. var ownerDoc = element.ownerDocument;
  3804. if ("activeElement" in ownerDoc) {
  3805. var active;
  3806. try {
  3807. active = ownerDoc.activeElement;
  3808. } catch(e) {
  3809. // IE9 throws if you access activeElement during page load (see issue #703)
  3810. active = ownerDoc.body;
  3811. }
  3812. isFocused = (active === element);
  3813. }
  3814. var modelValue = valueAccessor();
  3815. ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'hasfocus', isFocused, true);
  3816. //cache the latest value, so we can avoid unnecessarily calling focus/blur in the update function
  3817. element[hasfocusLastValue] = isFocused;
  3818. element[hasfocusUpdatingProperty] = false;
  3819. };
  3820. var handleElementFocusIn = handleElementFocusChange.bind(null, true);
  3821. var handleElementFocusOut = handleElementFocusChange.bind(null, false);
  3822. ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
  3823. ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
  3824. ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
  3825. ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
  3826. },
  3827. 'update': function(element, valueAccessor) {
  3828. var value = !!ko.utils.unwrapObservable(valueAccessor());
  3829. if (!element[hasfocusUpdatingProperty] && element[hasfocusLastValue] !== value) {
  3830. value ? element.focus() : element.blur();
  3831. // In IE, the blur method doesn't always cause the element to lose focus (for example, if the window is not in focus).
  3832. // Setting focus to the body element does seem to be reliable in IE, but should only be used if we know that the current
  3833. // element was focused already.
  3834. if (!value && element[hasfocusLastValue]) {
  3835. element.ownerDocument.body.focus();
  3836. }
  3837. // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
  3838. ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]);
  3839. }
  3840. }
  3841. };
  3842. ko.expressionRewriting.twoWayBindings['hasfocus'] = true;
  3843. ko.bindingHandlers['hasFocus'] = ko.bindingHandlers['hasfocus']; // Make "hasFocus" an alias
  3844. ko.expressionRewriting.twoWayBindings['hasFocus'] = true;
  3845. ko.bindingHandlers['html'] = {
  3846. 'init': function() {
  3847. // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
  3848. return { 'controlsDescendantBindings': true };
  3849. },
  3850. 'update': function (element, valueAccessor) {
  3851. // setHtml will unwrap the value if needed
  3852. ko.utils.setHtml(element, valueAccessor());
  3853. }
  3854. };
  3855. // Makes a binding like with or if
  3856. function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
  3857. ko.bindingHandlers[bindingKey] = {
  3858. 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  3859. var didDisplayOnLastUpdate,
  3860. savedNodes;
  3861. ko.computed(function() {
  3862. var rawValue = valueAccessor(),
  3863. dataValue = ko.utils.unwrapObservable(rawValue),
  3864. shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
  3865. isFirstRender = !savedNodes,
  3866. needsRefresh = isFirstRender || isWith || (shouldDisplay !== didDisplayOnLastUpdate);
  3867. if (needsRefresh) {
  3868. // Save a copy of the inner nodes on the initial update, but only if we have dependencies.
  3869. if (isFirstRender && ko.computedContext.getDependenciesCount()) {
  3870. savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
  3871. }
  3872. if (shouldDisplay) {
  3873. if (!isFirstRender) {
  3874. ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes));
  3875. }
  3876. ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, rawValue) : bindingContext, element);
  3877. } else {
  3878. ko.virtualElements.emptyNode(element);
  3879. }
  3880. didDisplayOnLastUpdate = shouldDisplay;
  3881. }
  3882. }, null, { disposeWhenNodeIsRemoved: element });
  3883. return { 'controlsDescendantBindings': true };
  3884. }
  3885. };
  3886. ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
  3887. ko.virtualElements.allowedBindings[bindingKey] = true;
  3888. }
  3889. // Construct the actual binding handlers
  3890. makeWithIfBinding('if');
  3891. makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
  3892. makeWithIfBinding('with', true /* isWith */, false /* isNot */,
  3893. function(bindingContext, dataValue) {
  3894. return bindingContext.createStaticChildContext(dataValue);
  3895. }
  3896. );
  3897. var captionPlaceholder = {};
  3898. ko.bindingHandlers['options'] = {
  3899. 'init': function(element) {
  3900. if (ko.utils.tagNameLower(element) !== "select")
  3901. throw new Error("options binding applies only to SELECT elements");
  3902. // Remove all existing <option>s.
  3903. while (element.length > 0) {
  3904. element.remove(0);
  3905. }
  3906. // Ensures that the binding processor doesn't try to bind the options
  3907. return { 'controlsDescendantBindings': true };
  3908. },
  3909. 'update': function (element, valueAccessor, allBindings) {
  3910. function selectedOptions() {
  3911. return ko.utils.arrayFilter(element.options, function (node) { return node.selected; });
  3912. }
  3913. var selectWasPreviouslyEmpty = element.length == 0,
  3914. multiple = element.multiple,
  3915. previousScrollTop = (!selectWasPreviouslyEmpty && multiple) ? element.scrollTop : null,
  3916. unwrappedArray = ko.utils.unwrapObservable(valueAccessor()),
  3917. valueAllowUnset = allBindings.get('valueAllowUnset') && allBindings['has']('value'),
  3918. includeDestroyed = allBindings.get('optionsIncludeDestroyed'),
  3919. arrayToDomNodeChildrenOptions = {},
  3920. captionValue,
  3921. filteredArray,
  3922. previousSelectedValues = [];
  3923. if (!valueAllowUnset) {
  3924. if (multiple) {
  3925. previousSelectedValues = ko.utils.arrayMap(selectedOptions(), ko.selectExtensions.readValue);
  3926. } else if (element.selectedIndex >= 0) {
  3927. previousSelectedValues.push(ko.selectExtensions.readValue(element.options[element.selectedIndex]));
  3928. }
  3929. }
  3930. if (unwrappedArray) {
  3931. if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
  3932. unwrappedArray = [unwrappedArray];
  3933. // Filter out any entries marked as destroyed
  3934. filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
  3935. return includeDestroyed || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
  3936. });
  3937. // If caption is included, add it to the array
  3938. if (allBindings['has']('optionsCaption')) {
  3939. captionValue = ko.utils.unwrapObservable(allBindings.get('optionsCaption'));
  3940. // If caption value is null or undefined, don't show a caption
  3941. if (captionValue !== null && captionValue !== undefined) {
  3942. filteredArray.unshift(captionPlaceholder);
  3943. }
  3944. }
  3945. } else {
  3946. // If a falsy value is provided (e.g. null), we'll simply empty the select element
  3947. }
  3948. function applyToObject(object, predicate, defaultValue) {
  3949. var predicateType = typeof predicate;
  3950. if (predicateType == "function") // Given a function; run it against the data value
  3951. return predicate(object);
  3952. else if (predicateType == "string") // Given a string; treat it as a property name on the data value
  3953. return object[predicate];
  3954. else // Given no optionsText arg; use the data value itself
  3955. return defaultValue;
  3956. }
  3957. // The following functions can run at two different times:
  3958. // The first is when the whole array is being updated directly from this binding handler.
  3959. // The second is when an observable value for a specific array entry is updated.
  3960. // oldOptions will be empty in the first case, but will be filled with the previously generated option in the second.
  3961. var itemUpdate = false;
  3962. function optionForArrayItem(arrayEntry, index, oldOptions) {
  3963. if (oldOptions.length) {
  3964. previousSelectedValues = !valueAllowUnset && oldOptions[0].selected ? [ ko.selectExtensions.readValue(oldOptions[0]) ] : [];
  3965. itemUpdate = true;
  3966. }
  3967. var option = element.ownerDocument.createElement("option");
  3968. if (arrayEntry === captionPlaceholder) {
  3969. ko.utils.setTextContent(option, allBindings.get('optionsCaption'));
  3970. ko.selectExtensions.writeValue(option, undefined);
  3971. } else {
  3972. // Apply a value to the option element
  3973. var optionValue = applyToObject(arrayEntry, allBindings.get('optionsValue'), arrayEntry);
  3974. ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
  3975. // Apply some text to the option element
  3976. var optionText = applyToObject(arrayEntry, allBindings.get('optionsText'), optionValue);
  3977. ko.utils.setTextContent(option, optionText);
  3978. }
  3979. return [option];
  3980. }
  3981. // By using a beforeRemove callback, we delay the removal until after new items are added. This fixes a selection
  3982. // problem in IE<=8 and Firefox. See https://github.com/knockout/knockout/issues/1208
  3983. arrayToDomNodeChildrenOptions['beforeRemove'] =
  3984. function (option) {
  3985. element.removeChild(option);
  3986. };
  3987. function setSelectionCallback(arrayEntry, newOptions) {
  3988. if (itemUpdate && valueAllowUnset) {
  3989. // The model value is authoritative, so make sure its value is the one selected
  3990. // There is no need to use dependencyDetection.ignore since setDomNodeChildrenFromArrayMapping does so already.
  3991. ko.selectExtensions.writeValue(element, ko.utils.unwrapObservable(allBindings.get('value')), true /* allowUnset */);
  3992. } else if (previousSelectedValues.length) {
  3993. // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
  3994. // That's why we first added them without selection. Now it's time to set the selection.
  3995. var isSelected = ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[0])) >= 0;
  3996. ko.utils.setOptionNodeSelectionState(newOptions[0], isSelected);
  3997. // If this option was changed from being selected during a single-item update, notify the change
  3998. if (itemUpdate && !isSelected) {
  3999. ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
  4000. }
  4001. }
  4002. }
  4003. var callback = setSelectionCallback;
  4004. if (allBindings['has']('optionsAfterRender') && typeof allBindings.get('optionsAfterRender') == "function") {
  4005. callback = function(arrayEntry, newOptions) {
  4006. setSelectionCallback(arrayEntry, newOptions);
  4007. ko.dependencyDetection.ignore(allBindings.get('optionsAfterRender'), null, [newOptions[0], arrayEntry !== captionPlaceholder ? arrayEntry : undefined]);
  4008. }
  4009. }
  4010. ko.utils.setDomNodeChildrenFromArrayMapping(element, filteredArray, optionForArrayItem, arrayToDomNodeChildrenOptions, callback);
  4011. ko.dependencyDetection.ignore(function () {
  4012. if (valueAllowUnset) {
  4013. // The model value is authoritative, so make sure its value is the one selected
  4014. ko.selectExtensions.writeValue(element, ko.utils.unwrapObservable(allBindings.get('value')), true /* allowUnset */);
  4015. } else {
  4016. // Determine if the selection has changed as a result of updating the options list
  4017. var selectionChanged;
  4018. if (multiple) {
  4019. // For a multiple-select box, compare the new selection count to the previous one
  4020. // But if nothing was selected before, the selection can't have changed
  4021. selectionChanged = previousSelectedValues.length && selectedOptions().length < previousSelectedValues.length;
  4022. } else {
  4023. // For a single-select box, compare the current value to the previous value
  4024. // But if nothing was selected before or nothing is selected now, just look for a change in selection
  4025. selectionChanged = (previousSelectedValues.length && element.selectedIndex >= 0)
  4026. ? (ko.selectExtensions.readValue(element.options[element.selectedIndex]) !== previousSelectedValues[0])
  4027. : (previousSelectedValues.length || element.selectedIndex >= 0);
  4028. }
  4029. // Ensure consistency between model value and selected option.
  4030. // If the dropdown was changed so that selection is no longer the same,
  4031. // notify the value or selectedOptions binding.
  4032. if (selectionChanged) {
  4033. ko.utils.triggerEvent(element, "change");
  4034. }
  4035. }
  4036. });
  4037. // Workaround for IE bug
  4038. ko.utils.ensureSelectElementIsRenderedCorrectly(element);
  4039. if (previousScrollTop && Math.abs(previousScrollTop - element.scrollTop) > 20)
  4040. element.scrollTop = previousScrollTop;
  4041. }
  4042. };
  4043. ko.bindingHandlers['options'].optionValueDomDataKey = ko.utils.domData.nextKey();
  4044. ko.bindingHandlers['selectedOptions'] = {
  4045. 'after': ['options', 'foreach'],
  4046. 'init': function (element, valueAccessor, allBindings) {
  4047. ko.utils.registerEventHandler(element, "change", function () {
  4048. var value = valueAccessor(), valueToWrite = [];
  4049. ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
  4050. if (node.selected)
  4051. valueToWrite.push(ko.selectExtensions.readValue(node));
  4052. });
  4053. ko.expressionRewriting.writeValueToProperty(value, allBindings, 'selectedOptions', valueToWrite);
  4054. });
  4055. },
  4056. 'update': function (element, valueAccessor) {
  4057. if (ko.utils.tagNameLower(element) != "select")
  4058. throw new Error("values binding applies only to SELECT elements");
  4059. var newValue = ko.utils.unwrapObservable(valueAccessor()),
  4060. previousScrollTop = element.scrollTop;
  4061. if (newValue && typeof newValue.length == "number") {
  4062. ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
  4063. var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
  4064. if (node.selected != isSelected) { // This check prevents flashing of the select element in IE
  4065. ko.utils.setOptionNodeSelectionState(node, isSelected);
  4066. }
  4067. });
  4068. }
  4069. element.scrollTop = previousScrollTop;
  4070. }
  4071. };
  4072. ko.expressionRewriting.twoWayBindings['selectedOptions'] = true;
  4073. ko.bindingHandlers['style'] = {
  4074. 'update': function (element, valueAccessor) {
  4075. var value = ko.utils.unwrapObservable(valueAccessor() || {});
  4076. ko.utils.objectForEach(value, function(styleName, styleValue) {
  4077. styleValue = ko.utils.unwrapObservable(styleValue);
  4078. if (styleValue === null || styleValue === undefined || styleValue === false) {
  4079. // Empty string removes the value, whereas null/undefined have no effect
  4080. styleValue = "";
  4081. }
  4082. element.style[styleName] = styleValue;
  4083. });
  4084. }
  4085. };
  4086. ko.bindingHandlers['submit'] = {
  4087. 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
  4088. if (typeof valueAccessor() != "function")
  4089. throw new Error("The value for a submit binding must be a function");
  4090. ko.utils.registerEventHandler(element, "submit", function (event) {
  4091. var handlerReturnValue;
  4092. var value = valueAccessor();
  4093. try { handlerReturnValue = value.call(bindingContext['$data'], element); }
  4094. finally {
  4095. if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
  4096. if (event.preventDefault)
  4097. event.preventDefault();
  4098. else
  4099. event.returnValue = false;
  4100. }
  4101. }
  4102. });
  4103. }
  4104. };
  4105. ko.bindingHandlers['text'] = {
  4106. 'init': function() {
  4107. // Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications).
  4108. // It should also make things faster, as we no longer have to consider whether the text node might be bindable.
  4109. return { 'controlsDescendantBindings': true };
  4110. },
  4111. 'update': function (element, valueAccessor) {
  4112. ko.utils.setTextContent(element, valueAccessor());
  4113. }
  4114. };
  4115. ko.virtualElements.allowedBindings['text'] = true;
  4116. (function () {
  4117. if (window && window.navigator) {
  4118. var parseVersion = function (matches) {
  4119. if (matches) {
  4120. return parseFloat(matches[1]);
  4121. }
  4122. };
  4123. // Detect various browser versions because some old versions don't fully support the 'input' event
  4124. var operaVersion = window.opera && window.opera.version && parseInt(window.opera.version()),
  4125. userAgent = window.navigator.userAgent,
  4126. safariVersion = parseVersion(userAgent.match(/^(?:(?!chrome).)*version\/([^ ]*) safari/i)),
  4127. firefoxVersion = parseVersion(userAgent.match(/Firefox\/([^ ]*)/));
  4128. }
  4129. // IE 8 and 9 have bugs that prevent the normal events from firing when the value changes.
  4130. // But it does fire the 'selectionchange' event on many of those, presumably because the
  4131. // cursor is moving and that counts as the selection changing. The 'selectionchange' event is
  4132. // fired at the document level only and doesn't directly indicate which element changed. We
  4133. // set up just one event handler for the document and use 'activeElement' to determine which
  4134. // element was changed.
  4135. if (ko.utils.ieVersion < 10) {
  4136. var selectionChangeRegisteredName = ko.utils.domData.nextKey(),
  4137. selectionChangeHandlerName = ko.utils.domData.nextKey();
  4138. var selectionChangeHandler = function(event) {
  4139. var target = this.activeElement,
  4140. handler = target && ko.utils.domData.get(target, selectionChangeHandlerName);
  4141. if (handler) {
  4142. handler(event);
  4143. }
  4144. };
  4145. var registerForSelectionChangeEvent = function (element, handler) {
  4146. var ownerDoc = element.ownerDocument;
  4147. if (!ko.utils.domData.get(ownerDoc, selectionChangeRegisteredName)) {
  4148. ko.utils.domData.set(ownerDoc, selectionChangeRegisteredName, true);
  4149. ko.utils.registerEventHandler(ownerDoc, 'selectionchange', selectionChangeHandler);
  4150. }
  4151. ko.utils.domData.set(element, selectionChangeHandlerName, handler);
  4152. };
  4153. }
  4154. ko.bindingHandlers['textInput'] = {
  4155. 'init': function (element, valueAccessor, allBindings) {
  4156. var previousElementValue = element.value,
  4157. timeoutHandle,
  4158. elementValueBeforeEvent;
  4159. var updateModel = function (event) {
  4160. clearTimeout(timeoutHandle);
  4161. elementValueBeforeEvent = timeoutHandle = undefined;
  4162. var elementValue = element.value;
  4163. if (previousElementValue !== elementValue) {
  4164. // Provide a way for tests to know exactly which event was processed
  4165. if (DEBUG && event) element['_ko_textInputProcessedEvent'] = event.type;
  4166. previousElementValue = elementValue;
  4167. ko.expressionRewriting.writeValueToProperty(valueAccessor(), allBindings, 'textInput', elementValue);
  4168. }
  4169. };
  4170. var deferUpdateModel = function (event) {
  4171. if (!timeoutHandle) {
  4172. // The elementValueBeforeEvent variable is set *only* during the brief gap between an
  4173. // event firing and the updateModel function running. This allows us to ignore model
  4174. // updates that are from the previous state of the element, usually due to techniques
  4175. // such as rateLimit. Such updates, if not ignored, can cause keystrokes to be lost.
  4176. elementValueBeforeEvent = element.value;
  4177. var handler = DEBUG ? updateModel.bind(element, {type: event.type}) : updateModel;
  4178. timeoutHandle = ko.utils.setTimeout(handler, 4);
  4179. }
  4180. };
  4181. // IE9 will mess up the DOM if you handle events synchronously which results in DOM changes (such as other bindings);
  4182. // so we'll make sure all updates are asynchronous
  4183. var ieUpdateModel = ko.utils.ieVersion == 9 ? deferUpdateModel : updateModel;
  4184. var updateView = function () {
  4185. var modelValue = ko.utils.unwrapObservable(valueAccessor());
  4186. if (modelValue === null || modelValue === undefined) {
  4187. modelValue = '';
  4188. }
  4189. if (elementValueBeforeEvent !== undefined && modelValue === elementValueBeforeEvent) {
  4190. ko.utils.setTimeout(updateView, 4);
  4191. return;
  4192. }
  4193. // Update the element only if the element and model are different. On some browsers, updating the value
  4194. // will move the cursor to the end of the input, which would be bad while the user is typing.
  4195. if (element.value !== modelValue) {
  4196. previousElementValue = modelValue; // Make sure we ignore events (propertychange) that result from updating the value
  4197. element.value = modelValue;
  4198. }
  4199. };
  4200. var onEvent = function (event, handler) {
  4201. ko.utils.registerEventHandler(element, event, handler);
  4202. };
  4203. if (DEBUG && ko.bindingHandlers['textInput']['_forceUpdateOn']) {
  4204. // Provide a way for tests to specify exactly which events are bound
  4205. ko.utils.arrayForEach(ko.bindingHandlers['textInput']['_forceUpdateOn'], function(eventName) {
  4206. if (eventName.slice(0,5) == 'after') {
  4207. onEvent(eventName.slice(5), deferUpdateModel);
  4208. } else {
  4209. onEvent(eventName, updateModel);
  4210. }
  4211. });
  4212. } else {
  4213. if (ko.utils.ieVersion < 10) {
  4214. // Internet Explorer <= 8 doesn't support the 'input' event, but does include 'propertychange' that fires whenever
  4215. // any property of an element changes. Unlike 'input', it also fires if a property is changed from JavaScript code,
  4216. // but that's an acceptable compromise for this binding. IE 9 does support 'input', but since it doesn't fire it
  4217. // when using autocomplete, we'll use 'propertychange' for it also.
  4218. onEvent('propertychange', function(event) {
  4219. if (event.propertyName === 'value') {
  4220. ieUpdateModel(event);
  4221. }
  4222. });
  4223. if (ko.utils.ieVersion == 8) {
  4224. // IE 8 has a bug where it fails to fire 'propertychange' on the first update following a value change from
  4225. // JavaScript code. It also doesn't fire if you clear the entire value. To fix this, we bind to the following
  4226. // events too.
  4227. onEvent('keyup', updateModel); // A single keystoke
  4228. onEvent('keydown', updateModel); // The first character when a key is held down
  4229. }
  4230. if (ko.utils.ieVersion >= 8) {
  4231. // Internet Explorer 9 doesn't fire the 'input' event when deleting text, including using
  4232. // the backspace, delete, or ctrl-x keys, clicking the 'x' to clear the input, dragging text
  4233. // out of the field, and cutting or deleting text using the context menu. 'selectionchange'
  4234. // can detect all of those except dragging text out of the field, for which we use 'dragend'.
  4235. // These are also needed in IE8 because of the bug described above.
  4236. registerForSelectionChangeEvent(element, ieUpdateModel); // 'selectionchange' covers cut, paste, drop, delete, etc.
  4237. onEvent('dragend', deferUpdateModel);
  4238. }
  4239. } else {
  4240. // All other supported browsers support the 'input' event, which fires whenever the content of the element is changed
  4241. // through the user interface.
  4242. onEvent('input', updateModel);
  4243. if (safariVersion < 5 && ko.utils.tagNameLower(element) === "textarea") {
  4244. // Safari <5 doesn't fire the 'input' event for <textarea> elements (it does fire 'textInput'
  4245. // but only when typing). So we'll just catch as much as we can with keydown, cut, and paste.
  4246. onEvent('keydown', deferUpdateModel);
  4247. onEvent('paste', deferUpdateModel);
  4248. onEvent('cut', deferUpdateModel);
  4249. } else if (operaVersion < 11) {
  4250. // Opera 10 doesn't always fire the 'input' event for cut, paste, undo & drop operations.
  4251. // We can try to catch some of those using 'keydown'.
  4252. onEvent('keydown', deferUpdateModel);
  4253. } else if (firefoxVersion < 4.0) {
  4254. // Firefox <= 3.6 doesn't fire the 'input' event when text is filled in through autocomplete
  4255. onEvent('DOMAutoComplete', updateModel);
  4256. // Firefox <=3.5 doesn't fire the 'input' event when text is dropped into the input.
  4257. onEvent('dragdrop', updateModel); // <3.5
  4258. onEvent('drop', updateModel); // 3.5
  4259. }
  4260. }
  4261. }
  4262. // Bind to the change event so that we can catch programmatic updates of the value that fire this event.
  4263. onEvent('change', updateModel);
  4264. ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
  4265. }
  4266. };
  4267. ko.expressionRewriting.twoWayBindings['textInput'] = true;
  4268. // textinput is an alias for textInput
  4269. ko.bindingHandlers['textinput'] = {
  4270. // preprocess is the only way to set up a full alias
  4271. 'preprocess': function (value, name, addBinding) {
  4272. addBinding('textInput', value);
  4273. }
  4274. };
  4275. })();ko.bindingHandlers['uniqueName'] = {
  4276. 'init': function (element, valueAccessor) {
  4277. if (valueAccessor()) {
  4278. var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
  4279. ko.utils.setElementName(element, name);
  4280. }
  4281. }
  4282. };
  4283. ko.bindingHandlers['uniqueName'].currentIndex = 0;
  4284. ko.bindingHandlers['value'] = {
  4285. 'after': ['options', 'foreach'],
  4286. 'init': function (element, valueAccessor, allBindings) {
  4287. // If the value binding is placed on a radio/checkbox, then just pass through to checkedValue and quit
  4288. if (element.tagName.toLowerCase() == "input" && (element.type == "checkbox" || element.type == "radio")) {
  4289. ko.applyBindingAccessorsToNode(element, { 'checkedValue': valueAccessor });
  4290. return;
  4291. }
  4292. // Always catch "change" event; possibly other events too if asked
  4293. var eventsToCatch = ["change"];
  4294. var requestedEventsToCatch = allBindings.get("valueUpdate");
  4295. var propertyChangedFired = false;
  4296. var elementValueBeforeEvent = null;
  4297. if (requestedEventsToCatch) {
  4298. if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
  4299. requestedEventsToCatch = [requestedEventsToCatch];
  4300. ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
  4301. eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
  4302. }
  4303. var valueUpdateHandler = function() {
  4304. elementValueBeforeEvent = null;
  4305. propertyChangedFired = false;
  4306. var modelValue = valueAccessor();
  4307. var elementValue = ko.selectExtensions.readValue(element);
  4308. ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'value', elementValue);
  4309. }
  4310. // Workaround for https://github.com/SteveSanderson/knockout/issues/122
  4311. // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
  4312. var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
  4313. && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
  4314. if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
  4315. ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
  4316. ko.utils.registerEventHandler(element, "focus", function () { propertyChangedFired = false });
  4317. ko.utils.registerEventHandler(element, "blur", function() {
  4318. if (propertyChangedFired) {
  4319. valueUpdateHandler();
  4320. }
  4321. });
  4322. }
  4323. ko.utils.arrayForEach(eventsToCatch, function(eventName) {
  4324. // The syntax "after<eventname>" means "run the handler asynchronously after the event"
  4325. // This is useful, for example, to catch "keydown" events after the browser has updated the control
  4326. // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
  4327. var handler = valueUpdateHandler;
  4328. if (ko.utils.stringStartsWith(eventName, "after")) {
  4329. handler = function() {
  4330. // The elementValueBeforeEvent variable is non-null *only* during the brief gap between
  4331. // a keyX event firing and the valueUpdateHandler running, which is scheduled to happen
  4332. // at the earliest asynchronous opportunity. We store this temporary information so that
  4333. // if, between keyX and valueUpdateHandler, the underlying model value changes separately,
  4334. // we can overwrite that model value change with the value the user just typed. Otherwise,
  4335. // techniques like rateLimit can trigger model changes at critical moments that will
  4336. // override the user's inputs, causing keystrokes to be lost.
  4337. elementValueBeforeEvent = ko.selectExtensions.readValue(element);
  4338. ko.utils.setTimeout(valueUpdateHandler, 0);
  4339. };
  4340. eventName = eventName.substring("after".length);
  4341. }
  4342. ko.utils.registerEventHandler(element, eventName, handler);
  4343. });
  4344. var updateFromModel = function () {
  4345. var newValue = ko.utils.unwrapObservable(valueAccessor());
  4346. var elementValue = ko.selectExtensions.readValue(element);
  4347. if (elementValueBeforeEvent !== null && newValue === elementValueBeforeEvent) {
  4348. ko.utils.setTimeout(updateFromModel, 0);
  4349. return;
  4350. }
  4351. var valueHasChanged = (newValue !== elementValue);
  4352. if (valueHasChanged) {
  4353. if (ko.utils.tagNameLower(element) === "select") {
  4354. var allowUnset = allBindings.get('valueAllowUnset');
  4355. var applyValueAction = function () {
  4356. ko.selectExtensions.writeValue(element, newValue, allowUnset);
  4357. };
  4358. applyValueAction();
  4359. if (!allowUnset && newValue !== ko.selectExtensions.readValue(element)) {
  4360. // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
  4361. // because you're not allowed to have a model value that disagrees with a visible UI selection.
  4362. ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
  4363. } else {
  4364. // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
  4365. // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
  4366. // to apply the value as well.
  4367. ko.utils.setTimeout(applyValueAction, 0);
  4368. }
  4369. } else {
  4370. ko.selectExtensions.writeValue(element, newValue);
  4371. }
  4372. }
  4373. };
  4374. ko.computed(updateFromModel, null, { disposeWhenNodeIsRemoved: element });
  4375. },
  4376. 'update': function() {} // Keep for backwards compatibility with code that may have wrapped value binding
  4377. };
  4378. ko.expressionRewriting.twoWayBindings['value'] = true;
  4379. ko.bindingHandlers['visible'] = {
  4380. 'update': function (element, valueAccessor) {
  4381. var value = ko.utils.unwrapObservable(valueAccessor());
  4382. var isCurrentlyVisible = !(element.style.display == "none");
  4383. if (value && !isCurrentlyVisible)
  4384. element.style.display = "";
  4385. else if ((!value) && isCurrentlyVisible)
  4386. element.style.display = "none";
  4387. }
  4388. };
  4389. // 'click' is just a shorthand for the usual full-length event:{click:handler}
  4390. makeEventHandlerShortcut('click');
  4391. // If you want to make a custom template engine,
  4392. //
  4393. // [1] Inherit from this class (like ko.nativeTemplateEngine does)
  4394. // [2] Override 'renderTemplateSource', supplying a function with this signature:
  4395. //
  4396. // function (templateSource, bindingContext, options) {
  4397. // // - templateSource.text() is the text of the template you should render
  4398. // // - bindingContext.$data is the data you should pass into the template
  4399. // // - you might also want to make bindingContext.$parent, bindingContext.$parents,
  4400. // // and bindingContext.$root available in the template too
  4401. // // - options gives you access to any other properties set on "data-bind: { template: options }"
  4402. // // - templateDocument is the document object of the template
  4403. // //
  4404. // // Return value: an array of DOM nodes
  4405. // }
  4406. //
  4407. // [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
  4408. //
  4409. // function (script) {
  4410. // // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
  4411. // // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
  4412. // }
  4413. //
  4414. // This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
  4415. // If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
  4416. // and then you don't need to override 'createJavaScriptEvaluatorBlock'.
  4417. ko.templateEngine = function () { };
  4418. ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options, templateDocument) {
  4419. throw new Error("Override renderTemplateSource");
  4420. };
  4421. ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
  4422. throw new Error("Override createJavaScriptEvaluatorBlock");
  4423. };
  4424. ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
  4425. // Named template
  4426. if (typeof template == "string") {
  4427. templateDocument = templateDocument || document;
  4428. var elem = templateDocument.getElementById(template);
  4429. if (!elem)
  4430. throw new Error("Cannot find template with ID " + template);
  4431. return new ko.templateSources.domElement(elem);
  4432. } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
  4433. // Anonymous template
  4434. return new ko.templateSources.anonymousTemplate(template);
  4435. } else
  4436. throw new Error("Unknown template type: " + template);
  4437. };
  4438. ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
  4439. var templateSource = this['makeTemplateSource'](template, templateDocument);
  4440. return this['renderTemplateSource'](templateSource, bindingContext, options, templateDocument);
  4441. };
  4442. ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
  4443. // Skip rewriting if requested
  4444. if (this['allowTemplateRewriting'] === false)
  4445. return true;
  4446. return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
  4447. };
  4448. ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
  4449. var templateSource = this['makeTemplateSource'](template, templateDocument);
  4450. var rewritten = rewriterCallback(templateSource['text']());
  4451. templateSource['text'](rewritten);
  4452. templateSource['data']("isRewritten", true);
  4453. };
  4454. ko.exportSymbol('templateEngine', ko.templateEngine);
  4455. ko.templateRewriting = (function () {
  4456. var memoizeDataBindingAttributeSyntaxRegex = /(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'|[^>]*))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi;
  4457. var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
  4458. function validateDataBindValuesForRewriting(keyValueArray) {
  4459. var allValidators = ko.expressionRewriting.bindingRewriteValidators;
  4460. for (var i = 0; i < keyValueArray.length; i++) {
  4461. var key = keyValueArray[i]['key'];
  4462. if (allValidators.hasOwnProperty(key)) {
  4463. var validator = allValidators[key];
  4464. if (typeof validator === "function") {
  4465. var possibleErrorMessage = validator(keyValueArray[i]['value']);
  4466. if (possibleErrorMessage)
  4467. throw new Error(possibleErrorMessage);
  4468. } else if (!validator) {
  4469. throw new Error("This template engine does not support the '" + key + "' binding within its templates");
  4470. }
  4471. }
  4472. }
  4473. }
  4474. function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, nodeName, templateEngine) {
  4475. var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
  4476. validateDataBindValuesForRewriting(dataBindKeyValueArray);
  4477. var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray, {'valueAccessors':true});
  4478. // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
  4479. // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
  4480. // extra indirection.
  4481. var applyBindingsToNextSiblingScript =
  4482. "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()},'" + nodeName.toLowerCase() + "')";
  4483. return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
  4484. }
  4485. return {
  4486. ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
  4487. if (!templateEngine['isTemplateRewritten'](template, templateDocument))
  4488. templateEngine['rewriteTemplate'](template, function (htmlString) {
  4489. return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
  4490. }, templateDocument);
  4491. },
  4492. memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
  4493. return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
  4494. return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[4], /* tagToRetain: */ arguments[1], /* nodeName: */ arguments[2], templateEngine);
  4495. }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
  4496. return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", /* nodeName: */ "#comment", templateEngine);
  4497. });
  4498. },
  4499. applyMemoizedBindingsToNextSibling: function (bindings, nodeName) {
  4500. return ko.memoization.memoize(function (domNode, bindingContext) {
  4501. var nodeToBind = domNode.nextSibling;
  4502. if (nodeToBind && nodeToBind.nodeName.toLowerCase() === nodeName) {
  4503. ko.applyBindingAccessorsToNode(nodeToBind, bindings, bindingContext);
  4504. }
  4505. });
  4506. }
  4507. }
  4508. })();
  4509. // Exported only because it has to be referenced by string lookup from within rewritten template
  4510. ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
  4511. (function() {
  4512. // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
  4513. // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
  4514. //
  4515. // Two are provided by default:
  4516. // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
  4517. // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
  4518. // without reading/writing the actual element text content, since it will be overwritten
  4519. // with the rendered template output.
  4520. // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
  4521. // Template sources need to have the following functions:
  4522. // text() - returns the template text from your storage location
  4523. // text(value) - writes the supplied template text to your storage location
  4524. // data(key) - reads values stored using data(key, value) - see below
  4525. // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
  4526. //
  4527. // Optionally, template sources can also have the following functions:
  4528. // nodes() - returns a DOM element containing the nodes of this template, where available
  4529. // nodes(value) - writes the given DOM element to your storage location
  4530. // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
  4531. // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
  4532. //
  4533. // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
  4534. // using and overriding "makeTemplateSource" to return an instance of your custom template source.
  4535. ko.templateSources = {};
  4536. // ---- ko.templateSources.domElement -----
  4537. // template types
  4538. var templateScript = 1,
  4539. templateTextArea = 2,
  4540. templateTemplate = 3,
  4541. templateElement = 4;
  4542. ko.templateSources.domElement = function(element) {
  4543. this.domElement = element;
  4544. if (element) {
  4545. var tagNameLower = ko.utils.tagNameLower(element);
  4546. this.templateType =
  4547. tagNameLower === "script" ? templateScript :
  4548. tagNameLower === "textarea" ? templateTextArea :
  4549. // For browsers with proper <template> element support, where the .content property gives a document fragment
  4550. tagNameLower == "template" && element.content && element.content.nodeType === 11 ? templateTemplate :
  4551. templateElement;
  4552. }
  4553. }
  4554. ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
  4555. var elemContentsProperty = this.templateType === templateScript ? "text"
  4556. : this.templateType === templateTextArea ? "value"
  4557. : "innerHTML";
  4558. if (arguments.length == 0) {
  4559. return this.domElement[elemContentsProperty];
  4560. } else {
  4561. var valueToWrite = arguments[0];
  4562. if (elemContentsProperty === "innerHTML")
  4563. ko.utils.setHtml(this.domElement, valueToWrite);
  4564. else
  4565. this.domElement[elemContentsProperty] = valueToWrite;
  4566. }
  4567. };
  4568. var dataDomDataPrefix = ko.utils.domData.nextKey() + "_";
  4569. ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
  4570. if (arguments.length === 1) {
  4571. return ko.utils.domData.get(this.domElement, dataDomDataPrefix + key);
  4572. } else {
  4573. ko.utils.domData.set(this.domElement, dataDomDataPrefix + key, arguments[1]);
  4574. }
  4575. };
  4576. var templatesDomDataKey = ko.utils.domData.nextKey();
  4577. function getTemplateDomData(element) {
  4578. return ko.utils.domData.get(element, templatesDomDataKey) || {};
  4579. }
  4580. function setTemplateDomData(element, data) {
  4581. ko.utils.domData.set(element, templatesDomDataKey, data);
  4582. }
  4583. ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
  4584. var element = this.domElement;
  4585. if (arguments.length == 0) {
  4586. var templateData = getTemplateDomData(element),
  4587. containerData = templateData.containerData;
  4588. return containerData || (
  4589. this.templateType === templateTemplate ? element.content :
  4590. this.templateType === templateElement ? element :
  4591. undefined);
  4592. } else {
  4593. var valueToWrite = arguments[0];
  4594. setTemplateDomData(element, {containerData: valueToWrite});
  4595. }
  4596. };
  4597. // ---- ko.templateSources.anonymousTemplate -----
  4598. // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
  4599. // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
  4600. // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
  4601. ko.templateSources.anonymousTemplate = function(element) {
  4602. this.domElement = element;
  4603. }
  4604. ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
  4605. ko.templateSources.anonymousTemplate.prototype.constructor = ko.templateSources.anonymousTemplate;
  4606. ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
  4607. if (arguments.length == 0) {
  4608. var templateData = getTemplateDomData(this.domElement);
  4609. if (templateData.textData === undefined && templateData.containerData)
  4610. templateData.textData = templateData.containerData.innerHTML;
  4611. return templateData.textData;
  4612. } else {
  4613. var valueToWrite = arguments[0];
  4614. setTemplateDomData(this.domElement, {textData: valueToWrite});
  4615. }
  4616. };
  4617. ko.exportSymbol('templateSources', ko.templateSources);
  4618. ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
  4619. ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
  4620. })();
  4621. (function () {
  4622. var _templateEngine;
  4623. ko.setTemplateEngine = function (templateEngine) {
  4624. if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
  4625. throw new Error("templateEngine must inherit from ko.templateEngine");
  4626. _templateEngine = templateEngine;
  4627. }
  4628. function invokeForEachNodeInContinuousRange(firstNode, lastNode, action) {
  4629. var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
  4630. while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
  4631. nextInQueue = ko.virtualElements.nextSibling(node);
  4632. action(node, nextInQueue);
  4633. }
  4634. }
  4635. function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
  4636. // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
  4637. // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
  4638. // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
  4639. // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
  4640. // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
  4641. if (continuousNodeArray.length) {
  4642. var firstNode = continuousNodeArray[0],
  4643. lastNode = continuousNodeArray[continuousNodeArray.length - 1],
  4644. parentNode = firstNode.parentNode,
  4645. provider = ko.bindingProvider['instance'],
  4646. preprocessNode = provider['preprocessNode'];
  4647. if (preprocessNode) {
  4648. invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node, nextNodeInRange) {
  4649. var nodePreviousSibling = node.previousSibling;
  4650. var newNodes = preprocessNode.call(provider, node);
  4651. if (newNodes) {
  4652. if (node === firstNode)
  4653. firstNode = newNodes[0] || nextNodeInRange;
  4654. if (node === lastNode)
  4655. lastNode = newNodes[newNodes.length - 1] || nodePreviousSibling;
  4656. }
  4657. });
  4658. // Because preprocessNode can change the nodes, including the first and last nodes, update continuousNodeArray to match.
  4659. // We need the full set, including inner nodes, because the unmemoize step might remove the first node (and so the real
  4660. // first node needs to be in the array).
  4661. continuousNodeArray.length = 0;
  4662. if (!firstNode) { // preprocessNode might have removed all the nodes, in which case there's nothing left to do
  4663. return;
  4664. }
  4665. if (firstNode === lastNode) {
  4666. continuousNodeArray.push(firstNode);
  4667. } else {
  4668. continuousNodeArray.push(firstNode, lastNode);
  4669. ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
  4670. }
  4671. }
  4672. // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
  4673. // whereas a regular applyBindings won't introduce new memoized nodes
  4674. invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
  4675. if (node.nodeType === 1 || node.nodeType === 8)
  4676. ko.applyBindings(bindingContext, node);
  4677. });
  4678. invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
  4679. if (node.nodeType === 1 || node.nodeType === 8)
  4680. ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
  4681. });
  4682. // Make sure any changes done by applyBindings or unmemoize are reflected in the array
  4683. ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
  4684. }
  4685. }
  4686. function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
  4687. return nodeOrNodeArray.nodeType ? nodeOrNodeArray
  4688. : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
  4689. : null;
  4690. }
  4691. function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
  4692. options = options || {};
  4693. var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  4694. var templateDocument = (firstTargetNode || template || {}).ownerDocument;
  4695. var templateEngineToUse = (options['templateEngine'] || _templateEngine);
  4696. ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
  4697. var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
  4698. // Loosely check result is an array of DOM nodes
  4699. if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
  4700. throw new Error("Template engine must return an array of DOM nodes");
  4701. var haveAddedNodesToParent = false;
  4702. switch (renderMode) {
  4703. case "replaceChildren":
  4704. ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
  4705. haveAddedNodesToParent = true;
  4706. break;
  4707. case "replaceNode":
  4708. ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
  4709. haveAddedNodesToParent = true;
  4710. break;
  4711. case "ignoreTargetNode": break;
  4712. default:
  4713. throw new Error("Unknown renderMode: " + renderMode);
  4714. }
  4715. if (haveAddedNodesToParent) {
  4716. activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
  4717. if (options['afterRender'])
  4718. ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
  4719. }
  4720. return renderedNodesArray;
  4721. }
  4722. function resolveTemplateName(template, data, context) {
  4723. // The template can be specified as:
  4724. if (ko.isObservable(template)) {
  4725. // 1. An observable, with string value
  4726. return template();
  4727. } else if (typeof template === 'function') {
  4728. // 2. A function of (data, context) returning a string
  4729. return template(data, context);
  4730. } else {
  4731. // 3. A string
  4732. return template;
  4733. }
  4734. }
  4735. ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
  4736. options = options || {};
  4737. if ((options['templateEngine'] || _templateEngine) == undefined)
  4738. throw new Error("Set a template engine before calling renderTemplate");
  4739. renderMode = renderMode || "replaceChildren";
  4740. if (targetNodeOrNodeArray) {
  4741. var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  4742. var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
  4743. var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
  4744. return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
  4745. function () {
  4746. // Ensure we've got a proper binding context to work with
  4747. var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
  4748. ? dataOrBindingContext
  4749. : new ko.bindingContext(dataOrBindingContext, null, null, null, { "exportDependencies": true });
  4750. var templateName = resolveTemplateName(template, bindingContext['$data'], bindingContext),
  4751. renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
  4752. if (renderMode == "replaceNode") {
  4753. targetNodeOrNodeArray = renderedNodesArray;
  4754. firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  4755. }
  4756. },
  4757. null,
  4758. { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
  4759. );
  4760. } else {
  4761. // We don't yet have a DOM node to evaluate, so use a memo and render the template later when there is a DOM node
  4762. return ko.memoization.memoize(function (domNode) {
  4763. ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
  4764. });
  4765. }
  4766. };
  4767. ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
  4768. // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
  4769. // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
  4770. var arrayItemContext;
  4771. // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
  4772. var executeTemplateForArrayItem = function (arrayValue, index) {
  4773. // Support selecting template as a function of the data being rendered
  4774. arrayItemContext = parentBindingContext['createChildContext'](arrayValue, options['as'], function(context) {
  4775. context['$index'] = index;
  4776. });
  4777. var templateName = resolveTemplateName(template, arrayValue, arrayItemContext);
  4778. return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
  4779. }
  4780. // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
  4781. var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
  4782. activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
  4783. if (options['afterRender'])
  4784. options['afterRender'](addedNodesArray, arrayValue);
  4785. // release the "cache" variable, so that it can be collected by
  4786. // the GC when its value isn't used from within the bindings anymore.
  4787. arrayItemContext = null;
  4788. };
  4789. return ko.dependentObservable(function () {
  4790. var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
  4791. if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
  4792. unwrappedArray = [unwrappedArray];
  4793. // Filter out any entries marked as destroyed
  4794. var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
  4795. return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
  4796. });
  4797. // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
  4798. // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
  4799. ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
  4800. }, null, { disposeWhenNodeIsRemoved: targetNode });
  4801. };
  4802. var templateComputedDomDataKey = ko.utils.domData.nextKey();
  4803. function disposeOldComputedAndStoreNewOne(element, newComputed) {
  4804. var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
  4805. if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
  4806. oldComputed.dispose();
  4807. ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
  4808. }
  4809. ko.bindingHandlers['template'] = {
  4810. 'init': function(element, valueAccessor) {
  4811. // Support anonymous templates
  4812. var bindingValue = ko.utils.unwrapObservable(valueAccessor());
  4813. if (typeof bindingValue == "string" || bindingValue['name']) {
  4814. // It's a named template - clear the element
  4815. ko.virtualElements.emptyNode(element);
  4816. } else if ('nodes' in bindingValue) {
  4817. // We've been given an array of DOM nodes. Save them as the template source.
  4818. // There is no known use case for the node array being an observable array (if the output
  4819. // varies, put that behavior *into* your template - that's what templates are for), and
  4820. // the implementation would be a mess, so assert that it's not observable.
  4821. var nodes = bindingValue['nodes'] || [];
  4822. if (ko.isObservable(nodes)) {
  4823. throw new Error('The "nodes" option must be a plain, non-observable array.');
  4824. }
  4825. var container = ko.utils.moveCleanedNodesToContainerElement(nodes); // This also removes the nodes from their current parent
  4826. new ko.templateSources.anonymousTemplate(element)['nodes'](container);
  4827. } else {
  4828. // It's an anonymous template - store the element contents, then clear the element
  4829. var templateNodes = ko.virtualElements.childNodes(element),
  4830. container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
  4831. new ko.templateSources.anonymousTemplate(element)['nodes'](container);
  4832. }
  4833. return { 'controlsDescendantBindings': true };
  4834. },
  4835. 'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
  4836. var value = valueAccessor(),
  4837. options = ko.utils.unwrapObservable(value),
  4838. shouldDisplay = true,
  4839. templateComputed = null,
  4840. templateName;
  4841. if (typeof options == "string") {
  4842. templateName = value;
  4843. options = {};
  4844. } else {
  4845. templateName = options['name'];
  4846. // Support "if"/"ifnot" conditions
  4847. if ('if' in options)
  4848. shouldDisplay = ko.utils.unwrapObservable(options['if']);
  4849. if (shouldDisplay && 'ifnot' in options)
  4850. shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
  4851. }
  4852. if ('foreach' in options) {
  4853. // Render once for each data point (treating data set as empty if shouldDisplay==false)
  4854. var dataArray = (shouldDisplay && options['foreach']) || [];
  4855. templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
  4856. } else if (!shouldDisplay) {
  4857. ko.virtualElements.emptyNode(element);
  4858. } else {
  4859. // Render once for this single data point (or use the viewModel if no data was provided)
  4860. var innerBindingContext = ('data' in options) ?
  4861. bindingContext.createStaticChildContext(options['data'], options['as']) : // Given an explitit 'data' value, we create a child binding context for it
  4862. bindingContext; // Given no explicit 'data' value, we retain the same binding context
  4863. templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
  4864. }
  4865. // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
  4866. disposeOldComputedAndStoreNewOne(element, templateComputed);
  4867. }
  4868. };
  4869. // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
  4870. ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
  4871. var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
  4872. if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
  4873. return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
  4874. if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
  4875. return null; // Named templates can be rewritten, so return "no error"
  4876. return "This template engine does not support anonymous templates nested within its templates";
  4877. };
  4878. ko.virtualElements.allowedBindings['template'] = true;
  4879. })();
  4880. ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
  4881. ko.exportSymbol('renderTemplate', ko.renderTemplate);
  4882. // Go through the items that have been added and deleted and try to find matches between them.
  4883. ko.utils.findMovesInArrayComparison = function (left, right, limitFailedCompares) {
  4884. if (left.length && right.length) {
  4885. var failedCompares, l, r, leftItem, rightItem;
  4886. for (failedCompares = l = 0; (!limitFailedCompares || failedCompares < limitFailedCompares) && (leftItem = left[l]); ++l) {
  4887. for (r = 0; rightItem = right[r]; ++r) {
  4888. if (leftItem['value'] === rightItem['value']) {
  4889. leftItem['moved'] = rightItem['index'];
  4890. rightItem['moved'] = leftItem['index'];
  4891. right.splice(r, 1); // This item is marked as moved; so remove it from right list
  4892. failedCompares = r = 0; // Reset failed compares count because we're checking for consecutive failures
  4893. break;
  4894. }
  4895. }
  4896. failedCompares += r;
  4897. }
  4898. }
  4899. };
  4900. ko.utils.compareArrays = (function () {
  4901. var statusNotInOld = 'added', statusNotInNew = 'deleted';
  4902. // Simple calculation based on Levenshtein distance.
  4903. function compareArrays(oldArray, newArray, options) {
  4904. // For backward compatibility, if the third arg is actually a bool, interpret
  4905. // it as the old parameter 'dontLimitMoves'. Newer code should use { dontLimitMoves: true }.
  4906. options = (typeof options === 'boolean') ? { 'dontLimitMoves': options } : (options || {});
  4907. oldArray = oldArray || [];
  4908. newArray = newArray || [];
  4909. if (oldArray.length < newArray.length)
  4910. return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, options);
  4911. else
  4912. return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, options);
  4913. }
  4914. function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, options) {
  4915. var myMin = Math.min,
  4916. myMax = Math.max,
  4917. editDistanceMatrix = [],
  4918. smlIndex, smlIndexMax = smlArray.length,
  4919. bigIndex, bigIndexMax = bigArray.length,
  4920. compareRange = (bigIndexMax - smlIndexMax) || 1,
  4921. maxDistance = smlIndexMax + bigIndexMax + 1,
  4922. thisRow, lastRow,
  4923. bigIndexMaxForRow, bigIndexMinForRow;
  4924. for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
  4925. lastRow = thisRow;
  4926. editDistanceMatrix.push(thisRow = []);
  4927. bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
  4928. bigIndexMinForRow = myMax(0, smlIndex - 1);
  4929. for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
  4930. if (!bigIndex)
  4931. thisRow[bigIndex] = smlIndex + 1;
  4932. else if (!smlIndex) // Top row - transform empty array into new array via additions
  4933. thisRow[bigIndex] = bigIndex + 1;
  4934. else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
  4935. thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
  4936. else {
  4937. var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
  4938. var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
  4939. thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
  4940. }
  4941. }
  4942. }
  4943. var editScript = [], meMinusOne, notInSml = [], notInBig = [];
  4944. for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
  4945. meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
  4946. if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
  4947. notInSml.push(editScript[editScript.length] = { // added
  4948. 'status': statusNotInSml,
  4949. 'value': bigArray[--bigIndex],
  4950. 'index': bigIndex });
  4951. } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
  4952. notInBig.push(editScript[editScript.length] = { // deleted
  4953. 'status': statusNotInBig,
  4954. 'value': smlArray[--smlIndex],
  4955. 'index': smlIndex });
  4956. } else {
  4957. --bigIndex;
  4958. --smlIndex;
  4959. if (!options['sparse']) {
  4960. editScript.push({
  4961. 'status': "retained",
  4962. 'value': bigArray[bigIndex] });
  4963. }
  4964. }
  4965. }
  4966. // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
  4967. // smlIndexMax keeps the time complexity of this algorithm linear.
  4968. ko.utils.findMovesInArrayComparison(notInBig, notInSml, !options['dontLimitMoves'] && smlIndexMax * 10);
  4969. return editScript.reverse();
  4970. }
  4971. return compareArrays;
  4972. })();
  4973. ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
  4974. (function () {
  4975. // Objective:
  4976. // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
  4977. // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
  4978. // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
  4979. // so that its children is again the concatenation of the mappings of the array elements, but don't re-map any array elements that we
  4980. // previously mapped - retain those nodes, and just insert/delete other ones
  4981. // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
  4982. // You can use this, for example, to activate bindings on those nodes.
  4983. function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
  4984. // Map this array value inside a dependentObservable so we re-map when any dependency changes
  4985. var mappedNodes = [];
  4986. var dependentObservable = ko.dependentObservable(function() {
  4987. var newMappedNodes = mapping(valueToMap, index, ko.utils.fixUpContinuousNodeArray(mappedNodes, containerNode)) || [];
  4988. // On subsequent evaluations, just replace the previously-inserted DOM nodes
  4989. if (mappedNodes.length > 0) {
  4990. ko.utils.replaceDomNodes(mappedNodes, newMappedNodes);
  4991. if (callbackAfterAddingNodes)
  4992. ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
  4993. }
  4994. // Replace the contents of the mappedNodes array, thereby updating the record
  4995. // of which nodes would be deleted if valueToMap was itself later removed
  4996. mappedNodes.length = 0;
  4997. ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
  4998. }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return !ko.utils.anyDomNodeIsAttachedToDocument(mappedNodes); } });
  4999. return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
  5000. }
  5001. var lastMappingResultDomDataKey = ko.utils.domData.nextKey(),
  5002. deletedItemDummyValue = ko.utils.domData.nextKey();
  5003. ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
  5004. // Compare the provided array against the previous one
  5005. array = array || [];
  5006. options = options || {};
  5007. var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
  5008. var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
  5009. var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
  5010. var editScript = ko.utils.compareArrays(lastArray, array, options['dontLimitMoves']);
  5011. // Build the new mapping result
  5012. var newMappingResult = [];
  5013. var lastMappingResultIndex = 0;
  5014. var newMappingResultIndex = 0;
  5015. var nodesToDelete = [];
  5016. var itemsToProcess = [];
  5017. var itemsForBeforeRemoveCallbacks = [];
  5018. var itemsForMoveCallbacks = [];
  5019. var itemsForAfterAddCallbacks = [];
  5020. var mapData;
  5021. function itemMovedOrRetained(editScriptIndex, oldPosition) {
  5022. mapData = lastMappingResult[oldPosition];
  5023. if (newMappingResultIndex !== oldPosition)
  5024. itemsForMoveCallbacks[editScriptIndex] = mapData;
  5025. // Since updating the index might change the nodes, do so before calling fixUpContinuousNodeArray
  5026. mapData.indexObservable(newMappingResultIndex++);
  5027. ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode);
  5028. newMappingResult.push(mapData);
  5029. itemsToProcess.push(mapData);
  5030. }
  5031. function callCallback(callback, items) {
  5032. if (callback) {
  5033. for (var i = 0, n = items.length; i < n; i++) {
  5034. if (items[i]) {
  5035. ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
  5036. callback(node, i, items[i].arrayEntry);
  5037. });
  5038. }
  5039. }
  5040. }
  5041. }
  5042. for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
  5043. movedIndex = editScriptItem['moved'];
  5044. switch (editScriptItem['status']) {
  5045. case "deleted":
  5046. if (movedIndex === undefined) {
  5047. mapData = lastMappingResult[lastMappingResultIndex];
  5048. // Stop tracking changes to the mapping for these nodes
  5049. if (mapData.dependentObservable) {
  5050. mapData.dependentObservable.dispose();
  5051. mapData.dependentObservable = undefined;
  5052. }
  5053. // Queue these nodes for later removal
  5054. if (ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode).length) {
  5055. if (options['beforeRemove']) {
  5056. newMappingResult.push(mapData);
  5057. itemsToProcess.push(mapData);
  5058. if (mapData.arrayEntry === deletedItemDummyValue) {
  5059. mapData = null;
  5060. } else {
  5061. itemsForBeforeRemoveCallbacks[i] = mapData;
  5062. }
  5063. }
  5064. if (mapData) {
  5065. nodesToDelete.push.apply(nodesToDelete, mapData.mappedNodes);
  5066. }
  5067. }
  5068. }
  5069. lastMappingResultIndex++;
  5070. break;
  5071. case "retained":
  5072. itemMovedOrRetained(i, lastMappingResultIndex++);
  5073. break;
  5074. case "added":
  5075. if (movedIndex !== undefined) {
  5076. itemMovedOrRetained(i, movedIndex);
  5077. } else {
  5078. mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
  5079. newMappingResult.push(mapData);
  5080. itemsToProcess.push(mapData);
  5081. if (!isFirstExecution)
  5082. itemsForAfterAddCallbacks[i] = mapData;
  5083. }
  5084. break;
  5085. }
  5086. }
  5087. // Store a copy of the array items we just considered so we can difference it next time
  5088. ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
  5089. // Call beforeMove first before any changes have been made to the DOM
  5090. callCallback(options['beforeMove'], itemsForMoveCallbacks);
  5091. // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
  5092. ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
  5093. // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
  5094. for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
  5095. // Get nodes for newly added items
  5096. if (!mapData.mappedNodes)
  5097. ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
  5098. // Put nodes in the right place if they aren't there already
  5099. for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
  5100. if (node !== nextNode)
  5101. ko.virtualElements.insertAfter(domNode, node, lastNode);
  5102. }
  5103. // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
  5104. if (!mapData.initialized && callbackAfterAddingNodes) {
  5105. callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
  5106. mapData.initialized = true;
  5107. }
  5108. }
  5109. // If there's a beforeRemove callback, call it after reordering.
  5110. // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
  5111. // some sort of animation, which is why we first reorder the nodes that will be removed. If the
  5112. // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
  5113. // Perhaps we'll make that change in the future if this scenario becomes more common.
  5114. callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
  5115. // Replace the stored values of deleted items with a dummy value. This provides two benefits: it marks this item
  5116. // as already "removed" so we won't call beforeRemove for it again, and it ensures that the item won't match up
  5117. // with an actual item in the array and appear as "retained" or "moved".
  5118. for (i = 0; i < itemsForBeforeRemoveCallbacks.length; ++i) {
  5119. if (itemsForBeforeRemoveCallbacks[i]) {
  5120. itemsForBeforeRemoveCallbacks[i].arrayEntry = deletedItemDummyValue;
  5121. }
  5122. }
  5123. // Finally call afterMove and afterAdd callbacks
  5124. callCallback(options['afterMove'], itemsForMoveCallbacks);
  5125. callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
  5126. }
  5127. })();
  5128. ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
  5129. ko.nativeTemplateEngine = function () {
  5130. this['allowTemplateRewriting'] = false;
  5131. }
  5132. ko.nativeTemplateEngine.prototype = new ko.templateEngine();
  5133. ko.nativeTemplateEngine.prototype.constructor = ko.nativeTemplateEngine;
  5134. ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options, templateDocument) {
  5135. var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
  5136. templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
  5137. templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
  5138. if (templateNodes) {
  5139. return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
  5140. } else {
  5141. var templateText = templateSource['text']();
  5142. return ko.utils.parseHtmlFragment(templateText, templateDocument);
  5143. }
  5144. };
  5145. ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
  5146. ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
  5147. ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
  5148. (function() {
  5149. ko.jqueryTmplTemplateEngine = function () {
  5150. // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
  5151. // doesn't expose a version number, so we have to infer it.
  5152. // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
  5153. // which KO internally refers to as version "2", so older versions are no longer detected.
  5154. var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
  5155. if (!jQueryInstance || !(jQueryInstance['tmpl']))
  5156. return 0;
  5157. // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
  5158. try {
  5159. if (jQueryInstance['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
  5160. // Since 1.0.0pre, custom tags should append markup to an array called "__"
  5161. return 2; // Final version of jquery.tmpl
  5162. }
  5163. } catch(ex) { /* Apparently not the version we were looking for */ }
  5164. return 1; // Any older version that we don't support
  5165. })();
  5166. function ensureHasReferencedJQueryTemplates() {
  5167. if (jQueryTmplVersion < 2)
  5168. throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
  5169. }
  5170. function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
  5171. return jQueryInstance['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
  5172. }
  5173. this['renderTemplateSource'] = function(templateSource, bindingContext, options, templateDocument) {
  5174. templateDocument = templateDocument || document;
  5175. options = options || {};
  5176. ensureHasReferencedJQueryTemplates();
  5177. // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
  5178. var precompiled = templateSource['data']('precompiled');
  5179. if (!precompiled) {
  5180. var templateText = templateSource['text']() || "";
  5181. // Wrap in "with($whatever.koBindingContext) { ... }"
  5182. templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
  5183. precompiled = jQueryInstance['template'](null, templateText);
  5184. templateSource['data']('precompiled', precompiled);
  5185. }
  5186. var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
  5187. var jQueryTemplateOptions = jQueryInstance['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
  5188. var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
  5189. resultNodes['appendTo'](templateDocument.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
  5190. jQueryInstance['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
  5191. return resultNodes;
  5192. };
  5193. this['createJavaScriptEvaluatorBlock'] = function(script) {
  5194. return "{{ko_code ((function() { return " + script + " })()) }}";
  5195. };
  5196. this['addTemplate'] = function(templateName, templateMarkup) {
  5197. document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "<" + "/script>");
  5198. };
  5199. if (jQueryTmplVersion > 0) {
  5200. jQueryInstance['tmpl']['tag']['ko_code'] = {
  5201. open: "__.push($1 || '');"
  5202. };
  5203. jQueryInstance['tmpl']['tag']['ko_with'] = {
  5204. open: "with($1) {",
  5205. close: "} "
  5206. };
  5207. }
  5208. };
  5209. ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
  5210. ko.jqueryTmplTemplateEngine.prototype.constructor = ko.jqueryTmplTemplateEngine;
  5211. // Use this one by default *only if jquery.tmpl is referenced*
  5212. var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
  5213. if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
  5214. ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
  5215. ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
  5216. })();
  5217. }));
  5218. }());
  5219. })();