590f19b8e587b01dff921d4441469d3b298aaf8d.svn-base 264 KB

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