knockout-3.1.0.debug.js 215 KB

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