You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3591 lines
174 KiB

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