knockout-2.1.0.debug.js 167 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443
  1. // Knockout JavaScript library v2.1.0
  2. // (c) Steven Sanderson - http://knockoutjs.com/
  3. // License: MIT (http://www.opensource.org/licenses/mit-license.php)
  4. (function(window,document,navigator,undefined){
  5. var DEBUG=true;
  6. !function(factory) {
  7. // Support three module loading scenarios
  8. if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
  9. // [1] CommonJS/Node.js
  10. var target = module['exports'] || exports; // module.exports is for Node.js
  11. factory(target);
  12. } else if (typeof define === 'function' && define['amd']) {
  13. // [2] AMD anonymous module
  14. define(['exports'], factory);
  15. } else {
  16. // [3] No module loader (plain <script> tag) - put directly in global namespace
  17. factory(window['ko'] = {});
  18. }
  19. }(function(koExports){
  20. // Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
  21. // In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
  22. var ko = typeof koExports !== 'undefined' ? koExports : {};
  23. // Google Closure Compiler helpers (used only to make the minified file smaller)
  24. ko.exportSymbol = function(koPath, object) {
  25. var tokens = koPath.split(".");
  26. // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
  27. // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
  28. var target = ko;
  29. for (var i = 0; i < tokens.length - 1; i++)
  30. target = target[tokens[i]];
  31. target[tokens[tokens.length - 1]] = object;
  32. };
  33. ko.exportProperty = function(owner, publicName, object) {
  34. owner[publicName] = object;
  35. };
  36. ko.version = "2.1.0";
  37. ko.exportSymbol('version', ko.version);
  38. ko.utils = new (function () {
  39. var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
  40. // 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)
  41. var knownEvents = {}, knownEventTypesByEventName = {};
  42. var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';
  43. knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
  44. knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
  45. for (var eventType in knownEvents) {
  46. var knownEventsForType = knownEvents[eventType];
  47. if (knownEventsForType.length) {
  48. for (var i = 0, j = knownEventsForType.length; i < j; i++)
  49. knownEventTypesByEventName[knownEventsForType[i]] = eventType;
  50. }
  51. }
  52. var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
  53. // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
  54. var ieVersion = (function() {
  55. var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
  56. // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
  57. while (
  58. div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
  59. iElems[0]
  60. );
  61. return version > 4 ? version : undefined;
  62. }());
  63. var isIe6 = ieVersion === 6,
  64. isIe7 = ieVersion === 7;
  65. function isClickOnCheckableElement(element, eventType) {
  66. if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
  67. if (eventType.toLowerCase() != "click") return false;
  68. var inputType = element.type;
  69. return (inputType == "checkbox") || (inputType == "radio");
  70. }
  71. return {
  72. fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
  73. arrayForEach: function (array, action) {
  74. for (var i = 0, j = array.length; i < j; i++)
  75. action(array[i]);
  76. },
  77. arrayIndexOf: function (array, item) {
  78. if (typeof Array.prototype.indexOf == "function")
  79. return Array.prototype.indexOf.call(array, item);
  80. for (var i = 0, j = array.length; i < j; i++)
  81. if (array[i] === item)
  82. return i;
  83. return -1;
  84. },
  85. arrayFirst: function (array, predicate, predicateOwner) {
  86. for (var i = 0, j = array.length; i < j; i++)
  87. if (predicate.call(predicateOwner, array[i]))
  88. return array[i];
  89. return null;
  90. },
  91. arrayRemoveItem: function (array, itemToRemove) {
  92. var index = ko.utils.arrayIndexOf(array, itemToRemove);
  93. if (index >= 0)
  94. array.splice(index, 1);
  95. },
  96. arrayGetDistinctValues: function (array) {
  97. array = array || [];
  98. var result = [];
  99. for (var i = 0, j = array.length; i < j; i++) {
  100. if (ko.utils.arrayIndexOf(result, array[i]) < 0)
  101. result.push(array[i]);
  102. }
  103. return result;
  104. },
  105. arrayMap: function (array, mapping) {
  106. array = array || [];
  107. var result = [];
  108. for (var i = 0, j = array.length; i < j; i++)
  109. result.push(mapping(array[i]));
  110. return result;
  111. },
  112. arrayFilter: function (array, predicate) {
  113. array = array || [];
  114. var result = [];
  115. for (var i = 0, j = array.length; i < j; i++)
  116. if (predicate(array[i]))
  117. result.push(array[i]);
  118. return result;
  119. },
  120. arrayPushAll: function (array, valuesToPush) {
  121. if (valuesToPush instanceof Array)
  122. array.push.apply(array, valuesToPush);
  123. else
  124. for (var i = 0, j = valuesToPush.length; i < j; i++)
  125. array.push(valuesToPush[i]);
  126. return array;
  127. },
  128. extend: function (target, source) {
  129. if (source) {
  130. for(var prop in source) {
  131. if(source.hasOwnProperty(prop)) {
  132. target[prop] = source[prop];
  133. }
  134. }
  135. }
  136. return target;
  137. },
  138. emptyDomNode: function (domNode) {
  139. while (domNode.firstChild) {
  140. ko.removeNode(domNode.firstChild);
  141. }
  142. },
  143. moveCleanedNodesToContainerElement: function(nodes) {
  144. // Ensure it's a real array, as we're about to reparent the nodes and
  145. // we don't want the underlying collection to change while we're doing that.
  146. var nodesArray = ko.utils.makeArray(nodes);
  147. var container = document.createElement('div');
  148. for (var i = 0, j = nodesArray.length; i < j; i++) {
  149. ko.cleanNode(nodesArray[i]);
  150. container.appendChild(nodesArray[i]);
  151. }
  152. return container;
  153. },
  154. setDomNodeChildren: function (domNode, childNodes) {
  155. ko.utils.emptyDomNode(domNode);
  156. if (childNodes) {
  157. for (var i = 0, j = childNodes.length; i < j; i++)
  158. domNode.appendChild(childNodes[i]);
  159. }
  160. },
  161. replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
  162. var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
  163. if (nodesToReplaceArray.length > 0) {
  164. var insertionPoint = nodesToReplaceArray[0];
  165. var parent = insertionPoint.parentNode;
  166. for (var i = 0, j = newNodesArray.length; i < j; i++)
  167. parent.insertBefore(newNodesArray[i], insertionPoint);
  168. for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
  169. ko.removeNode(nodesToReplaceArray[i]);
  170. }
  171. }
  172. },
  173. setOptionNodeSelectionState: function (optionNode, isSelected) {
  174. // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
  175. if (navigator.userAgent.indexOf("MSIE 6") >= 0)
  176. optionNode.setAttribute("selected", isSelected);
  177. else
  178. optionNode.selected = isSelected;
  179. },
  180. stringTrim: function (string) {
  181. return (string || "").replace(stringTrimRegex, "");
  182. },
  183. stringTokenize: function (string, delimiter) {
  184. var result = [];
  185. var tokens = (string || "").split(delimiter);
  186. for (var i = 0, j = tokens.length; i < j; i++) {
  187. var trimmed = ko.utils.stringTrim(tokens[i]);
  188. if (trimmed !== "")
  189. result.push(trimmed);
  190. }
  191. return result;
  192. },
  193. stringStartsWith: function (string, startsWith) {
  194. string = string || "";
  195. if (startsWith.length > string.length)
  196. return false;
  197. return string.substring(0, startsWith.length) === startsWith;
  198. },
  199. buildEvalWithinScopeFunction: function (expression, scopeLevels) {
  200. // Build the source for a function that evaluates "expression"
  201. // For each scope variable, add an extra level of "with" nesting
  202. // Example result: with(sc[1]) { with(sc[0]) { return (expression) } }
  203. var functionBody = "return (" + expression + ")";
  204. for (var i = 0; i < scopeLevels; i++) {
  205. functionBody = "with(sc[" + i + "]) { " + functionBody + " } ";
  206. }
  207. return new Function("sc", functionBody);
  208. },
  209. domNodeIsContainedBy: function (node, containedByNode) {
  210. if (containedByNode.compareDocumentPosition)
  211. return (containedByNode.compareDocumentPosition(node) & 16) == 16;
  212. while (node != null) {
  213. if (node == containedByNode)
  214. return true;
  215. node = node.parentNode;
  216. }
  217. return false;
  218. },
  219. domNodeIsAttachedToDocument: function (node) {
  220. return ko.utils.domNodeIsContainedBy(node, node.ownerDocument);
  221. },
  222. tagNameLower: function(element) {
  223. // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
  224. // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
  225. // we don't need to do the .toLowerCase() as it will always be lower case anyway.
  226. return element && element.tagName && element.tagName.toLowerCase();
  227. },
  228. registerEventHandler: function (element, eventType, handler) {
  229. var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
  230. if (!mustUseAttachEvent && typeof jQuery != "undefined") {
  231. if (isClickOnCheckableElement(element, eventType)) {
  232. // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
  233. // it toggles the element checked state *after* the click event handlers run, whereas native
  234. // click events toggle the checked state *before* the event handler.
  235. // Fix this by intecepting the handler and applying the correct checkedness before it runs.
  236. var originalHandler = handler;
  237. handler = function(event, eventData) {
  238. var jQuerySuppliedCheckedState = this.checked;
  239. if (eventData)
  240. this.checked = eventData.checkedStateBeforeEvent !== true;
  241. originalHandler.call(this, event);
  242. this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
  243. };
  244. }
  245. jQuery(element)['bind'](eventType, handler);
  246. } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
  247. element.addEventListener(eventType, handler, false);
  248. else if (typeof element.attachEvent != "undefined")
  249. element.attachEvent("on" + eventType, function (event) {
  250. handler.call(element, event);
  251. });
  252. else
  253. throw new Error("Browser doesn't support addEventListener or attachEvent");
  254. },
  255. triggerEvent: function (element, eventType) {
  256. if (!(element && element.nodeType))
  257. throw new Error("element must be a DOM node when calling triggerEvent");
  258. if (typeof jQuery != "undefined") {
  259. var eventData = [];
  260. if (isClickOnCheckableElement(element, eventType)) {
  261. // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
  262. eventData.push({ checkedStateBeforeEvent: element.checked });
  263. }
  264. jQuery(element)['trigger'](eventType, eventData);
  265. } else if (typeof document.createEvent == "function") {
  266. if (typeof element.dispatchEvent == "function") {
  267. var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
  268. var event = document.createEvent(eventCategory);
  269. event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
  270. element.dispatchEvent(event);
  271. }
  272. else
  273. throw new Error("The supplied element doesn't support dispatchEvent");
  274. } else if (typeof element.fireEvent != "undefined") {
  275. // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
  276. // so to make it consistent, we'll do it manually here
  277. if (isClickOnCheckableElement(element, eventType))
  278. element.checked = element.checked !== true;
  279. element.fireEvent("on" + eventType);
  280. }
  281. else
  282. throw new Error("Browser doesn't support triggering events");
  283. },
  284. unwrapObservable: function (value) {
  285. return ko.isObservable(value) ? value() : value;
  286. },
  287. toggleDomNodeCssClass: function (node, className, shouldHaveClass) {
  288. var currentClassNames = (node.className || "").split(/\s+/);
  289. var hasClass = ko.utils.arrayIndexOf(currentClassNames, className) >= 0;
  290. if (shouldHaveClass && !hasClass) {
  291. node.className += (currentClassNames[0] ? " " : "") + className;
  292. } else if (hasClass && !shouldHaveClass) {
  293. var newClassName = "";
  294. for (var i = 0; i < currentClassNames.length; i++)
  295. if (currentClassNames[i] != className)
  296. newClassName += currentClassNames[i] + " ";
  297. node.className = ko.utils.stringTrim(newClassName);
  298. }
  299. },
  300. setTextContent: function(element, textContent) {
  301. var value = ko.utils.unwrapObservable(textContent);
  302. if ((value === null) || (value === undefined))
  303. value = "";
  304. 'innerText' in element ? element.innerText = value
  305. : element.textContent = value;
  306. if (ieVersion >= 9) {
  307. // Believe it or not, this actually fixes an IE9 rendering bug
  308. // (See https://github.com/SteveSanderson/knockout/issues/209)
  309. element.style.display = element.style.display;
  310. }
  311. },
  312. ensureSelectElementIsRenderedCorrectly: function(selectElement) {
  313. // 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.
  314. // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
  315. if (ieVersion >= 9) {
  316. var originalWidth = selectElement.style.width;
  317. selectElement.style.width = 0;
  318. selectElement.style.width = originalWidth;
  319. }
  320. },
  321. range: function (min, max) {
  322. min = ko.utils.unwrapObservable(min);
  323. max = ko.utils.unwrapObservable(max);
  324. var result = [];
  325. for (var i = min; i <= max; i++)
  326. result.push(i);
  327. return result;
  328. },
  329. makeArray: function(arrayLikeObject) {
  330. var result = [];
  331. for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
  332. result.push(arrayLikeObject[i]);
  333. };
  334. return result;
  335. },
  336. isIe6 : isIe6,
  337. isIe7 : isIe7,
  338. ieVersion : ieVersion,
  339. getFormFields: function(form, fieldName) {
  340. var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
  341. var isMatchingField = (typeof fieldName == 'string')
  342. ? function(field) { return field.name === fieldName }
  343. : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
  344. var matches = [];
  345. for (var i = fields.length - 1; i >= 0; i--) {
  346. if (isMatchingField(fields[i]))
  347. matches.push(fields[i]);
  348. };
  349. return matches;
  350. },
  351. parseJson: function (jsonString) {
  352. if (typeof jsonString == "string") {
  353. jsonString = ko.utils.stringTrim(jsonString);
  354. if (jsonString) {
  355. if (window.JSON && window.JSON.parse) // Use native parsing where available
  356. return window.JSON.parse(jsonString);
  357. return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
  358. }
  359. }
  360. return null;
  361. },
  362. stringifyJson: function (data, replacer, space) { // replacer and space are optional
  363. if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
  364. 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");
  365. return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
  366. },
  367. postJson: function (urlOrForm, data, options) {
  368. options = options || {};
  369. var params = options['params'] || {};
  370. var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
  371. var url = urlOrForm;
  372. // If we were given a form, use its 'action' URL and pick out any requested field values
  373. if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
  374. var originalForm = urlOrForm;
  375. url = originalForm.action;
  376. for (var i = includeFields.length - 1; i >= 0; i--) {
  377. var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
  378. for (var j = fields.length - 1; j >= 0; j--)
  379. params[fields[j].name] = fields[j].value;
  380. }
  381. }
  382. data = ko.utils.unwrapObservable(data);
  383. var form = document.createElement("form");
  384. form.style.display = "none";
  385. form.action = url;
  386. form.method = "post";
  387. for (var key in data) {
  388. var input = document.createElement("input");
  389. input.name = key;
  390. input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
  391. form.appendChild(input);
  392. }
  393. for (var key in params) {
  394. var input = document.createElement("input");
  395. input.name = key;
  396. input.value = params[key];
  397. form.appendChild(input);
  398. }
  399. document.body.appendChild(form);
  400. options['submitter'] ? options['submitter'](form) : form.submit();
  401. setTimeout(function () { form.parentNode.removeChild(form); }, 0);
  402. }
  403. }
  404. })();
  405. ko.exportSymbol('utils', ko.utils);
  406. ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
  407. ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
  408. ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
  409. ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
  410. ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
  411. ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
  412. ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
  413. ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
  414. ko.exportSymbol('utils.extend', ko.utils.extend);
  415. ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
  416. ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
  417. ko.exportSymbol('utils.postJson', ko.utils.postJson);
  418. ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
  419. ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
  420. ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
  421. ko.exportSymbol('utils.range', ko.utils.range);
  422. ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
  423. ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
  424. ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
  425. if (!Function.prototype['bind']) {
  426. // 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)
  427. // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
  428. Function.prototype['bind'] = function (object) {
  429. var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
  430. return function () {
  431. return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
  432. };
  433. };
  434. }
  435. ko.utils.domData = new (function () {
  436. var uniqueId = 0;
  437. var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
  438. var dataStore = {};
  439. return {
  440. get: function (node, key) {
  441. var allDataForNode = ko.utils.domData.getAll(node, false);
  442. return allDataForNode === undefined ? undefined : allDataForNode[key];
  443. },
  444. set: function (node, key, value) {
  445. if (value === undefined) {
  446. // Make sure we don't actually create a new domData key if we are actually deleting a value
  447. if (ko.utils.domData.getAll(node, false) === undefined)
  448. return;
  449. }
  450. var allDataForNode = ko.utils.domData.getAll(node, true);
  451. allDataForNode[key] = value;
  452. },
  453. getAll: function (node, createIfNotFound) {
  454. var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
  455. var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null");
  456. if (!hasExistingDataStore) {
  457. if (!createIfNotFound)
  458. return undefined;
  459. dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
  460. dataStore[dataStoreKey] = {};
  461. }
  462. return dataStore[dataStoreKey];
  463. },
  464. clear: function (node) {
  465. var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
  466. if (dataStoreKey) {
  467. delete dataStore[dataStoreKey];
  468. node[dataStoreKeyExpandoPropertyName] = null;
  469. }
  470. }
  471. }
  472. })();
  473. ko.exportSymbol('utils.domData', ko.utils.domData);
  474. ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
  475. ko.utils.domNodeDisposal = new (function () {
  476. var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();
  477. var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
  478. var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
  479. function getDisposeCallbacksCollection(node, createIfNotFound) {
  480. var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
  481. if ((allDisposeCallbacks === undefined) && createIfNotFound) {
  482. allDisposeCallbacks = [];
  483. ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
  484. }
  485. return allDisposeCallbacks;
  486. }
  487. function destroyCallbacksCollection(node) {
  488. ko.utils.domData.set(node, domDataKey, undefined);
  489. }
  490. function cleanSingleNode(node) {
  491. // Run all the dispose callbacks
  492. var callbacks = getDisposeCallbacksCollection(node, false);
  493. if (callbacks) {
  494. callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
  495. for (var i = 0; i < callbacks.length; i++)
  496. callbacks[i](node);
  497. }
  498. // Also erase the DOM data
  499. ko.utils.domData.clear(node);
  500. // Special support for jQuery here because it's so commonly used.
  501. // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
  502. // so notify it to tear down any resources associated with the node & descendants here.
  503. if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
  504. jQuery['cleanData']([node]);
  505. // Also clear any immediate-child comment nodes, as these wouldn't have been found by
  506. // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
  507. if (cleanableNodeTypesWithDescendants[node.nodeType])
  508. cleanImmediateCommentTypeChildren(node);
  509. }
  510. function cleanImmediateCommentTypeChildren(nodeWithChildren) {
  511. var child, nextChild = nodeWithChildren.firstChild;
  512. while (child = nextChild) {
  513. nextChild = child.nextSibling;
  514. if (child.nodeType === 8)
  515. cleanSingleNode(child);
  516. }
  517. }
  518. return {
  519. addDisposeCallback : function(node, callback) {
  520. if (typeof callback != "function")
  521. throw new Error("Callback must be a function");
  522. getDisposeCallbacksCollection(node, true).push(callback);
  523. },
  524. removeDisposeCallback : function(node, callback) {
  525. var callbacksCollection = getDisposeCallbacksCollection(node, false);
  526. if (callbacksCollection) {
  527. ko.utils.arrayRemoveItem(callbacksCollection, callback);
  528. if (callbacksCollection.length == 0)
  529. destroyCallbacksCollection(node);
  530. }
  531. },
  532. cleanNode : function(node) {
  533. // First clean this node, where applicable
  534. if (cleanableNodeTypes[node.nodeType]) {
  535. cleanSingleNode(node);
  536. // ... then its descendants, where applicable
  537. if (cleanableNodeTypesWithDescendants[node.nodeType]) {
  538. // Clone the descendants list in case it changes during iteration
  539. var descendants = [];
  540. ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
  541. for (var i = 0, j = descendants.length; i < j; i++)
  542. cleanSingleNode(descendants[i]);
  543. }
  544. }
  545. },
  546. removeNode : function(node) {
  547. ko.cleanNode(node);
  548. if (node.parentNode)
  549. node.parentNode.removeChild(node);
  550. }
  551. }
  552. })();
  553. ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
  554. ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
  555. ko.exportSymbol('cleanNode', ko.cleanNode);
  556. ko.exportSymbol('removeNode', ko.removeNode);
  557. ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
  558. ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
  559. ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
  560. (function () {
  561. var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
  562. function simpleHtmlParse(html) {
  563. // Based on jQuery's "clean" function, but only accounting for table-related elements.
  564. // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
  565. // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
  566. // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
  567. // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
  568. // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
  569. // Trim whitespace, otherwise indexOf won't work as expected
  570. var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
  571. // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
  572. var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
  573. !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
  574. (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
  575. /* anything else */ [0, "", ""];
  576. // Go to html and back, then peel off extra wrappers
  577. // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
  578. var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
  579. if (typeof window['innerShiv'] == "function") {
  580. div.appendChild(window['innerShiv'](markup));
  581. } else {
  582. div.innerHTML = markup;
  583. }
  584. // Move to the right depth
  585. while (wrap[0]--)
  586. div = div.lastChild;
  587. return ko.utils.makeArray(div.lastChild.childNodes);
  588. }
  589. function jQueryHtmlParse(html) {
  590. var elems = jQuery['clean']([html]);
  591. // 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.
  592. // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
  593. // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
  594. if (elems && elems[0]) {
  595. // Find the top-most parent element that's a direct child of a document fragment
  596. var elem = elems[0];
  597. while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
  598. elem = elem.parentNode;
  599. // ... then detach it
  600. if (elem.parentNode)
  601. elem.parentNode.removeChild(elem);
  602. }
  603. return elems;
  604. }
  605. ko.utils.parseHtmlFragment = function(html) {
  606. return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
  607. : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
  608. };
  609. ko.utils.setHtml = function(node, html) {
  610. ko.utils.emptyDomNode(node);
  611. if ((html !== null) && (html !== undefined)) {
  612. if (typeof html != 'string')
  613. html = html.toString();
  614. // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
  615. // for example <tr> elements which are not normally allowed to exist on their own.
  616. // If you've referenced jQuery we'll use that rather than duplicating its code.
  617. if (typeof jQuery != 'undefined') {
  618. jQuery(node)['html'](html);
  619. } else {
  620. // ... otherwise, use KO's own parsing logic.
  621. var parsedNodes = ko.utils.parseHtmlFragment(html);
  622. for (var i = 0; i < parsedNodes.length; i++)
  623. node.appendChild(parsedNodes[i]);
  624. }
  625. }
  626. };
  627. })();
  628. ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
  629. ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
  630. ko.memoization = (function () {
  631. var memos = {};
  632. function randomMax8HexChars() {
  633. return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
  634. }
  635. function generateRandomId() {
  636. return randomMax8HexChars() + randomMax8HexChars();
  637. }
  638. function findMemoNodes(rootNode, appendToArray) {
  639. if (!rootNode)
  640. return;
  641. if (rootNode.nodeType == 8) {
  642. var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
  643. if (memoId != null)
  644. appendToArray.push({ domNode: rootNode, memoId: memoId });
  645. } else if (rootNode.nodeType == 1) {
  646. for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
  647. findMemoNodes(childNodes[i], appendToArray);
  648. }
  649. }
  650. return {
  651. memoize: function (callback) {
  652. if (typeof callback != "function")
  653. throw new Error("You can only pass a function to ko.memoization.memoize()");
  654. var memoId = generateRandomId();
  655. memos[memoId] = callback;
  656. return "<!--[ko_memo:" + memoId + "]-->";
  657. },
  658. unmemoize: function (memoId, callbackParams) {
  659. var callback = memos[memoId];
  660. if (callback === undefined)
  661. throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
  662. try {
  663. callback.apply(null, callbackParams || []);
  664. return true;
  665. }
  666. finally { delete memos[memoId]; }
  667. },
  668. unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
  669. var memos = [];
  670. findMemoNodes(domNode, memos);
  671. for (var i = 0, j = memos.length; i < j; i++) {
  672. var node = memos[i].domNode;
  673. var combinedParams = [node];
  674. if (extraCallbackParamsArray)
  675. ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
  676. ko.memoization.unmemoize(memos[i].memoId, combinedParams);
  677. node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
  678. if (node.parentNode)
  679. 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)
  680. }
  681. },
  682. parseMemoText: function (memoText) {
  683. var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
  684. return match ? match[1] : null;
  685. }
  686. };
  687. })();
  688. ko.exportSymbol('memoization', ko.memoization);
  689. ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
  690. ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
  691. ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
  692. ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
  693. ko.extenders = {
  694. 'throttle': function(target, timeout) {
  695. // Throttling means two things:
  696. // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
  697. // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
  698. target['throttleEvaluation'] = timeout;
  699. // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
  700. // so the target cannot change value synchronously or faster than a certain rate
  701. var writeTimeoutInstance = null;
  702. return ko.dependentObservable({
  703. 'read': target,
  704. 'write': function(value) {
  705. clearTimeout(writeTimeoutInstance);
  706. writeTimeoutInstance = setTimeout(function() {
  707. target(value);
  708. }, timeout);
  709. }
  710. });
  711. },
  712. 'notify': function(target, notifyWhen) {
  713. target["equalityComparer"] = notifyWhen == "always"
  714. ? function() { return false } // Treat all values as not equal
  715. : ko.observable["fn"]["equalityComparer"];
  716. return target;
  717. }
  718. };
  719. function applyExtenders(requestedExtenders) {
  720. var target = this;
  721. if (requestedExtenders) {
  722. for (var key in requestedExtenders) {
  723. var extenderHandler = ko.extenders[key];
  724. if (typeof extenderHandler == 'function') {
  725. target = extenderHandler(target, requestedExtenders[key]);
  726. }
  727. }
  728. }
  729. return target;
  730. }
  731. ko.exportSymbol('extenders', ko.extenders);
  732. ko.subscription = function (target, callback, disposeCallback) {
  733. this.target = target;
  734. this.callback = callback;
  735. this.disposeCallback = disposeCallback;
  736. ko.exportProperty(this, 'dispose', this.dispose);
  737. };
  738. ko.subscription.prototype.dispose = function () {
  739. this.isDisposed = true;
  740. this.disposeCallback();
  741. };
  742. ko.subscribable = function () {
  743. this._subscriptions = {};
  744. ko.utils.extend(this, ko.subscribable['fn']);
  745. ko.exportProperty(this, 'subscribe', this.subscribe);
  746. ko.exportProperty(this, 'extend', this.extend);
  747. ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
  748. }
  749. var defaultEvent = "change";
  750. ko.subscribable['fn'] = {
  751. subscribe: function (callback, callbackTarget, event) {
  752. event = event || defaultEvent;
  753. var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
  754. var subscription = new ko.subscription(this, boundCallback, function () {
  755. ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
  756. }.bind(this));
  757. if (!this._subscriptions[event])
  758. this._subscriptions[event] = [];
  759. this._subscriptions[event].push(subscription);
  760. return subscription;
  761. },
  762. "notifySubscribers": function (valueToNotify, event) {
  763. event = event || defaultEvent;
  764. if (this._subscriptions[event]) {
  765. ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
  766. // In case a subscription was disposed during the arrayForEach cycle, check
  767. // for isDisposed on each subscription before invoking its callback
  768. if (subscription && (subscription.isDisposed !== true))
  769. subscription.callback(valueToNotify);
  770. });
  771. }
  772. },
  773. getSubscriptionsCount: function () {
  774. var total = 0;
  775. for (var eventName in this._subscriptions) {
  776. if (this._subscriptions.hasOwnProperty(eventName))
  777. total += this._subscriptions[eventName].length;
  778. }
  779. return total;
  780. },
  781. extend: applyExtenders
  782. };
  783. ko.isSubscribable = function (instance) {
  784. return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
  785. };
  786. ko.exportSymbol('subscribable', ko.subscribable);
  787. ko.exportSymbol('isSubscribable', ko.isSubscribable);
  788. ko.dependencyDetection = (function () {
  789. var _frames = [];
  790. return {
  791. begin: function (callback) {
  792. _frames.push({ callback: callback, distinctDependencies:[] });
  793. },
  794. end: function () {
  795. _frames.pop();
  796. },
  797. registerDependency: function (subscribable) {
  798. if (!ko.isSubscribable(subscribable))
  799. throw new Error("Only subscribable things can act as dependencies");
  800. if (_frames.length > 0) {
  801. var topFrame = _frames[_frames.length - 1];
  802. if (ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
  803. return;
  804. topFrame.distinctDependencies.push(subscribable);
  805. topFrame.callback(subscribable);
  806. }
  807. }
  808. };
  809. })();
  810. var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };
  811. ko.observable = function (initialValue) {
  812. var _latestValue = initialValue;
  813. function observable() {
  814. if (arguments.length > 0) {
  815. // Write
  816. // Ignore writes if the value hasn't changed
  817. if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
  818. observable.valueWillMutate();
  819. _latestValue = arguments[0];
  820. if (DEBUG) observable._latestValue = _latestValue;
  821. observable.valueHasMutated();
  822. }
  823. return this; // Permits chained assignments
  824. }
  825. else {
  826. // Read
  827. ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
  828. return _latestValue;
  829. }
  830. }
  831. if (DEBUG) observable._latestValue = _latestValue;
  832. ko.subscribable.call(observable);
  833. observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
  834. observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
  835. ko.utils.extend(observable, ko.observable['fn']);
  836. ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
  837. ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
  838. return observable;
  839. }
  840. ko.observable['fn'] = {
  841. "equalityComparer": function valuesArePrimitiveAndEqual(a, b) {
  842. var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
  843. return oldValueIsPrimitive ? (a === b) : false;
  844. }
  845. };
  846. var protoProperty = ko.observable.protoProperty = "__ko_proto__";
  847. ko.observable['fn'][protoProperty] = ko.observable;
  848. ko.hasPrototype = function(instance, prototype) {
  849. if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
  850. if (instance[protoProperty] === prototype) return true;
  851. return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
  852. };
  853. ko.isObservable = function (instance) {
  854. return ko.hasPrototype(instance, ko.observable);
  855. }
  856. ko.isWriteableObservable = function (instance) {
  857. // Observable
  858. if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
  859. return true;
  860. // Writeable dependent observable
  861. if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
  862. return true;
  863. // Anything else
  864. return false;
  865. }
  866. ko.exportSymbol('observable', ko.observable);
  867. ko.exportSymbol('isObservable', ko.isObservable);
  868. ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
  869. ko.observableArray = function (initialValues) {
  870. if (arguments.length == 0) {
  871. // Zero-parameter constructor initializes to empty array
  872. initialValues = [];
  873. }
  874. if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
  875. throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
  876. var result = ko.observable(initialValues);
  877. ko.utils.extend(result, ko.observableArray['fn']);
  878. return result;
  879. }
  880. ko.observableArray['fn'] = {
  881. 'remove': function (valueOrPredicate) {
  882. var underlyingArray = this();
  883. var removedValues = [];
  884. var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
  885. for (var i = 0; i < underlyingArray.length; i++) {
  886. var value = underlyingArray[i];
  887. if (predicate(value)) {
  888. if (removedValues.length === 0) {
  889. this.valueWillMutate();
  890. }
  891. removedValues.push(value);
  892. underlyingArray.splice(i, 1);
  893. i--;
  894. }
  895. }
  896. if (removedValues.length) {
  897. this.valueHasMutated();
  898. }
  899. return removedValues;
  900. },
  901. 'removeAll': function (arrayOfValues) {
  902. // If you passed zero args, we remove everything
  903. if (arrayOfValues === undefined) {
  904. var underlyingArray = this();
  905. var allValues = underlyingArray.slice(0);
  906. this.valueWillMutate();
  907. underlyingArray.splice(0, underlyingArray.length);
  908. this.valueHasMutated();
  909. return allValues;
  910. }
  911. // If you passed an arg, we interpret it as an array of entries to remove
  912. if (!arrayOfValues)
  913. return [];
  914. return this['remove'](function (value) {
  915. return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
  916. });
  917. },
  918. 'destroy': function (valueOrPredicate) {
  919. var underlyingArray = this();
  920. var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
  921. this.valueWillMutate();
  922. for (var i = underlyingArray.length - 1; i >= 0; i--) {
  923. var value = underlyingArray[i];
  924. if (predicate(value))
  925. underlyingArray[i]["_destroy"] = true;
  926. }
  927. this.valueHasMutated();
  928. },
  929. 'destroyAll': function (arrayOfValues) {
  930. // If you passed zero args, we destroy everything
  931. if (arrayOfValues === undefined)
  932. return this['destroy'](function() { return true });
  933. // If you passed an arg, we interpret it as an array of entries to destroy
  934. if (!arrayOfValues)
  935. return [];
  936. return this['destroy'](function (value) {
  937. return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
  938. });
  939. },
  940. 'indexOf': function (item) {
  941. var underlyingArray = this();
  942. return ko.utils.arrayIndexOf(underlyingArray, item);
  943. },
  944. 'replace': function(oldItem, newItem) {
  945. var index = this['indexOf'](oldItem);
  946. if (index >= 0) {
  947. this.valueWillMutate();
  948. this()[index] = newItem;
  949. this.valueHasMutated();
  950. }
  951. }
  952. }
  953. // Populate ko.observableArray.fn with read/write functions from native arrays
  954. ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
  955. ko.observableArray['fn'][methodName] = function () {
  956. var underlyingArray = this();
  957. this.valueWillMutate();
  958. var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
  959. this.valueHasMutated();
  960. return methodCallResult;
  961. };
  962. });
  963. // Populate ko.observableArray.fn with read-only functions from native arrays
  964. ko.utils.arrayForEach(["slice"], function (methodName) {
  965. ko.observableArray['fn'][methodName] = function () {
  966. var underlyingArray = this();
  967. return underlyingArray[methodName].apply(underlyingArray, arguments);
  968. };
  969. });
  970. ko.exportSymbol('observableArray', ko.observableArray);
  971. ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
  972. var _latestValue,
  973. _hasBeenEvaluated = false,
  974. _isBeingEvaluated = false,
  975. readFunction = evaluatorFunctionOrOptions;
  976. if (readFunction && typeof readFunction == "object") {
  977. // Single-parameter syntax - everything is on this "options" param
  978. options = readFunction;
  979. readFunction = options["read"];
  980. } else {
  981. // Multi-parameter syntax - construct the options according to the params passed
  982. options = options || {};
  983. if (!readFunction)
  984. readFunction = options["read"];
  985. }
  986. // By here, "options" is always non-null
  987. if (typeof readFunction != "function")
  988. throw new Error("Pass a function that returns the value of the ko.computed");
  989. var writeFunction = options["write"];
  990. if (!evaluatorFunctionTarget)
  991. evaluatorFunctionTarget = options["owner"];
  992. var _subscriptionsToDependencies = [];
  993. function disposeAllSubscriptionsToDependencies() {
  994. ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
  995. subscription.dispose();
  996. });
  997. _subscriptionsToDependencies = [];
  998. }
  999. var dispose = disposeAllSubscriptionsToDependencies;
  1000. // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values
  1001. // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
  1002. // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
  1003. var disposeWhenNodeIsRemoved = (typeof options["disposeWhenNodeIsRemoved"] == "object") ? options["disposeWhenNodeIsRemoved"] : null;
  1004. var disposeWhen = options["disposeWhen"] || function() { return false; };
  1005. if (disposeWhenNodeIsRemoved) {
  1006. dispose = function() {
  1007. ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
  1008. disposeAllSubscriptionsToDependencies();
  1009. };
  1010. ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
  1011. var existingDisposeWhenFunction = disposeWhen;
  1012. disposeWhen = function () {
  1013. return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
  1014. }
  1015. }
  1016. var evaluationTimeoutInstance = null;
  1017. function evaluatePossiblyAsync() {
  1018. var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
  1019. if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
  1020. clearTimeout(evaluationTimeoutInstance);
  1021. evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
  1022. } else
  1023. evaluateImmediate();
  1024. }
  1025. function evaluateImmediate() {
  1026. if (_isBeingEvaluated) {
  1027. // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
  1028. // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
  1029. // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
  1030. // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
  1031. return;
  1032. }
  1033. // Don't dispose on first evaluation, because the "disposeWhen" callback might
  1034. // e.g., dispose when the associated DOM element isn't in the doc, and it's not
  1035. // going to be in the doc until *after* the first evaluation
  1036. if (_hasBeenEvaluated && disposeWhen()) {
  1037. dispose();
  1038. return;
  1039. }
  1040. _isBeingEvaluated = true;
  1041. try {
  1042. // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
  1043. // Then, during evaluation, we cross off any that are in fact still being used.
  1044. var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
  1045. ko.dependencyDetection.begin(function(subscribable) {
  1046. var inOld;
  1047. if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
  1048. disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
  1049. else
  1050. _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync)); // Brand new subscription - add it
  1051. });
  1052. var newValue = readFunction.call(evaluatorFunctionTarget);
  1053. // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
  1054. for (var i = disposalCandidates.length - 1; i >= 0; i--) {
  1055. if (disposalCandidates[i])
  1056. _subscriptionsToDependencies.splice(i, 1)[0].dispose();
  1057. }
  1058. _hasBeenEvaluated = true;
  1059. dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
  1060. _latestValue = newValue;
  1061. if (DEBUG) dependentObservable._latestValue = _latestValue;
  1062. } finally {
  1063. ko.dependencyDetection.end();
  1064. }
  1065. dependentObservable["notifySubscribers"](_latestValue);
  1066. _isBeingEvaluated = false;
  1067. }
  1068. function dependentObservable() {
  1069. if (arguments.length > 0) {
  1070. set.apply(dependentObservable, arguments);
  1071. } else {
  1072. return get();
  1073. }
  1074. }
  1075. function set() {
  1076. if (typeof writeFunction === "function") {
  1077. // Writing a value
  1078. writeFunction.apply(evaluatorFunctionTarget, arguments);
  1079. } else {
  1080. 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.");
  1081. }
  1082. }
  1083. function get() {
  1084. // Reading the value
  1085. if (!_hasBeenEvaluated)
  1086. evaluateImmediate();
  1087. ko.dependencyDetection.registerDependency(dependentObservable);
  1088. return _latestValue;
  1089. }
  1090. dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
  1091. dependentObservable.hasWriteFunction = typeof options["write"] === "function";
  1092. dependentObservable.dispose = function () { dispose(); };
  1093. ko.subscribable.call(dependentObservable);
  1094. ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
  1095. if (options['deferEvaluation'] !== true)
  1096. evaluateImmediate();
  1097. ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
  1098. ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
  1099. return dependentObservable;
  1100. };
  1101. ko.isComputed = function(instance) {
  1102. return ko.hasPrototype(instance, ko.dependentObservable);
  1103. };
  1104. var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
  1105. ko.dependentObservable[protoProp] = ko.observable;
  1106. ko.dependentObservable['fn'] = {};
  1107. ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
  1108. ko.exportSymbol('dependentObservable', ko.dependentObservable);
  1109. ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
  1110. ko.exportSymbol('isComputed', ko.isComputed);
  1111. (function() {
  1112. var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
  1113. ko.toJS = function(rootObject) {
  1114. if (arguments.length == 0)
  1115. throw new Error("When calling ko.toJS, pass the object you want to convert.");
  1116. // We just unwrap everything at every level in the object graph
  1117. return mapJsObjectGraph(rootObject, function(valueToMap) {
  1118. // Loop because an observable's value might in turn be another observable wrapper
  1119. for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
  1120. valueToMap = valueToMap();
  1121. return valueToMap;
  1122. });
  1123. };
  1124. ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
  1125. var plainJavaScriptObject = ko.toJS(rootObject);
  1126. return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
  1127. };
  1128. function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
  1129. visitedObjects = visitedObjects || new objectLookup();
  1130. rootObject = mapInputCallback(rootObject);
  1131. var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
  1132. if (!canHaveProperties)
  1133. return rootObject;
  1134. var outputProperties = rootObject instanceof Array ? [] : {};
  1135. visitedObjects.save(rootObject, outputProperties);
  1136. visitPropertiesOrArrayEntries(rootObject, function(indexer) {
  1137. var propertyValue = mapInputCallback(rootObject[indexer]);
  1138. switch (typeof propertyValue) {
  1139. case "boolean":
  1140. case "number":
  1141. case "string":
  1142. case "function":
  1143. outputProperties[indexer] = propertyValue;
  1144. break;
  1145. case "object":
  1146. case "undefined":
  1147. var previouslyMappedValue = visitedObjects.get(propertyValue);
  1148. outputProperties[indexer] = (previouslyMappedValue !== undefined)
  1149. ? previouslyMappedValue
  1150. : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
  1151. break;
  1152. }
  1153. });
  1154. return outputProperties;
  1155. }
  1156. function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
  1157. if (rootObject instanceof Array) {
  1158. for (var i = 0; i < rootObject.length; i++)
  1159. visitorCallback(i);
  1160. // For arrays, also respect toJSON property for custom mappings (fixes #278)
  1161. if (typeof rootObject['toJSON'] == 'function')
  1162. visitorCallback('toJSON');
  1163. } else {
  1164. for (var propertyName in rootObject)
  1165. visitorCallback(propertyName);
  1166. }
  1167. };
  1168. function objectLookup() {
  1169. var keys = [];
  1170. var values = [];
  1171. this.save = function(key, value) {
  1172. var existingIndex = ko.utils.arrayIndexOf(keys, key);
  1173. if (existingIndex >= 0)
  1174. values[existingIndex] = value;
  1175. else {
  1176. keys.push(key);
  1177. values.push(value);
  1178. }
  1179. };
  1180. this.get = function(key) {
  1181. var existingIndex = ko.utils.arrayIndexOf(keys, key);
  1182. return (existingIndex >= 0) ? values[existingIndex] : undefined;
  1183. };
  1184. };
  1185. })();
  1186. ko.exportSymbol('toJS', ko.toJS);
  1187. ko.exportSymbol('toJSON', ko.toJSON);
  1188. (function () {
  1189. var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
  1190. // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
  1191. // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
  1192. // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
  1193. ko.selectExtensions = {
  1194. readValue : function(element) {
  1195. switch (ko.utils.tagNameLower(element)) {
  1196. case 'option':
  1197. if (element[hasDomDataExpandoProperty] === true)
  1198. return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
  1199. return element.getAttribute("value");
  1200. case 'select':
  1201. return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
  1202. default:
  1203. return element.value;
  1204. }
  1205. },
  1206. writeValue: function(element, value) {
  1207. switch (ko.utils.tagNameLower(element)) {
  1208. case 'option':
  1209. switch(typeof value) {
  1210. case "string":
  1211. ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
  1212. if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
  1213. delete element[hasDomDataExpandoProperty];
  1214. }
  1215. element.value = value;
  1216. break;
  1217. default:
  1218. // Store arbitrary object using DomData
  1219. ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
  1220. element[hasDomDataExpandoProperty] = true;
  1221. // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
  1222. element.value = typeof value === "number" ? value : "";
  1223. break;
  1224. }
  1225. break;
  1226. case 'select':
  1227. for (var i = element.options.length - 1; i >= 0; i--) {
  1228. if (ko.selectExtensions.readValue(element.options[i]) == value) {
  1229. element.selectedIndex = i;
  1230. break;
  1231. }
  1232. }
  1233. break;
  1234. default:
  1235. if ((value === null) || (value === undefined))
  1236. value = "";
  1237. element.value = value;
  1238. break;
  1239. }
  1240. }
  1241. };
  1242. })();
  1243. ko.exportSymbol('selectExtensions', ko.selectExtensions);
  1244. ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
  1245. ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
  1246. ko.jsonExpressionRewriting = (function () {
  1247. var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
  1248. var javaScriptAssignmentTarget = /^[\_$a-z][\_$a-z0-9]*(\[.*?\])*(\.[\_$a-z][\_$a-z0-9]*(\[.*?\])*)*$/i;
  1249. var javaScriptReservedWords = ["true", "false"];
  1250. function restoreTokens(string, tokens) {
  1251. var prevValue = null;
  1252. while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
  1253. prevValue = string;
  1254. string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
  1255. return tokens[tokenIndex];
  1256. });
  1257. }
  1258. return string;
  1259. }
  1260. function isWriteableValue(expression) {
  1261. if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
  1262. return false;
  1263. return expression.match(javaScriptAssignmentTarget) !== null;
  1264. }
  1265. function ensureQuoted(key) {
  1266. var trimmedKey = ko.utils.stringTrim(key);
  1267. switch (trimmedKey.length && trimmedKey.charAt(0)) {
  1268. case "'":
  1269. case '"':
  1270. return key;
  1271. default:
  1272. return "'" + trimmedKey + "'";
  1273. }
  1274. }
  1275. return {
  1276. bindingRewriteValidators: [],
  1277. parseObjectLiteral: function(objectLiteralString) {
  1278. // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
  1279. // that is sufficient just to split an object literal string into a set of top-level key-value pairs
  1280. var str = ko.utils.stringTrim(objectLiteralString);
  1281. if (str.length < 3)
  1282. return [];
  1283. if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
  1284. str = str.substring(1, str.length - 1);
  1285. // Pull out any string literals and regex literals
  1286. var tokens = [];
  1287. var tokenStart = null, tokenEndChar;
  1288. for (var position = 0; position < str.length; position++) {
  1289. var c = str.charAt(position);
  1290. if (tokenStart === null) {
  1291. switch (c) {
  1292. case '"':
  1293. case "'":
  1294. case "/":
  1295. tokenStart = position;
  1296. tokenEndChar = c;
  1297. break;
  1298. }
  1299. } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
  1300. var token = str.substring(tokenStart, position + 1);
  1301. tokens.push(token);
  1302. var replacement = "@ko_token_" + (tokens.length - 1) + "@";
  1303. str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
  1304. position -= (token.length - replacement.length);
  1305. tokenStart = null;
  1306. }
  1307. }
  1308. // Next pull out balanced paren, brace, and bracket blocks
  1309. tokenStart = null;
  1310. tokenEndChar = null;
  1311. var tokenDepth = 0, tokenStartChar = null;
  1312. for (var position = 0; position < str.length; position++) {
  1313. var c = str.charAt(position);
  1314. if (tokenStart === null) {
  1315. switch (c) {
  1316. case "{": tokenStart = position; tokenStartChar = c;
  1317. tokenEndChar = "}";
  1318. break;
  1319. case "(": tokenStart = position; tokenStartChar = c;
  1320. tokenEndChar = ")";
  1321. break;
  1322. case "[": tokenStart = position; tokenStartChar = c;
  1323. tokenEndChar = "]";
  1324. break;
  1325. }
  1326. }
  1327. if (c === tokenStartChar)
  1328. tokenDepth++;
  1329. else if (c === tokenEndChar) {
  1330. tokenDepth--;
  1331. if (tokenDepth === 0) {
  1332. var token = str.substring(tokenStart, position + 1);
  1333. tokens.push(token);
  1334. var replacement = "@ko_token_" + (tokens.length - 1) + "@";
  1335. str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
  1336. position -= (token.length - replacement.length);
  1337. tokenStart = null;
  1338. }
  1339. }
  1340. }
  1341. // Now we can safely split on commas to get the key/value pairs
  1342. var result = [];
  1343. var keyValuePairs = str.split(",");
  1344. for (var i = 0, j = keyValuePairs.length; i < j; i++) {
  1345. var pair = keyValuePairs[i];
  1346. var colonPos = pair.indexOf(":");
  1347. if ((colonPos > 0) && (colonPos < pair.length - 1)) {
  1348. var key = pair.substring(0, colonPos);
  1349. var value = pair.substring(colonPos + 1);
  1350. result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
  1351. } else {
  1352. result.push({ 'unknown': restoreTokens(pair, tokens) });
  1353. }
  1354. }
  1355. return result;
  1356. },
  1357. insertPropertyAccessorsIntoJson: function (objectLiteralStringOrKeyValueArray) {
  1358. var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
  1359. ? ko.jsonExpressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
  1360. : objectLiteralStringOrKeyValueArray;
  1361. var resultStrings = [], propertyAccessorResultStrings = [];
  1362. var keyValueEntry;
  1363. for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
  1364. if (resultStrings.length > 0)
  1365. resultStrings.push(",");
  1366. if (keyValueEntry['key']) {
  1367. var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
  1368. resultStrings.push(quotedKey);
  1369. resultStrings.push(":");
  1370. resultStrings.push(val);
  1371. if (isWriteableValue(ko.utils.stringTrim(val))) {
  1372. if (propertyAccessorResultStrings.length > 0)
  1373. propertyAccessorResultStrings.push(", ");
  1374. propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
  1375. }
  1376. } else if (keyValueEntry['unknown']) {
  1377. resultStrings.push(keyValueEntry['unknown']);
  1378. }
  1379. }
  1380. var combinedResult = resultStrings.join("");
  1381. if (propertyAccessorResultStrings.length > 0) {
  1382. var allPropertyAccessors = propertyAccessorResultStrings.join("");
  1383. combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
  1384. }
  1385. return combinedResult;
  1386. },
  1387. keyValueArrayContainsKey: function(keyValueArray, key) {
  1388. for (var i = 0; i < keyValueArray.length; i++)
  1389. if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
  1390. return true;
  1391. return false;
  1392. },
  1393. // Internal, private KO utility for updating model properties from within bindings
  1394. // property: If the property being updated is (or might be) an observable, pass it here
  1395. // If it turns out to be a writable observable, it will be written to directly
  1396. // allBindingsAccessor: All bindings in the current execution context.
  1397. // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
  1398. // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
  1399. // value: The value to be written
  1400. // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
  1401. // it is !== existing value on that writable observable
  1402. writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
  1403. if (!property || !ko.isWriteableObservable(property)) {
  1404. var propWriters = allBindingsAccessor()['_ko_property_writers'];
  1405. if (propWriters && propWriters[key])
  1406. propWriters[key](value);
  1407. } else if (!checkIfDifferent || property() !== value) {
  1408. property(value);
  1409. }
  1410. }
  1411. };
  1412. })();
  1413. ko.exportSymbol('jsonExpressionRewriting', ko.jsonExpressionRewriting);
  1414. ko.exportSymbol('jsonExpressionRewriting.bindingRewriteValidators', ko.jsonExpressionRewriting.bindingRewriteValidators);
  1415. ko.exportSymbol('jsonExpressionRewriting.parseObjectLiteral', ko.jsonExpressionRewriting.parseObjectLiteral);
  1416. ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson);
  1417. (function() {
  1418. // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
  1419. // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
  1420. // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
  1421. // of that virtual hierarchy
  1422. //
  1423. // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
  1424. // without having to scatter special cases all over the binding and templating code.
  1425. // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
  1426. // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
  1427. // So, use node.text where available, and node.nodeValue elsewhere
  1428. var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
  1429. var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko\s+(.*\:.*)\s*-->$/ : /^\s*ko\s+(.*\:.*)\s*$/;
  1430. var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
  1431. var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
  1432. function isStartComment(node) {
  1433. return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
  1434. }
  1435. function isEndComment(node) {
  1436. return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
  1437. }
  1438. function getVirtualChildren(startComment, allowUnbalanced) {
  1439. var currentNode = startComment;
  1440. var depth = 1;
  1441. var children = [];
  1442. while (currentNode = currentNode.nextSibling) {
  1443. if (isEndComment(currentNode)) {
  1444. depth--;
  1445. if (depth === 0)
  1446. return children;
  1447. }
  1448. children.push(currentNode);
  1449. if (isStartComment(currentNode))
  1450. depth++;
  1451. }
  1452. if (!allowUnbalanced)
  1453. throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
  1454. return null;
  1455. }
  1456. function getMatchingEndComment(startComment, allowUnbalanced) {
  1457. var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
  1458. if (allVirtualChildren) {
  1459. if (allVirtualChildren.length > 0)
  1460. return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
  1461. return startComment.nextSibling;
  1462. } else
  1463. return null; // Must have no matching end comment, and allowUnbalanced is true
  1464. }
  1465. function getUnbalancedChildTags(node) {
  1466. // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
  1467. // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
  1468. var childNode = node.firstChild, captureRemaining = null;
  1469. if (childNode) {
  1470. do {
  1471. if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
  1472. captureRemaining.push(childNode);
  1473. else if (isStartComment(childNode)) {
  1474. var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
  1475. if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
  1476. childNode = matchingEndComment;
  1477. else
  1478. captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
  1479. } else if (isEndComment(childNode)) {
  1480. captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
  1481. }
  1482. } while (childNode = childNode.nextSibling);
  1483. }
  1484. return captureRemaining;
  1485. }
  1486. ko.virtualElements = {
  1487. allowedBindings: {},
  1488. childNodes: function(node) {
  1489. return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
  1490. },
  1491. emptyNode: function(node) {
  1492. if (!isStartComment(node))
  1493. ko.utils.emptyDomNode(node);
  1494. else {
  1495. var virtualChildren = ko.virtualElements.childNodes(node);
  1496. for (var i = 0, j = virtualChildren.length; i < j; i++)
  1497. ko.removeNode(virtualChildren[i]);
  1498. }
  1499. },
  1500. setDomNodeChildren: function(node, childNodes) {
  1501. if (!isStartComment(node))
  1502. ko.utils.setDomNodeChildren(node, childNodes);
  1503. else {
  1504. ko.virtualElements.emptyNode(node);
  1505. var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
  1506. for (var i = 0, j = childNodes.length; i < j; i++)
  1507. endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
  1508. }
  1509. },
  1510. prepend: function(containerNode, nodeToPrepend) {
  1511. if (!isStartComment(containerNode)) {
  1512. if (containerNode.firstChild)
  1513. containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
  1514. else
  1515. containerNode.appendChild(nodeToPrepend);
  1516. } else {
  1517. // Start comments must always have a parent and at least one following sibling (the end comment)
  1518. containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
  1519. }
  1520. },
  1521. insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
  1522. if (!isStartComment(containerNode)) {
  1523. // Insert after insertion point
  1524. if (insertAfterNode.nextSibling)
  1525. containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
  1526. else
  1527. containerNode.appendChild(nodeToInsert);
  1528. } else {
  1529. // Children of start comments must always have a parent and at least one following sibling (the end comment)
  1530. containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
  1531. }
  1532. },
  1533. firstChild: function(node) {
  1534. if (!isStartComment(node))
  1535. return node.firstChild;
  1536. if (!node.nextSibling || isEndComment(node.nextSibling))
  1537. return null;
  1538. return node.nextSibling;
  1539. },
  1540. nextSibling: function(node) {
  1541. if (isStartComment(node))
  1542. node = getMatchingEndComment(node);
  1543. if (node.nextSibling && isEndComment(node.nextSibling))
  1544. return null;
  1545. return node.nextSibling;
  1546. },
  1547. virtualNodeBindingValue: function(node) {
  1548. var regexMatch = isStartComment(node);
  1549. return regexMatch ? regexMatch[1] : null;
  1550. },
  1551. normaliseVirtualElementDomStructure: function(elementVerified) {
  1552. // Workaround for https://github.com/SteveSanderson/knockout/issues/155
  1553. // (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
  1554. // that are direct descendants of <ul> into the preceding <li>)
  1555. if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
  1556. return;
  1557. // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
  1558. // must be intended to appear *after* that child, so move them there.
  1559. var childNode = elementVerified.firstChild;
  1560. if (childNode) {
  1561. do {
  1562. if (childNode.nodeType === 1) {
  1563. var unbalancedTags = getUnbalancedChildTags(childNode);
  1564. if (unbalancedTags) {
  1565. // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
  1566. var nodeToInsertBefore = childNode.nextSibling;
  1567. for (var i = 0; i < unbalancedTags.length; i++) {
  1568. if (nodeToInsertBefore)
  1569. elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
  1570. else
  1571. elementVerified.appendChild(unbalancedTags[i]);
  1572. }
  1573. }
  1574. }
  1575. } while (childNode = childNode.nextSibling);
  1576. }
  1577. }
  1578. };
  1579. })();
  1580. ko.exportSymbol('virtualElements', ko.virtualElements);
  1581. ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
  1582. ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
  1583. //ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
  1584. ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
  1585. //ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
  1586. ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
  1587. ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
  1588. (function() {
  1589. var defaultBindingAttributeName = "data-bind";
  1590. ko.bindingProvider = function() {
  1591. this.bindingCache = {};
  1592. };
  1593. ko.utils.extend(ko.bindingProvider.prototype, {
  1594. 'nodeHasBindings': function(node) {
  1595. switch (node.nodeType) {
  1596. case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
  1597. case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
  1598. default: return false;
  1599. }
  1600. },
  1601. 'getBindings': function(node, bindingContext) {
  1602. var bindingsString = this['getBindingsString'](node, bindingContext);
  1603. return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext) : null;
  1604. },
  1605. // The following function is only used internally by this default provider.
  1606. // It's not part of the interface definition for a general binding provider.
  1607. 'getBindingsString': function(node, bindingContext) {
  1608. switch (node.nodeType) {
  1609. case 1: return node.getAttribute(defaultBindingAttributeName); // Element
  1610. case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
  1611. default: return null;
  1612. }
  1613. },
  1614. // The following function is only used internally by this default provider.
  1615. // It's not part of the interface definition for a general binding provider.
  1616. 'parseBindingsString': function(bindingsString, bindingContext) {
  1617. try {
  1618. var viewModel = bindingContext['$data'],
  1619. scopes = (typeof viewModel == 'object' && viewModel != null) ? [viewModel, bindingContext] : [bindingContext],
  1620. bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, scopes.length, this.bindingCache);
  1621. return bindingFunction(scopes);
  1622. } catch (ex) {
  1623. throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
  1624. }
  1625. }
  1626. });
  1627. ko.bindingProvider['instance'] = new ko.bindingProvider();
  1628. function createBindingsStringEvaluatorViaCache(bindingsString, scopesCount, cache) {
  1629. var cacheKey = scopesCount + '_' + bindingsString;
  1630. return cache[cacheKey]
  1631. || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, scopesCount));
  1632. }
  1633. function createBindingsStringEvaluator(bindingsString, scopesCount) {
  1634. var rewrittenBindings = " { " + ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson(bindingsString) + " } ";
  1635. return ko.utils.buildEvalWithinScopeFunction(rewrittenBindings, scopesCount);
  1636. }
  1637. })();
  1638. ko.exportSymbol('bindingProvider', ko.bindingProvider);
  1639. (function () {
  1640. ko.bindingHandlers = {};
  1641. ko.bindingContext = function(dataItem, parentBindingContext) {
  1642. if (parentBindingContext) {
  1643. ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
  1644. this['$parentContext'] = parentBindingContext;
  1645. this['$parent'] = parentBindingContext['$data'];
  1646. this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
  1647. this['$parents'].unshift(this['$parent']);
  1648. } else {
  1649. this['$parents'] = [];
  1650. this['$root'] = dataItem;
  1651. }
  1652. this['$data'] = dataItem;
  1653. }
  1654. ko.bindingContext.prototype['createChildContext'] = function (dataItem) {
  1655. return new ko.bindingContext(dataItem, this);
  1656. };
  1657. ko.bindingContext.prototype['extend'] = function(properties) {
  1658. var clone = ko.utils.extend(new ko.bindingContext(), this);
  1659. return ko.utils.extend(clone, properties);
  1660. };
  1661. function validateThatBindingIsAllowedForVirtualElements(bindingName) {
  1662. var validator = ko.virtualElements.allowedBindings[bindingName];
  1663. if (!validator)
  1664. throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
  1665. }
  1666. function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
  1667. var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
  1668. while (currentChild = nextInQueue) {
  1669. // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
  1670. nextInQueue = ko.virtualElements.nextSibling(currentChild);
  1671. applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
  1672. }
  1673. }
  1674. function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
  1675. var shouldBindDescendants = true;
  1676. // Perf optimisation: Apply bindings only if...
  1677. // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
  1678. // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
  1679. // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
  1680. var isElement = (nodeVerified.nodeType === 1);
  1681. if (isElement) // Workaround IE <= 8 HTML parsing weirdness
  1682. ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
  1683. var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
  1684. || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
  1685. if (shouldApplyBindings)
  1686. shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
  1687. if (shouldBindDescendants) {
  1688. // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
  1689. // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
  1690. // hence bindingContextsMayDifferFromDomParentElement is false
  1691. // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
  1692. // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
  1693. // hence bindingContextsMayDifferFromDomParentElement is true
  1694. applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
  1695. }
  1696. }
  1697. function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
  1698. // Need to be sure that inits are only run once, and updates never run until all the inits have been run
  1699. var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
  1700. // Each time the dependentObservable is evaluated (after data changes),
  1701. // the binding attribute is reparsed so that it can pick out the correct
  1702. // model properties in the context of the changed data.
  1703. // DOM event callbacks need to be able to access this changed data,
  1704. // so we need a single parsedBindings variable (shared by all callbacks
  1705. // associated with this node's bindings) that all the closures can access.
  1706. var parsedBindings;
  1707. function makeValueAccessor(bindingKey) {
  1708. return function () { return parsedBindings[bindingKey] }
  1709. }
  1710. function parsedBindingsAccessor() {
  1711. return parsedBindings;
  1712. }
  1713. var bindingHandlerThatControlsDescendantBindings;
  1714. ko.dependentObservable(
  1715. function () {
  1716. // Ensure we have a nonnull binding context to work with
  1717. var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
  1718. ? viewModelOrBindingContext
  1719. : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
  1720. var viewModel = bindingContextInstance['$data'];
  1721. // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
  1722. // we can easily recover it just by scanning up the node's ancestors in the DOM
  1723. // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
  1724. if (bindingContextMayDifferFromDomParentElement)
  1725. ko.storedBindingContextForNode(node, bindingContextInstance);
  1726. // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
  1727. var evaluatedBindings = (typeof bindings == "function") ? bindings() : bindings;
  1728. parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
  1729. if (parsedBindings) {
  1730. // First run all the inits, so bindings can register for notification on changes
  1731. if (initPhase === 0) {
  1732. initPhase = 1;
  1733. for (var bindingKey in parsedBindings) {
  1734. var binding = ko.bindingHandlers[bindingKey];
  1735. if (binding && node.nodeType === 8)
  1736. validateThatBindingIsAllowedForVirtualElements(bindingKey);
  1737. if (binding && typeof binding["init"] == "function") {
  1738. var handlerInitFn = binding["init"];
  1739. var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
  1740. // If this binding handler claims to control descendant bindings, make a note of this
  1741. if (initResult && initResult['controlsDescendantBindings']) {
  1742. if (bindingHandlerThatControlsDescendantBindings !== undefined)
  1743. 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.");
  1744. bindingHandlerThatControlsDescendantBindings = bindingKey;
  1745. }
  1746. }
  1747. }
  1748. initPhase = 2;
  1749. }
  1750. // ... then run all the updates, which might trigger changes even on the first evaluation
  1751. if (initPhase === 2) {
  1752. for (var bindingKey in parsedBindings) {
  1753. var binding = ko.bindingHandlers[bindingKey];
  1754. if (binding && typeof binding["update"] == "function") {
  1755. var handlerUpdateFn = binding["update"];
  1756. handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
  1757. }
  1758. }
  1759. }
  1760. }
  1761. },
  1762. null,
  1763. { 'disposeWhenNodeIsRemoved' : node }
  1764. );
  1765. return {
  1766. shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
  1767. };
  1768. };
  1769. var storedBindingContextDomDataKey = "__ko_bindingContext__";
  1770. ko.storedBindingContextForNode = function (node, bindingContext) {
  1771. if (arguments.length == 2)
  1772. ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
  1773. else
  1774. return ko.utils.domData.get(node, storedBindingContextDomDataKey);
  1775. }
  1776. ko.applyBindingsToNode = function (node, bindings, viewModel) {
  1777. if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
  1778. ko.virtualElements.normaliseVirtualElementDomStructure(node);
  1779. return applyBindingsToNodeInternal(node, bindings, viewModel, true);
  1780. };
  1781. ko.applyBindingsToDescendants = function(viewModel, rootNode) {
  1782. if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
  1783. applyBindingsToDescendantsInternal(viewModel, rootNode, true);
  1784. };
  1785. ko.applyBindings = function (viewModel, rootNode) {
  1786. if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
  1787. throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
  1788. rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
  1789. applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
  1790. };
  1791. // Retrieving binding context from arbitrary nodes
  1792. ko.contextFor = function(node) {
  1793. // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
  1794. switch (node.nodeType) {
  1795. case 1:
  1796. case 8:
  1797. var context = ko.storedBindingContextForNode(node);
  1798. if (context) return context;
  1799. if (node.parentNode) return ko.contextFor(node.parentNode);
  1800. break;
  1801. }
  1802. return undefined;
  1803. };
  1804. ko.dataFor = function(node) {
  1805. var context = ko.contextFor(node);
  1806. return context ? context['$data'] : undefined;
  1807. };
  1808. ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
  1809. ko.exportSymbol('applyBindings', ko.applyBindings);
  1810. ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
  1811. ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
  1812. ko.exportSymbol('contextFor', ko.contextFor);
  1813. ko.exportSymbol('dataFor', ko.dataFor);
  1814. })();
  1815. // For certain common events (currently just 'click'), allow a simplified data-binding syntax
  1816. // e.g. click:handler instead of the usual full-length event:{click:handler}
  1817. var eventHandlersWithShortcuts = ['click'];
  1818. ko.utils.arrayForEach(eventHandlersWithShortcuts, function(eventName) {
  1819. ko.bindingHandlers[eventName] = {
  1820. 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
  1821. var newValueAccessor = function () {
  1822. var result = {};
  1823. result[eventName] = valueAccessor();
  1824. return result;
  1825. };
  1826. return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
  1827. }
  1828. }
  1829. });
  1830. ko.bindingHandlers['event'] = {
  1831. 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
  1832. var eventsToHandle = valueAccessor() || {};
  1833. for(var eventNameOutsideClosure in eventsToHandle) {
  1834. (function() {
  1835. var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
  1836. if (typeof eventName == "string") {
  1837. ko.utils.registerEventHandler(element, eventName, function (event) {
  1838. var handlerReturnValue;
  1839. var handlerFunction = valueAccessor()[eventName];
  1840. if (!handlerFunction)
  1841. return;
  1842. var allBindings = allBindingsAccessor();
  1843. try {
  1844. // Take all the event args, and prefix with the viewmodel
  1845. var argsForHandler = ko.utils.makeArray(arguments);
  1846. argsForHandler.unshift(viewModel);
  1847. handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
  1848. } finally {
  1849. if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
  1850. if (event.preventDefault)
  1851. event.preventDefault();
  1852. else
  1853. event.returnValue = false;
  1854. }
  1855. }
  1856. var bubble = allBindings[eventName + 'Bubble'] !== false;
  1857. if (!bubble) {
  1858. event.cancelBubble = true;
  1859. if (event.stopPropagation)
  1860. event.stopPropagation();
  1861. }
  1862. });
  1863. }
  1864. })();
  1865. }
  1866. }
  1867. };
  1868. ko.bindingHandlers['submit'] = {
  1869. 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
  1870. if (typeof valueAccessor() != "function")
  1871. throw new Error("The value for a submit binding must be a function");
  1872. ko.utils.registerEventHandler(element, "submit", function (event) {
  1873. var handlerReturnValue;
  1874. var value = valueAccessor();
  1875. try { handlerReturnValue = value.call(viewModel, element); }
  1876. finally {
  1877. if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
  1878. if (event.preventDefault)
  1879. event.preventDefault();
  1880. else
  1881. event.returnValue = false;
  1882. }
  1883. }
  1884. });
  1885. }
  1886. };
  1887. ko.bindingHandlers['visible'] = {
  1888. 'update': function (element, valueAccessor) {
  1889. var value = ko.utils.unwrapObservable(valueAccessor());
  1890. var isCurrentlyVisible = !(element.style.display == "none");
  1891. if (value && !isCurrentlyVisible)
  1892. element.style.display = "";
  1893. else if ((!value) && isCurrentlyVisible)
  1894. element.style.display = "none";
  1895. }
  1896. }
  1897. ko.bindingHandlers['enable'] = {
  1898. 'update': function (element, valueAccessor) {
  1899. var value = ko.utils.unwrapObservable(valueAccessor());
  1900. if (value && element.disabled)
  1901. element.removeAttribute("disabled");
  1902. else if ((!value) && (!element.disabled))
  1903. element.disabled = true;
  1904. }
  1905. };
  1906. ko.bindingHandlers['disable'] = {
  1907. 'update': function (element, valueAccessor) {
  1908. ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
  1909. }
  1910. };
  1911. function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
  1912. if (preferModelValue) {
  1913. if (modelValue !== ko.selectExtensions.readValue(element))
  1914. ko.selectExtensions.writeValue(element, modelValue);
  1915. }
  1916. // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
  1917. // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
  1918. // change the model value to match the dropdown.
  1919. if (modelValue !== ko.selectExtensions.readValue(element))
  1920. ko.utils.triggerEvent(element, "change");
  1921. };
  1922. ko.bindingHandlers['value'] = {
  1923. 'init': function (element, valueAccessor, allBindingsAccessor) {
  1924. // Always catch "change" event; possibly other events too if asked
  1925. var eventsToCatch = ["change"];
  1926. var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
  1927. if (requestedEventsToCatch) {
  1928. if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
  1929. requestedEventsToCatch = [requestedEventsToCatch];
  1930. ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
  1931. eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
  1932. }
  1933. var valueUpdateHandler = function() {
  1934. var modelValue = valueAccessor();
  1935. var elementValue = ko.selectExtensions.readValue(element);
  1936. ko.jsonExpressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue, /* checkIfDifferent: */ true);
  1937. }
  1938. // Workaround for https://github.com/SteveSanderson/knockout/issues/122
  1939. // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
  1940. var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
  1941. && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
  1942. if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
  1943. var propertyChangedFired = false;
  1944. ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
  1945. ko.utils.registerEventHandler(element, "blur", function() {
  1946. if (propertyChangedFired) {
  1947. propertyChangedFired = false;
  1948. valueUpdateHandler();
  1949. }
  1950. });
  1951. }
  1952. ko.utils.arrayForEach(eventsToCatch, function(eventName) {
  1953. // The syntax "after<eventname>" means "run the handler asynchronously after the event"
  1954. // This is useful, for example, to catch "keydown" events after the browser has updated the control
  1955. // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
  1956. var handler = valueUpdateHandler;
  1957. if (ko.utils.stringStartsWith(eventName, "after")) {
  1958. handler = function() { setTimeout(valueUpdateHandler, 0) };
  1959. eventName = eventName.substring("after".length);
  1960. }
  1961. ko.utils.registerEventHandler(element, eventName, handler);
  1962. });
  1963. },
  1964. 'update': function (element, valueAccessor) {
  1965. var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
  1966. var newValue = ko.utils.unwrapObservable(valueAccessor());
  1967. var elementValue = ko.selectExtensions.readValue(element);
  1968. var valueHasChanged = (newValue != elementValue);
  1969. // JavaScript's 0 == "" behavious is unfortunate here as it prevents writing 0 to an empty text box (loose equality suggests the values are the same).
  1970. // We don't want to do a strict equality comparison as that is more confusing for developers in certain cases, so we specifically special case 0 != "" here.
  1971. if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
  1972. valueHasChanged = true;
  1973. if (valueHasChanged) {
  1974. var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
  1975. applyValueAction();
  1976. // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
  1977. // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
  1978. // to apply the value as well.
  1979. var alsoApplyAsynchronously = valueIsSelectOption;
  1980. if (alsoApplyAsynchronously)
  1981. setTimeout(applyValueAction, 0);
  1982. }
  1983. // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
  1984. // because you're not allowed to have a model value that disagrees with a visible UI selection.
  1985. if (valueIsSelectOption && (element.length > 0))
  1986. ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
  1987. }
  1988. };
  1989. ko.bindingHandlers['options'] = {
  1990. 'update': function (element, valueAccessor, allBindingsAccessor) {
  1991. if (ko.utils.tagNameLower(element) !== "select")
  1992. throw new Error("options binding applies only to SELECT elements");
  1993. var selectWasPreviouslyEmpty = element.length == 0;
  1994. var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
  1995. return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
  1996. }), function (node) {
  1997. return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
  1998. });
  1999. var previousScrollTop = element.scrollTop;
  2000. var value = ko.utils.unwrapObservable(valueAccessor());
  2001. var selectedValue = element.value;
  2002. // Remove all existing <option>s.
  2003. // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
  2004. while (element.length > 0) {
  2005. ko.cleanNode(element.options[0]);
  2006. element.remove(0);
  2007. }
  2008. if (value) {
  2009. var allBindings = allBindingsAccessor();
  2010. if (typeof value.length != "number")
  2011. value = [value];
  2012. if (allBindings['optionsCaption']) {
  2013. var option = document.createElement("option");
  2014. ko.utils.setHtml(option, allBindings['optionsCaption']);
  2015. ko.selectExtensions.writeValue(option, undefined);
  2016. element.appendChild(option);
  2017. }
  2018. for (var i = 0, j = value.length; i < j; i++) {
  2019. var option = document.createElement("option");
  2020. // Apply a value to the option element
  2021. var optionValue = typeof allBindings['optionsValue'] == "string" ? value[i][allBindings['optionsValue']] : value[i];
  2022. optionValue = ko.utils.unwrapObservable(optionValue);
  2023. ko.selectExtensions.writeValue(option, optionValue);
  2024. // Apply some text to the option element
  2025. var optionsTextValue = allBindings['optionsText'];
  2026. var optionText;
  2027. if (typeof optionsTextValue == "function")
  2028. optionText = optionsTextValue(value[i]); // Given a function; run it against the data value
  2029. else if (typeof optionsTextValue == "string")
  2030. optionText = value[i][optionsTextValue]; // Given a string; treat it as a property name on the data value
  2031. else
  2032. optionText = optionValue; // Given no optionsText arg; use the data value itself
  2033. if ((optionText === null) || (optionText === undefined))
  2034. optionText = "";
  2035. ko.utils.setTextContent(option, optionText);
  2036. element.appendChild(option);
  2037. }
  2038. // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
  2039. // That's why we first added them without selection. Now it's time to set the selection.
  2040. var newOptions = element.getElementsByTagName("option");
  2041. var countSelectionsRetained = 0;
  2042. for (var i = 0, j = newOptions.length; i < j; i++) {
  2043. if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
  2044. ko.utils.setOptionNodeSelectionState(newOptions[i], true);
  2045. countSelectionsRetained++;
  2046. }
  2047. }
  2048. element.scrollTop = previousScrollTop;
  2049. if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
  2050. // Ensure consistency between model value and selected option.
  2051. // If the dropdown is being populated for the first time here (or was otherwise previously empty),
  2052. // the dropdown selection state is meaningless, so we preserve the model value.
  2053. ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.unwrapObservable(allBindings['value']), /* preferModelValue */ true);
  2054. }
  2055. // Workaround for IE9 bug
  2056. ko.utils.ensureSelectElementIsRenderedCorrectly(element);
  2057. }
  2058. }
  2059. };
  2060. ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
  2061. ko.bindingHandlers['selectedOptions'] = {
  2062. getSelectedValuesFromSelectNode: function (selectNode) {
  2063. var result = [];
  2064. var nodes = selectNode.childNodes;
  2065. for (var i = 0, j = nodes.length; i < j; i++) {
  2066. var node = nodes[i], tagName = ko.utils.tagNameLower(node);
  2067. if (tagName == "option" && node.selected)
  2068. result.push(ko.selectExtensions.readValue(node));
  2069. else if (tagName == "optgroup") {
  2070. var selectedValuesFromOptGroup = ko.bindingHandlers['selectedOptions'].getSelectedValuesFromSelectNode(node);
  2071. Array.prototype.splice.apply(result, [result.length, 0].concat(selectedValuesFromOptGroup)); // Add new entries to existing 'result' instance
  2072. }
  2073. }
  2074. return result;
  2075. },
  2076. 'init': function (element, valueAccessor, allBindingsAccessor) {
  2077. ko.utils.registerEventHandler(element, "change", function () {
  2078. var value = valueAccessor();
  2079. var valueToWrite = ko.bindingHandlers['selectedOptions'].getSelectedValuesFromSelectNode(this);
  2080. ko.jsonExpressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
  2081. });
  2082. },
  2083. 'update': function (element, valueAccessor) {
  2084. if (ko.utils.tagNameLower(element) != "select")
  2085. throw new Error("values binding applies only to SELECT elements");
  2086. var newValue = ko.utils.unwrapObservable(valueAccessor());
  2087. if (newValue && typeof newValue.length == "number") {
  2088. var nodes = element.childNodes;
  2089. for (var i = 0, j = nodes.length; i < j; i++) {
  2090. var node = nodes[i];
  2091. if (ko.utils.tagNameLower(node) === "option")
  2092. ko.utils.setOptionNodeSelectionState(node, ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0);
  2093. }
  2094. }
  2095. }
  2096. };
  2097. ko.bindingHandlers['text'] = {
  2098. 'update': function (element, valueAccessor) {
  2099. ko.utils.setTextContent(element, valueAccessor());
  2100. }
  2101. };
  2102. ko.bindingHandlers['html'] = {
  2103. 'init': function() {
  2104. // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
  2105. return { 'controlsDescendantBindings': true };
  2106. },
  2107. 'update': function (element, valueAccessor) {
  2108. var value = ko.utils.unwrapObservable(valueAccessor());
  2109. ko.utils.setHtml(element, value);
  2110. }
  2111. };
  2112. ko.bindingHandlers['css'] = {
  2113. 'update': function (element, valueAccessor) {
  2114. var value = ko.utils.unwrapObservable(valueAccessor() || {});
  2115. for (var className in value) {
  2116. if (typeof className == "string") {
  2117. var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
  2118. ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
  2119. }
  2120. }
  2121. }
  2122. };
  2123. ko.bindingHandlers['style'] = {
  2124. 'update': function (element, valueAccessor) {
  2125. var value = ko.utils.unwrapObservable(valueAccessor() || {});
  2126. for (var styleName in value) {
  2127. if (typeof styleName == "string") {
  2128. var styleValue = ko.utils.unwrapObservable(value[styleName]);
  2129. element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
  2130. }
  2131. }
  2132. }
  2133. };
  2134. ko.bindingHandlers['uniqueName'] = {
  2135. 'init': function (element, valueAccessor) {
  2136. if (valueAccessor()) {
  2137. element.name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
  2138. // Workaround IE 6/7 issue
  2139. // - https://github.com/SteveSanderson/knockout/issues/197
  2140. // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
  2141. if (ko.utils.isIe6 || ko.utils.isIe7)
  2142. element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
  2143. }
  2144. }
  2145. };
  2146. ko.bindingHandlers['uniqueName'].currentIndex = 0;
  2147. ko.bindingHandlers['checked'] = {
  2148. 'init': function (element, valueAccessor, allBindingsAccessor) {
  2149. var updateHandler = function() {
  2150. var valueToWrite;
  2151. if (element.type == "checkbox") {
  2152. valueToWrite = element.checked;
  2153. } else if ((element.type == "radio") && (element.checked)) {
  2154. valueToWrite = element.value;
  2155. } else {
  2156. return; // "checked" binding only responds to checkboxes and selected radio buttons
  2157. }
  2158. var modelValue = valueAccessor();
  2159. if ((element.type == "checkbox") && (ko.utils.unwrapObservable(modelValue) instanceof Array)) {
  2160. // For checkboxes bound to an array, we add/remove the checkbox value to that array
  2161. // This works for both observable and non-observable arrays
  2162. var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.unwrapObservable(modelValue), element.value);
  2163. if (element.checked && (existingEntryIndex < 0))
  2164. modelValue.push(element.value);
  2165. else if ((!element.checked) && (existingEntryIndex >= 0))
  2166. modelValue.splice(existingEntryIndex, 1);
  2167. } else {
  2168. ko.jsonExpressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
  2169. }
  2170. };
  2171. ko.utils.registerEventHandler(element, "click", updateHandler);
  2172. // IE 6 won't allow radio buttons to be selected unless they have a name
  2173. if ((element.type == "radio") && !element.name)
  2174. ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
  2175. },
  2176. 'update': function (element, valueAccessor) {
  2177. var value = ko.utils.unwrapObservable(valueAccessor());
  2178. if (element.type == "checkbox") {
  2179. if (value instanceof Array) {
  2180. // When bound to an array, the checkbox being checked represents its value being present in that array
  2181. element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
  2182. } else {
  2183. // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
  2184. element.checked = value;
  2185. }
  2186. } else if (element.type == "radio") {
  2187. element.checked = (element.value == value);
  2188. }
  2189. }
  2190. };
  2191. var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
  2192. ko.bindingHandlers['attr'] = {
  2193. 'update': function(element, valueAccessor, allBindingsAccessor) {
  2194. var value = ko.utils.unwrapObservable(valueAccessor()) || {};
  2195. for (var attrName in value) {
  2196. if (typeof attrName == "string") {
  2197. var attrValue = ko.utils.unwrapObservable(value[attrName]);
  2198. // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
  2199. // when someProp is a "no value"-like value (strictly null, false, or undefined)
  2200. // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
  2201. var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
  2202. if (toRemove)
  2203. element.removeAttribute(attrName);
  2204. // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
  2205. // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
  2206. // but instead of figuring out the mode, we'll just set the attribute through the Javascript
  2207. // property for IE <= 8.
  2208. if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
  2209. attrName = attrHtmlToJavascriptMap[attrName];
  2210. if (toRemove)
  2211. element.removeAttribute(attrName);
  2212. else
  2213. element[attrName] = attrValue;
  2214. } else if (!toRemove) {
  2215. element.setAttribute(attrName, attrValue.toString());
  2216. }
  2217. }
  2218. }
  2219. }
  2220. };
  2221. ko.bindingHandlers['hasfocus'] = {
  2222. 'init': function(element, valueAccessor, allBindingsAccessor) {
  2223. var writeValue = function(valueToWrite) {
  2224. var modelValue = valueAccessor();
  2225. ko.jsonExpressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', valueToWrite, true);
  2226. };
  2227. ko.utils.registerEventHandler(element, "focus", function() { writeValue(true) });
  2228. ko.utils.registerEventHandler(element, "focusin", function() { writeValue(true) }); // For IE
  2229. ko.utils.registerEventHandler(element, "blur", function() { writeValue(false) });
  2230. ko.utils.registerEventHandler(element, "focusout", function() { writeValue(false) }); // For IE
  2231. },
  2232. 'update': function(element, valueAccessor) {
  2233. var value = ko.utils.unwrapObservable(valueAccessor());
  2234. value ? element.focus() : element.blur();
  2235. ko.utils.triggerEvent(element, value ? "focusin" : "focusout"); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
  2236. }
  2237. };
  2238. // "with: someExpression" is equivalent to "template: { if: someExpression, data: someExpression }"
  2239. ko.bindingHandlers['with'] = {
  2240. makeTemplateValueAccessor: function(valueAccessor) {
  2241. return function() { var value = valueAccessor(); return { 'if': value, 'data': value, 'templateEngine': ko.nativeTemplateEngine.instance } };
  2242. },
  2243. 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2244. return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['with'].makeTemplateValueAccessor(valueAccessor));
  2245. },
  2246. 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2247. return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['with'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
  2248. }
  2249. };
  2250. ko.jsonExpressionRewriting.bindingRewriteValidators['with'] = false; // Can't rewrite control flow bindings
  2251. ko.virtualElements.allowedBindings['with'] = true;
  2252. // "if: someExpression" is equivalent to "template: { if: someExpression }"
  2253. ko.bindingHandlers['if'] = {
  2254. makeTemplateValueAccessor: function(valueAccessor) {
  2255. return function() { return { 'if': valueAccessor(), 'templateEngine': ko.nativeTemplateEngine.instance } };
  2256. },
  2257. 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2258. return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['if'].makeTemplateValueAccessor(valueAccessor));
  2259. },
  2260. 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2261. return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['if'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
  2262. }
  2263. };
  2264. ko.jsonExpressionRewriting.bindingRewriteValidators['if'] = false; // Can't rewrite control flow bindings
  2265. ko.virtualElements.allowedBindings['if'] = true;
  2266. // "ifnot: someExpression" is equivalent to "template: { ifnot: someExpression }"
  2267. ko.bindingHandlers['ifnot'] = {
  2268. makeTemplateValueAccessor: function(valueAccessor) {
  2269. return function() { return { 'ifnot': valueAccessor(), 'templateEngine': ko.nativeTemplateEngine.instance } };
  2270. },
  2271. 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2272. return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['ifnot'].makeTemplateValueAccessor(valueAccessor));
  2273. },
  2274. 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2275. return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['ifnot'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
  2276. }
  2277. };
  2278. ko.jsonExpressionRewriting.bindingRewriteValidators['ifnot'] = false; // Can't rewrite control flow bindings
  2279. ko.virtualElements.allowedBindings['ifnot'] = true;
  2280. // "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
  2281. // "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
  2282. ko.bindingHandlers['foreach'] = {
  2283. makeTemplateValueAccessor: function(valueAccessor) {
  2284. return function() {
  2285. var bindingValue = ko.utils.unwrapObservable(valueAccessor());
  2286. // If bindingValue is the array, just pass it on its own
  2287. if ((!bindingValue) || typeof bindingValue.length == "number")
  2288. return { 'foreach': bindingValue, 'templateEngine': ko.nativeTemplateEngine.instance };
  2289. // If bindingValue.data is the array, preserve all relevant options
  2290. return {
  2291. 'foreach': bindingValue['data'],
  2292. 'includeDestroyed': bindingValue['includeDestroyed'],
  2293. 'afterAdd': bindingValue['afterAdd'],
  2294. 'beforeRemove': bindingValue['beforeRemove'],
  2295. 'afterRender': bindingValue['afterRender'],
  2296. 'templateEngine': ko.nativeTemplateEngine.instance
  2297. };
  2298. };
  2299. },
  2300. 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2301. return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
  2302. },
  2303. 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2304. return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
  2305. }
  2306. };
  2307. ko.jsonExpressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
  2308. ko.virtualElements.allowedBindings['foreach'] = true;
  2309. // If you want to make a custom template engine,
  2310. //
  2311. // [1] Inherit from this class (like ko.nativeTemplateEngine does)
  2312. // [2] Override 'renderTemplateSource', supplying a function with this signature:
  2313. //
  2314. // function (templateSource, bindingContext, options) {
  2315. // // - templateSource.text() is the text of the template you should render
  2316. // // - bindingContext.$data is the data you should pass into the template
  2317. // // - you might also want to make bindingContext.$parent, bindingContext.$parents,
  2318. // // and bindingContext.$root available in the template too
  2319. // // - options gives you access to any other properties set on "data-bind: { template: options }"
  2320. // //
  2321. // // Return value: an array of DOM nodes
  2322. // }
  2323. //
  2324. // [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
  2325. //
  2326. // function (script) {
  2327. // // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
  2328. // // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
  2329. // }
  2330. //
  2331. // This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
  2332. // If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
  2333. // and then you don't need to override 'createJavaScriptEvaluatorBlock'.
  2334. ko.templateEngine = function () { };
  2335. ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
  2336. throw new Error("Override renderTemplateSource");
  2337. };
  2338. ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
  2339. throw new Error("Override createJavaScriptEvaluatorBlock");
  2340. };
  2341. ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
  2342. // Named template
  2343. if (typeof template == "string") {
  2344. templateDocument = templateDocument || document;
  2345. var elem = templateDocument.getElementById(template);
  2346. if (!elem)
  2347. throw new Error("Cannot find template with ID " + template);
  2348. return new ko.templateSources.domElement(elem);
  2349. } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
  2350. // Anonymous template
  2351. return new ko.templateSources.anonymousTemplate(template);
  2352. } else
  2353. throw new Error("Unknown template type: " + template);
  2354. };
  2355. ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
  2356. var templateSource = this['makeTemplateSource'](template, templateDocument);
  2357. return this['renderTemplateSource'](templateSource, bindingContext, options);
  2358. };
  2359. ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
  2360. // Skip rewriting if requested
  2361. if (this['allowTemplateRewriting'] === false)
  2362. return true;
  2363. // Perf optimisation - see below
  2364. var templateIsInExternalDocument = templateDocument && templateDocument != document;
  2365. if (!templateIsInExternalDocument && this.knownRewrittenTemplates && this.knownRewrittenTemplates[template])
  2366. return true;
  2367. return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
  2368. };
  2369. ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
  2370. var templateSource = this['makeTemplateSource'](template, templateDocument);
  2371. var rewritten = rewriterCallback(templateSource['text']());
  2372. templateSource['text'](rewritten);
  2373. templateSource['data']("isRewritten", true);
  2374. // Perf optimisation - for named templates, track which ones have been rewritten so we can
  2375. // answer 'isTemplateRewritten' *without* having to use getElementById (which is slow on IE < 8)
  2376. //
  2377. // Note that we only cache the status for templates in the main document, because caching on a per-doc
  2378. // basis complicates the implementation excessively. In a future version of KO, we will likely remove
  2379. // this 'isRewritten' cache entirely anyway, because the benefit is extremely minor and only applies
  2380. // to rewritable templates, which are pretty much deprecated since KO 2.0.
  2381. var templateIsInExternalDocument = templateDocument && templateDocument != document;
  2382. if (!templateIsInExternalDocument && typeof template == "string") {
  2383. this.knownRewrittenTemplates = this.knownRewrittenTemplates || {};
  2384. this.knownRewrittenTemplates[template] = true;
  2385. }
  2386. };
  2387. ko.exportSymbol('templateEngine', ko.templateEngine);
  2388. ko.templateRewriting = (function () {
  2389. var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
  2390. var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
  2391. function validateDataBindValuesForRewriting(keyValueArray) {
  2392. var allValidators = ko.jsonExpressionRewriting.bindingRewriteValidators;
  2393. for (var i = 0; i < keyValueArray.length; i++) {
  2394. var key = keyValueArray[i]['key'];
  2395. if (allValidators.hasOwnProperty(key)) {
  2396. var validator = allValidators[key];
  2397. if (typeof validator === "function") {
  2398. var possibleErrorMessage = validator(keyValueArray[i]['value']);
  2399. if (possibleErrorMessage)
  2400. throw new Error(possibleErrorMessage);
  2401. } else if (!validator) {
  2402. throw new Error("This template engine does not support the '" + key + "' binding within its templates");
  2403. }
  2404. }
  2405. }
  2406. }
  2407. function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
  2408. var dataBindKeyValueArray = ko.jsonExpressionRewriting.parseObjectLiteral(dataBindAttributeValue);
  2409. validateDataBindValuesForRewriting(dataBindKeyValueArray);
  2410. var rewrittenDataBindAttributeValue = ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson(dataBindKeyValueArray);
  2411. // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
  2412. // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
  2413. // extra indirection.
  2414. var applyBindingsToNextSiblingScript = "ko.templateRewriting.applyMemoizedBindingsToNextSibling(function() { \
  2415. return (function() { return { " + rewrittenDataBindAttributeValue + " } })() \
  2416. })";
  2417. return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
  2418. }
  2419. return {
  2420. ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
  2421. if (!templateEngine['isTemplateRewritten'](template, templateDocument))
  2422. templateEngine['rewriteTemplate'](template, function (htmlString) {
  2423. return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
  2424. }, templateDocument);
  2425. },
  2426. memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
  2427. return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
  2428. return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
  2429. }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
  2430. return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
  2431. });
  2432. },
  2433. applyMemoizedBindingsToNextSibling: function (bindings) {
  2434. return ko.memoization.memoize(function (domNode, bindingContext) {
  2435. if (domNode.nextSibling)
  2436. ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
  2437. });
  2438. }
  2439. }
  2440. })();
  2441. ko.exportSymbol('templateRewriting', ko.templateRewriting);
  2442. ko.exportSymbol('templateRewriting.applyMemoizedBindingsToNextSibling', ko.templateRewriting.applyMemoizedBindingsToNextSibling); // Exported only because it has to be referenced by string lookup from within rewritten template
  2443. (function() {
  2444. // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
  2445. // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
  2446. //
  2447. // Two are provided by default:
  2448. // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
  2449. // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
  2450. // without reading/writing the actual element text content, since it will be overwritten
  2451. // with the rendered template output.
  2452. // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
  2453. // Template sources need to have the following functions:
  2454. // text() - returns the template text from your storage location
  2455. // text(value) - writes the supplied template text to your storage location
  2456. // data(key) - reads values stored using data(key, value) - see below
  2457. // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
  2458. //
  2459. // Optionally, template sources can also have the following functions:
  2460. // nodes() - returns a DOM element containing the nodes of this template, where available
  2461. // nodes(value) - writes the given DOM element to your storage location
  2462. // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
  2463. // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
  2464. //
  2465. // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
  2466. // using and overriding "makeTemplateSource" to return an instance of your custom template source.
  2467. ko.templateSources = {};
  2468. // ---- ko.templateSources.domElement -----
  2469. ko.templateSources.domElement = function(element) {
  2470. this.domElement = element;
  2471. }
  2472. ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
  2473. var tagNameLower = ko.utils.tagNameLower(this.domElement),
  2474. elemContentsProperty = tagNameLower === "script" ? "text"
  2475. : tagNameLower === "textarea" ? "value"
  2476. : "innerHTML";
  2477. if (arguments.length == 0) {
  2478. return this.domElement[elemContentsProperty];
  2479. } else {
  2480. var valueToWrite = arguments[0];
  2481. if (elemContentsProperty === "innerHTML")
  2482. ko.utils.setHtml(this.domElement, valueToWrite);
  2483. else
  2484. this.domElement[elemContentsProperty] = valueToWrite;
  2485. }
  2486. };
  2487. ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
  2488. if (arguments.length === 1) {
  2489. return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
  2490. } else {
  2491. ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
  2492. }
  2493. };
  2494. // ---- ko.templateSources.anonymousTemplate -----
  2495. // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
  2496. // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
  2497. // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
  2498. var anonymousTemplatesDomDataKey = "__ko_anon_template__";
  2499. ko.templateSources.anonymousTemplate = function(element) {
  2500. this.domElement = element;
  2501. }
  2502. ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
  2503. ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
  2504. if (arguments.length == 0) {
  2505. var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
  2506. if (templateData.textData === undefined && templateData.containerData)
  2507. templateData.textData = templateData.containerData.innerHTML;
  2508. return templateData.textData;
  2509. } else {
  2510. var valueToWrite = arguments[0];
  2511. ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
  2512. }
  2513. };
  2514. ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
  2515. if (arguments.length == 0) {
  2516. var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
  2517. return templateData.containerData;
  2518. } else {
  2519. var valueToWrite = arguments[0];
  2520. ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
  2521. }
  2522. };
  2523. ko.exportSymbol('templateSources', ko.templateSources);
  2524. ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
  2525. ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
  2526. })();
  2527. (function () {
  2528. var _templateEngine;
  2529. ko.setTemplateEngine = function (templateEngine) {
  2530. if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
  2531. throw new Error("templateEngine must inherit from ko.templateEngine");
  2532. _templateEngine = templateEngine;
  2533. }
  2534. function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
  2535. var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
  2536. while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
  2537. nextInQueue = ko.virtualElements.nextSibling(node);
  2538. if (node.nodeType === 1 || node.nodeType === 8)
  2539. action(node);
  2540. }
  2541. }
  2542. function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
  2543. // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
  2544. // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
  2545. // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
  2546. // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
  2547. // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
  2548. if (continuousNodeArray.length) {
  2549. var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
  2550. // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
  2551. // whereas a regular applyBindings won't introduce new memoized nodes
  2552. invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
  2553. ko.applyBindings(bindingContext, node);
  2554. });
  2555. invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
  2556. ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
  2557. });
  2558. }
  2559. }
  2560. function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
  2561. return nodeOrNodeArray.nodeType ? nodeOrNodeArray
  2562. : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
  2563. : null;
  2564. }
  2565. function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
  2566. options = options || {};
  2567. var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  2568. var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
  2569. var templateEngineToUse = (options['templateEngine'] || _templateEngine);
  2570. ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
  2571. var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
  2572. // Loosely check result is an array of DOM nodes
  2573. if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
  2574. throw new Error("Template engine must return an array of DOM nodes");
  2575. var haveAddedNodesToParent = false;
  2576. switch (renderMode) {
  2577. case "replaceChildren":
  2578. ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
  2579. haveAddedNodesToParent = true;
  2580. break;
  2581. case "replaceNode":
  2582. ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
  2583. haveAddedNodesToParent = true;
  2584. break;
  2585. case "ignoreTargetNode": break;
  2586. default:
  2587. throw new Error("Unknown renderMode: " + renderMode);
  2588. }
  2589. if (haveAddedNodesToParent) {
  2590. activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
  2591. if (options['afterRender'])
  2592. options['afterRender'](renderedNodesArray, bindingContext['$data']);
  2593. }
  2594. return renderedNodesArray;
  2595. }
  2596. ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
  2597. options = options || {};
  2598. if ((options['templateEngine'] || _templateEngine) == undefined)
  2599. throw new Error("Set a template engine before calling renderTemplate");
  2600. renderMode = renderMode || "replaceChildren";
  2601. if (targetNodeOrNodeArray) {
  2602. var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  2603. var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
  2604. var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
  2605. return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
  2606. function () {
  2607. // Ensure we've got a proper binding context to work with
  2608. var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
  2609. ? dataOrBindingContext
  2610. : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
  2611. // Support selecting template as a function of the data being rendered
  2612. var templateName = typeof(template) == 'function' ? template(bindingContext['$data']) : template;
  2613. var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
  2614. if (renderMode == "replaceNode") {
  2615. targetNodeOrNodeArray = renderedNodesArray;
  2616. firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  2617. }
  2618. },
  2619. null,
  2620. { 'disposeWhen': whenToDispose, 'disposeWhenNodeIsRemoved': activelyDisposeWhenNodeIsRemoved }
  2621. );
  2622. } else {
  2623. // 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
  2624. return ko.memoization.memoize(function (domNode) {
  2625. ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
  2626. });
  2627. }
  2628. };
  2629. ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
  2630. // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
  2631. // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
  2632. var arrayItemContext;
  2633. // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
  2634. var executeTemplateForArrayItem = function (arrayValue, index) {
  2635. // Support selecting template as a function of the data being rendered
  2636. var templateName = typeof(template) == 'function' ? template(arrayValue) : template;
  2637. arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue));
  2638. arrayItemContext['$index'] = index;
  2639. return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
  2640. }
  2641. // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
  2642. var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
  2643. activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
  2644. if (options['afterRender'])
  2645. options['afterRender'](addedNodesArray, arrayValue);
  2646. };
  2647. return ko.dependentObservable(function () {
  2648. var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
  2649. if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
  2650. unwrappedArray = [unwrappedArray];
  2651. // Filter out any entries marked as destroyed
  2652. var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
  2653. return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
  2654. });
  2655. ko.utils.setDomNodeChildrenFromArrayMapping(targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback);
  2656. }, null, { 'disposeWhenNodeIsRemoved': targetNode });
  2657. };
  2658. var templateSubscriptionDomDataKey = '__ko__templateSubscriptionDomDataKey__';
  2659. function disposeOldSubscriptionAndStoreNewOne(element, newSubscription) {
  2660. var oldSubscription = ko.utils.domData.get(element, templateSubscriptionDomDataKey);
  2661. if (oldSubscription && (typeof(oldSubscription.dispose) == 'function'))
  2662. oldSubscription.dispose();
  2663. ko.utils.domData.set(element, templateSubscriptionDomDataKey, newSubscription);
  2664. }
  2665. ko.bindingHandlers['template'] = {
  2666. 'init': function(element, valueAccessor) {
  2667. // Support anonymous templates
  2668. var bindingValue = ko.utils.unwrapObservable(valueAccessor());
  2669. if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
  2670. // It's an anonymous template - store the element contents, then clear the element
  2671. var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
  2672. container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
  2673. new ko.templateSources.anonymousTemplate(element)['nodes'](container);
  2674. }
  2675. return { 'controlsDescendantBindings': true };
  2676. },
  2677. 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2678. var bindingValue = ko.utils.unwrapObservable(valueAccessor());
  2679. var templateName;
  2680. var shouldDisplay = true;
  2681. if (typeof bindingValue == "string") {
  2682. templateName = bindingValue;
  2683. } else {
  2684. templateName = bindingValue['name'];
  2685. // Support "if"/"ifnot" conditions
  2686. if ('if' in bindingValue)
  2687. shouldDisplay = shouldDisplay && ko.utils.unwrapObservable(bindingValue['if']);
  2688. if ('ifnot' in bindingValue)
  2689. shouldDisplay = shouldDisplay && !ko.utils.unwrapObservable(bindingValue['ifnot']);
  2690. }
  2691. var templateSubscription = null;
  2692. if ((typeof bindingValue === 'object') && ('foreach' in bindingValue)) { // Note: can't use 'in' operator on strings
  2693. // Render once for each data point (treating data set as empty if shouldDisplay==false)
  2694. var dataArray = (shouldDisplay && bindingValue['foreach']) || [];
  2695. templateSubscription = ko.renderTemplateForEach(templateName || element, dataArray, /* options: */ bindingValue, element, bindingContext);
  2696. } else {
  2697. if (shouldDisplay) {
  2698. // Render once for this single data point (or use the viewModel if no data was provided)
  2699. var innerBindingContext = (typeof bindingValue == 'object') && ('data' in bindingValue)
  2700. ? bindingContext['createChildContext'](ko.utils.unwrapObservable(bindingValue['data'])) // Given an explitit 'data' value, we create a child binding context for it
  2701. : bindingContext; // Given no explicit 'data' value, we retain the same binding context
  2702. templateSubscription = ko.renderTemplate(templateName || element, innerBindingContext, /* options: */ bindingValue, element);
  2703. } else
  2704. ko.virtualElements.emptyNode(element);
  2705. }
  2706. // It only makes sense to have a single template subscription per element (otherwise which one should have its output displayed?)
  2707. disposeOldSubscriptionAndStoreNewOne(element, templateSubscription);
  2708. }
  2709. };
  2710. // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
  2711. ko.jsonExpressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
  2712. var parsedBindingValue = ko.jsonExpressionRewriting.parseObjectLiteral(bindingValue);
  2713. if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
  2714. return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
  2715. if (ko.jsonExpressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
  2716. return null; // Named templates can be rewritten, so return "no error"
  2717. return "This template engine does not support anonymous templates nested within its templates";
  2718. };
  2719. ko.virtualElements.allowedBindings['template'] = true;
  2720. })();
  2721. ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
  2722. ko.exportSymbol('renderTemplate', ko.renderTemplate);
  2723. (function () {
  2724. // Simple calculation based on Levenshtein distance.
  2725. function calculateEditDistanceMatrix(oldArray, newArray, maxAllowedDistance) {
  2726. var distances = [];
  2727. for (var i = 0; i <= newArray.length; i++)
  2728. distances[i] = [];
  2729. // Top row - transform old array into empty array via deletions
  2730. for (var i = 0, j = Math.min(oldArray.length, maxAllowedDistance); i <= j; i++)
  2731. distances[0][i] = i;
  2732. // Left row - transform empty array into new array via additions
  2733. for (var i = 1, j = Math.min(newArray.length, maxAllowedDistance); i <= j; i++) {
  2734. distances[i][0] = i;
  2735. }
  2736. // Fill out the body of the array
  2737. var oldIndex, oldIndexMax = oldArray.length, newIndex, newIndexMax = newArray.length;
  2738. var distanceViaAddition, distanceViaDeletion;
  2739. for (oldIndex = 1; oldIndex <= oldIndexMax; oldIndex++) {
  2740. var newIndexMinForRow = Math.max(1, oldIndex - maxAllowedDistance);
  2741. var newIndexMaxForRow = Math.min(newIndexMax, oldIndex + maxAllowedDistance);
  2742. for (newIndex = newIndexMinForRow; newIndex <= newIndexMaxForRow; newIndex++) {
  2743. if (oldArray[oldIndex - 1] === newArray[newIndex - 1])
  2744. distances[newIndex][oldIndex] = distances[newIndex - 1][oldIndex - 1];
  2745. else {
  2746. var northDistance = distances[newIndex - 1][oldIndex] === undefined ? Number.MAX_VALUE : distances[newIndex - 1][oldIndex] + 1;
  2747. var westDistance = distances[newIndex][oldIndex - 1] === undefined ? Number.MAX_VALUE : distances[newIndex][oldIndex - 1] + 1;
  2748. distances[newIndex][oldIndex] = Math.min(northDistance, westDistance);
  2749. }
  2750. }
  2751. }
  2752. return distances;
  2753. }
  2754. function findEditScriptFromEditDistanceMatrix(editDistanceMatrix, oldArray, newArray) {
  2755. var oldIndex = oldArray.length;
  2756. var newIndex = newArray.length;
  2757. var editScript = [];
  2758. var maxDistance = editDistanceMatrix[newIndex][oldIndex];
  2759. if (maxDistance === undefined)
  2760. return null; // maxAllowedDistance must be too small
  2761. while ((oldIndex > 0) || (newIndex > 0)) {
  2762. var me = editDistanceMatrix[newIndex][oldIndex];
  2763. var distanceViaAdd = (newIndex > 0) ? editDistanceMatrix[newIndex - 1][oldIndex] : maxDistance + 1;
  2764. var distanceViaDelete = (oldIndex > 0) ? editDistanceMatrix[newIndex][oldIndex - 1] : maxDistance + 1;
  2765. var distanceViaRetain = (newIndex > 0) && (oldIndex > 0) ? editDistanceMatrix[newIndex - 1][oldIndex - 1] : maxDistance + 1;
  2766. if ((distanceViaAdd === undefined) || (distanceViaAdd < me - 1)) distanceViaAdd = maxDistance + 1;
  2767. if ((distanceViaDelete === undefined) || (distanceViaDelete < me - 1)) distanceViaDelete = maxDistance + 1;
  2768. if (distanceViaRetain < me - 1) distanceViaRetain = maxDistance + 1;
  2769. if ((distanceViaAdd <= distanceViaDelete) && (distanceViaAdd < distanceViaRetain)) {
  2770. editScript.push({ status: "added", value: newArray[newIndex - 1] });
  2771. newIndex--;
  2772. } else if ((distanceViaDelete < distanceViaAdd) && (distanceViaDelete < distanceViaRetain)) {
  2773. editScript.push({ status: "deleted", value: oldArray[oldIndex - 1] });
  2774. oldIndex--;
  2775. } else {
  2776. editScript.push({ status: "retained", value: oldArray[oldIndex - 1] });
  2777. newIndex--;
  2778. oldIndex--;
  2779. }
  2780. }
  2781. return editScript.reverse();
  2782. }
  2783. ko.utils.compareArrays = function (oldArray, newArray, maxEditsToConsider) {
  2784. if (maxEditsToConsider === undefined) {
  2785. return ko.utils.compareArrays(oldArray, newArray, 1) // First consider likely case where there is at most one edit (very fast)
  2786. || ko.utils.compareArrays(oldArray, newArray, 10) // If that fails, account for a fair number of changes while still being fast
  2787. || ko.utils.compareArrays(oldArray, newArray, Number.MAX_VALUE); // Ultimately give the right answer, even though it may take a long time
  2788. } else {
  2789. oldArray = oldArray || [];
  2790. newArray = newArray || [];
  2791. var editDistanceMatrix = calculateEditDistanceMatrix(oldArray, newArray, maxEditsToConsider);
  2792. return findEditScriptFromEditDistanceMatrix(editDistanceMatrix, oldArray, newArray);
  2793. }
  2794. };
  2795. })();
  2796. ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
  2797. (function () {
  2798. // Objective:
  2799. // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
  2800. // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
  2801. // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
  2802. // 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
  2803. // previously mapped - retain those nodes, and just insert/delete other ones
  2804. // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
  2805. // You can use this, for example, to activate bindings on those nodes.
  2806. function fixUpVirtualElements(contiguousNodeArray) {
  2807. // Ensures that contiguousNodeArray really *is* an array of contiguous siblings, even if some of the interior
  2808. // ones have changed since your array was first built (e.g., because your array contains virtual elements, and
  2809. // their virtual children changed when binding was applied to them).
  2810. // This is needed so that we can reliably remove or update the nodes corresponding to a given array item
  2811. if (contiguousNodeArray.length > 2) {
  2812. // Build up the actual new contiguous node set
  2813. var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
  2814. while (current !== last) {
  2815. current = current.nextSibling;
  2816. if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
  2817. return;
  2818. newContiguousSet.push(current);
  2819. }
  2820. // ... then mutate the input array to match this.
  2821. // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
  2822. Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
  2823. }
  2824. }
  2825. function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
  2826. // Map this array value inside a dependentObservable so we re-map when any dependency changes
  2827. var mappedNodes = [];
  2828. var dependentObservable = ko.dependentObservable(function() {
  2829. var newMappedNodes = mapping(valueToMap, index) || [];
  2830. // On subsequent evaluations, just replace the previously-inserted DOM nodes
  2831. if (mappedNodes.length > 0) {
  2832. fixUpVirtualElements(mappedNodes);
  2833. ko.utils.replaceDomNodes(mappedNodes, newMappedNodes);
  2834. if (callbackAfterAddingNodes)
  2835. callbackAfterAddingNodes(valueToMap, newMappedNodes);
  2836. }
  2837. // Replace the contents of the mappedNodes array, thereby updating the record
  2838. // of which nodes would be deleted if valueToMap was itself later removed
  2839. mappedNodes.splice(0, mappedNodes.length);
  2840. ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
  2841. }, null, { 'disposeWhenNodeIsRemoved': containerNode, 'disposeWhen': function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
  2842. return { mappedNodes : mappedNodes, dependentObservable : dependentObservable };
  2843. }
  2844. var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
  2845. ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
  2846. // Compare the provided array against the previous one
  2847. array = array || [];
  2848. options = options || {};
  2849. var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
  2850. var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
  2851. var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
  2852. var editScript = ko.utils.compareArrays(lastArray, array);
  2853. // Build the new mapping result
  2854. var newMappingResult = [];
  2855. var lastMappingResultIndex = 0;
  2856. var nodesToDelete = [];
  2857. var newMappingResultIndex = 0;
  2858. var nodesAdded = [];
  2859. var insertAfterNode = null;
  2860. for (var i = 0, j = editScript.length; i < j; i++) {
  2861. switch (editScript[i].status) {
  2862. case "retained":
  2863. // Just keep the information - don't touch the nodes
  2864. var dataToRetain = lastMappingResult[lastMappingResultIndex];
  2865. dataToRetain.indexObservable(newMappingResultIndex);
  2866. newMappingResultIndex = newMappingResult.push(dataToRetain);
  2867. if (dataToRetain.domNodes.length > 0)
  2868. insertAfterNode = dataToRetain.domNodes[dataToRetain.domNodes.length - 1];
  2869. lastMappingResultIndex++;
  2870. break;
  2871. case "deleted":
  2872. // Stop tracking changes to the mapping for these nodes
  2873. lastMappingResult[lastMappingResultIndex].dependentObservable.dispose();
  2874. // Queue these nodes for later removal
  2875. fixUpVirtualElements(lastMappingResult[lastMappingResultIndex].domNodes);
  2876. ko.utils.arrayForEach(lastMappingResult[lastMappingResultIndex].domNodes, function (node) {
  2877. nodesToDelete.push({
  2878. element: node,
  2879. index: i,
  2880. value: editScript[i].value
  2881. });
  2882. insertAfterNode = node;
  2883. });
  2884. lastMappingResultIndex++;
  2885. break;
  2886. case "added":
  2887. var valueToMap = editScript[i].value;
  2888. var indexObservable = ko.observable(newMappingResultIndex);
  2889. var mapData = mapNodeAndRefreshWhenChanged(domNode, mapping, valueToMap, callbackAfterAddingNodes, indexObservable);
  2890. var mappedNodes = mapData.mappedNodes;
  2891. // On the first evaluation, insert the nodes at the current insertion point
  2892. newMappingResultIndex = newMappingResult.push({
  2893. arrayEntry: editScript[i].value,
  2894. domNodes: mappedNodes,
  2895. dependentObservable: mapData.dependentObservable,
  2896. indexObservable: indexObservable
  2897. });
  2898. for (var nodeIndex = 0, nodeIndexMax = mappedNodes.length; nodeIndex < nodeIndexMax; nodeIndex++) {
  2899. var node = mappedNodes[nodeIndex];
  2900. nodesAdded.push({
  2901. element: node,
  2902. index: i,
  2903. value: editScript[i].value
  2904. });
  2905. if (insertAfterNode == null) {
  2906. // Insert "node" (the newly-created node) as domNode's first child
  2907. ko.virtualElements.prepend(domNode, node);
  2908. } else {
  2909. // Insert "node" into "domNode" immediately after "insertAfterNode"
  2910. ko.virtualElements.insertAfter(domNode, node, insertAfterNode);
  2911. }
  2912. insertAfterNode = node;
  2913. }
  2914. if (callbackAfterAddingNodes)
  2915. callbackAfterAddingNodes(valueToMap, mappedNodes, indexObservable);
  2916. break;
  2917. }
  2918. }
  2919. ko.utils.arrayForEach(nodesToDelete, function (node) { ko.cleanNode(node.element) });
  2920. var invokedBeforeRemoveCallback = false;
  2921. if (!isFirstExecution) {
  2922. if (options['afterAdd']) {
  2923. for (var i = 0; i < nodesAdded.length; i++)
  2924. options['afterAdd'](nodesAdded[i].element, nodesAdded[i].index, nodesAdded[i].value);
  2925. }
  2926. if (options['beforeRemove']) {
  2927. for (var i = 0; i < nodesToDelete.length; i++)
  2928. options['beforeRemove'](nodesToDelete[i].element, nodesToDelete[i].index, nodesToDelete[i].value);
  2929. invokedBeforeRemoveCallback = true;
  2930. }
  2931. }
  2932. if (!invokedBeforeRemoveCallback && nodesToDelete.length) {
  2933. for (var i = 0; i < nodesToDelete.length; i++) {
  2934. var element = nodesToDelete[i].element;
  2935. if (element.parentNode)
  2936. element.parentNode.removeChild(element);
  2937. }
  2938. }
  2939. // Store a copy of the array items we just considered so we can difference it next time
  2940. ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
  2941. }
  2942. })();
  2943. ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
  2944. ko.nativeTemplateEngine = function () {
  2945. this['allowTemplateRewriting'] = false;
  2946. }
  2947. ko.nativeTemplateEngine.prototype = new ko.templateEngine();
  2948. ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
  2949. var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
  2950. templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
  2951. templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
  2952. if (templateNodes) {
  2953. return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
  2954. } else {
  2955. var templateText = templateSource['text']();
  2956. return ko.utils.parseHtmlFragment(templateText);
  2957. }
  2958. };
  2959. ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
  2960. ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
  2961. ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
  2962. (function() {
  2963. ko.jqueryTmplTemplateEngine = function () {
  2964. // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
  2965. // doesn't expose a version number, so we have to infer it.
  2966. // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
  2967. // which KO internally refers to as version "2", so older versions are no longer detected.
  2968. var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
  2969. if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
  2970. return 0;
  2971. // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
  2972. try {
  2973. if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
  2974. // Since 1.0.0pre, custom tags should append markup to an array called "__"
  2975. return 2; // Final version of jquery.tmpl
  2976. }
  2977. } catch(ex) { /* Apparently not the version we were looking for */ }
  2978. return 1; // Any older version that we don't support
  2979. })();
  2980. function ensureHasReferencedJQueryTemplates() {
  2981. if (jQueryTmplVersion < 2)
  2982. throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
  2983. }
  2984. function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
  2985. return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
  2986. }
  2987. this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
  2988. options = options || {};
  2989. ensureHasReferencedJQueryTemplates();
  2990. // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
  2991. var precompiled = templateSource['data']('precompiled');
  2992. if (!precompiled) {
  2993. var templateText = templateSource['text']() || "";
  2994. // Wrap in "with($whatever.koBindingContext) { ... }"
  2995. templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
  2996. precompiled = jQuery['template'](null, templateText);
  2997. templateSource['data']('precompiled', precompiled);
  2998. }
  2999. var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
  3000. var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
  3001. var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
  3002. resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
  3003. jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
  3004. return resultNodes;
  3005. };
  3006. this['createJavaScriptEvaluatorBlock'] = function(script) {
  3007. return "{{ko_code ((function() { return " + script + " })()) }}";
  3008. };
  3009. this['addTemplate'] = function(templateName, templateMarkup) {
  3010. document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
  3011. };
  3012. if (jQueryTmplVersion > 0) {
  3013. jQuery['tmpl']['tag']['ko_code'] = {
  3014. open: "__.push($1 || '');"
  3015. };
  3016. jQuery['tmpl']['tag']['ko_with'] = {
  3017. open: "with($1) {",
  3018. close: "} "
  3019. };
  3020. }
  3021. };
  3022. ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
  3023. // Use this one by default *only if jquery.tmpl is referenced*
  3024. var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
  3025. if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
  3026. ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
  3027. ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
  3028. })();
  3029. });
  3030. })(window,document,navigator);