knockout-min.js 174 KB

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