/Scripts/knockout-2.2.0.debug.js

https://bitbucket.org/parivedasolutions/attributeroutingtest · JavaScript · 3577 lines · 2979 code · 303 blank · 295 comment · 610 complexity · 53ace77b7c95fc1ec9887939788244b0 MD5 · raw file

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