Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

6612 lignes
379 KiB

  1. /*!
  2. * Knockout JavaScript library v3.5.1
  3. * (c) The Knockout.js team - http://knockoutjs.com/
  4. * License: MIT (http://www.opensource.org/licenses/mit-license.php)
  5. */
  6. (function(){
  7. var DEBUG=true;
  8. (function(undefined){
  9. // (0, eval)('this') is a robust way of getting a reference to the global object
  10. // For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023
  11. var window = this || (0, eval)('this'),
  12. document = window['document'],
  13. navigator = window['navigator'],
  14. jQueryInstance = window["jQuery"],
  15. JSON = window["JSON"];
  16. if (!jQueryInstance && typeof jQuery !== "undefined") {
  17. jQueryInstance = jQuery;
  18. }
  19. (function(factory) {
  20. // Support three module loading scenarios
  21. if (typeof define === 'function' && define['amd']) {
  22. // [1] AMD anonymous module
  23. define(['exports', 'require'], factory);
  24. } else if (typeof exports === 'object' && typeof module === 'object') {
  25. // [2] CommonJS/Node.js
  26. factory(module['exports'] || exports); // module.exports is for Node.js
  27. } else {
  28. // [3] No module loader (plain <script> tag) - put directly in global namespace
  29. factory(window['ko'] = {});
  30. }
  31. }(function(koExports, amdRequire){
  32. // Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
  33. // In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
  34. var ko = typeof koExports !== 'undefined' ? koExports : {};
  35. // Google Closure Compiler helpers (used only to make the minified file smaller)
  36. ko.exportSymbol = function(koPath, object) {
  37. var tokens = koPath.split(".");
  38. // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
  39. // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
  40. var target = ko;
  41. for (var i = 0; i < tokens.length - 1; i++)
  42. target = target[tokens[i]];
  43. target[tokens[tokens.length - 1]] = object;
  44. };
  45. ko.exportProperty = function(owner, publicName, object) {
  46. owner[publicName] = object;
  47. };
  48. ko.version = "3.5.1";
  49. ko.exportSymbol('version', ko.version);
  50. // For any options that may affect various areas of Knockout and aren't directly associated with data binding.
  51. ko.options = {
  52. 'deferUpdates': false,
  53. 'useOnlyNativeEvents': false,
  54. 'foreachHidesDestroyed': false
  55. };
  56. //ko.exportSymbol('options', ko.options); // 'options' isn't minified
  57. ko.utils = (function () {
  58. var hasOwnProperty = Object.prototype.hasOwnProperty;
  59. function objectForEach(obj, action) {
  60. for (var prop in obj) {
  61. if (hasOwnProperty.call(obj, prop)) {
  62. action(prop, obj[prop]);
  63. }
  64. }
  65. }
  66. function extend(target, source) {
  67. if (source) {
  68. for(var prop in source) {
  69. if(hasOwnProperty.call(source, prop)) {
  70. target[prop] = source[prop];
  71. }
  72. }
  73. }
  74. return target;
  75. }
  76. function setPrototypeOf(obj, proto) {
  77. obj.__proto__ = proto;
  78. return obj;
  79. }
  80. var canSetPrototype = ({ __proto__: [] } instanceof Array);
  81. var canUseSymbols = !DEBUG && typeof Symbol === 'function';
  82. // 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)
  83. var knownEvents = {}, knownEventTypesByEventName = {};
  84. var keyEventTypeName = (navigator && /Firefox\/2/i.test(navigator.userAgent)) ? 'KeyboardEvent' : 'UIEvents';
  85. knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
  86. knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
  87. objectForEach(knownEvents, function(eventType, knownEventsForType) {
  88. if (knownEventsForType.length) {
  89. for (var i = 0, j = knownEventsForType.length; i < j; i++)
  90. knownEventTypesByEventName[knownEventsForType[i]] = eventType;
  91. }
  92. });
  93. var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
  94. // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
  95. // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
  96. // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
  97. // If there is a future need to detect specific versions of IE10+, we will amend this.
  98. var ieVersion = document && (function() {
  99. var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
  100. // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
  101. while (
  102. div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
  103. iElems[0]
  104. ) {}
  105. return version > 4 ? version : undefined;
  106. }());
  107. var isIe6 = ieVersion === 6,
  108. isIe7 = ieVersion === 7;
  109. function isClickOnCheckableElement(element, eventType) {
  110. if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
  111. if (eventType.toLowerCase() != "click") return false;
  112. var inputType = element.type;
  113. return (inputType == "checkbox") || (inputType == "radio");
  114. }
  115. // For details on the pattern for changing node classes
  116. // see: https://github.com/knockout/knockout/issues/1597
  117. var cssClassNameRegex = /\S+/g;
  118. var jQueryEventAttachName;
  119. function toggleDomNodeCssClass(node, classNames, shouldHaveClass) {
  120. var addOrRemoveFn;
  121. if (classNames) {
  122. if (typeof node.classList === 'object') {
  123. addOrRemoveFn = node.classList[shouldHaveClass ? 'add' : 'remove'];
  124. ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
  125. addOrRemoveFn.call(node.classList, className);
  126. });
  127. } else if (typeof node.className['baseVal'] === 'string') {
  128. // SVG tag .classNames is an SVGAnimatedString instance
  129. toggleObjectClassPropertyString(node.className, 'baseVal', classNames, shouldHaveClass);
  130. } else {
  131. // node.className ought to be a string.
  132. toggleObjectClassPropertyString(node, 'className', classNames, shouldHaveClass);
  133. }
  134. }
  135. }
  136. function toggleObjectClassPropertyString(obj, prop, classNames, shouldHaveClass) {
  137. // obj/prop is either a node/'className' or a SVGAnimatedString/'baseVal'.
  138. var currentClassNames = obj[prop].match(cssClassNameRegex) || [];
  139. ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
  140. ko.utils.addOrRemoveItem(currentClassNames, className, shouldHaveClass);
  141. });
  142. obj[prop] = currentClassNames.join(" ");
  143. }
  144. return {
  145. fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
  146. arrayForEach: function (array, action, actionOwner) {
  147. for (var i = 0, j = array.length; i < j; i++) {
  148. action.call(actionOwner, array[i], i, array);
  149. }
  150. },
  151. arrayIndexOf: typeof Array.prototype.indexOf == "function"
  152. ? function (array, item) {
  153. return Array.prototype.indexOf.call(array, item);
  154. }
  155. : function (array, item) {
  156. for (var i = 0, j = array.length; i < j; i++) {
  157. if (array[i] === item)
  158. return i;
  159. }
  160. return -1;
  161. },
  162. arrayFirst: function (array, predicate, predicateOwner) {
  163. for (var i = 0, j = array.length; i < j; i++) {
  164. if (predicate.call(predicateOwner, array[i], i, array))
  165. return array[i];
  166. }
  167. return undefined;
  168. },
  169. arrayRemoveItem: function (array, itemToRemove) {
  170. var index = ko.utils.arrayIndexOf(array, itemToRemove);
  171. if (index > 0) {
  172. array.splice(index, 1);
  173. }
  174. else if (index === 0) {
  175. array.shift();
  176. }
  177. },
  178. arrayGetDistinctValues: function (array) {
  179. var result = [];
  180. if (array) {
  181. ko.utils.arrayForEach(array, function(item) {
  182. if (ko.utils.arrayIndexOf(result, item) < 0)
  183. result.push(item);
  184. });
  185. }
  186. return result;
  187. },
  188. arrayMap: function (array, mapping, mappingOwner) {
  189. var result = [];
  190. if (array) {
  191. for (var i = 0, j = array.length; i < j; i++)
  192. result.push(mapping.call(mappingOwner, array[i], i));
  193. }
  194. return result;
  195. },
  196. arrayFilter: function (array, predicate, predicateOwner) {
  197. var result = [];
  198. if (array) {
  199. for (var i = 0, j = array.length; i < j; i++)
  200. if (predicate.call(predicateOwner, array[i], i))
  201. result.push(array[i]);
  202. }
  203. return result;
  204. },
  205. arrayPushAll: function (array, valuesToPush) {
  206. if (valuesToPush instanceof Array)
  207. array.push.apply(array, valuesToPush);
  208. else
  209. for (var i = 0, j = valuesToPush.length; i < j; i++)
  210. array.push(valuesToPush[i]);
  211. return array;
  212. },
  213. addOrRemoveItem: function(array, value, included) {
  214. var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.peekObservable(array), value);
  215. if (existingEntryIndex < 0) {
  216. if (included)
  217. array.push(value);
  218. } else {
  219. if (!included)
  220. array.splice(existingEntryIndex, 1);
  221. }
  222. },
  223. canSetPrototype: canSetPrototype,
  224. extend: extend,
  225. setPrototypeOf: setPrototypeOf,
  226. setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : extend,
  227. objectForEach: objectForEach,
  228. objectMap: function(source, mapping, mappingOwner) {
  229. if (!source)
  230. return source;
  231. var target = {};
  232. for (var prop in source) {
  233. if (hasOwnProperty.call(source, prop)) {
  234. target[prop] = mapping.call(mappingOwner, source[prop], prop, source);
  235. }
  236. }
  237. return target;
  238. },
  239. emptyDomNode: function (domNode) {
  240. while (domNode.firstChild) {
  241. ko.removeNode(domNode.firstChild);
  242. }
  243. },
  244. moveCleanedNodesToContainerElement: function(nodes) {
  245. // Ensure it's a real array, as we're about to reparent the nodes and
  246. // we don't want the underlying collection to change while we're doing that.
  247. var nodesArray = ko.utils.makeArray(nodes);
  248. var templateDocument = (nodesArray[0] && nodesArray[0].ownerDocument) || document;
  249. var container = templateDocument.createElement('div');
  250. for (var i = 0, j = nodesArray.length; i < j; i++) {
  251. container.appendChild(ko.cleanNode(nodesArray[i]));
  252. }
  253. return container;
  254. },
  255. cloneNodes: function (nodesArray, shouldCleanNodes) {
  256. for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
  257. var clonedNode = nodesArray[i].cloneNode(true);
  258. newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
  259. }
  260. return newNodesArray;
  261. },
  262. setDomNodeChildren: function (domNode, childNodes) {
  263. ko.utils.emptyDomNode(domNode);
  264. if (childNodes) {
  265. for (var i = 0, j = childNodes.length; i < j; i++)
  266. domNode.appendChild(childNodes[i]);
  267. }
  268. },
  269. replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
  270. var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
  271. if (nodesToReplaceArray.length > 0) {
  272. var insertionPoint = nodesToReplaceArray[0];
  273. var parent = insertionPoint.parentNode;
  274. for (var i = 0, j = newNodesArray.length; i < j; i++)
  275. parent.insertBefore(newNodesArray[i], insertionPoint);
  276. for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
  277. ko.removeNode(nodesToReplaceArray[i]);
  278. }
  279. }
  280. },
  281. fixUpContinuousNodeArray: function(continuousNodeArray, parentNode) {
  282. // Before acting on a set of nodes that were previously outputted by a template function, we have to reconcile
  283. // them against what is in the DOM right now. It may be that some of the nodes have already been removed, or that
  284. // new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
  285. // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
  286. // So, this function translates the old "map" output array into its best guess of the set of current DOM nodes.
  287. //
  288. // Rules:
  289. // [A] Any leading nodes that have been removed should be ignored
  290. // These most likely correspond to memoization nodes that were already removed during binding
  291. // See https://github.com/knockout/knockout/pull/440
  292. // [B] Any trailing nodes that have been remove should be ignored
  293. // This prevents the code here from adding unrelated nodes to the array while processing rule [C]
  294. // See https://github.com/knockout/knockout/pull/1903
  295. // [C] We want to output a continuous series of nodes. So, ignore any nodes that have already been removed,
  296. // and include any nodes that have been inserted among the previous collection
  297. if (continuousNodeArray.length) {
  298. // The parent node can be a virtual element; so get the real parent node
  299. parentNode = (parentNode.nodeType === 8 && parentNode.parentNode) || parentNode;
  300. // Rule [A]
  301. while (continuousNodeArray.length && continuousNodeArray[0].parentNode !== parentNode)
  302. continuousNodeArray.splice(0, 1);
  303. // Rule [B]
  304. while (continuousNodeArray.length > 1 && continuousNodeArray[continuousNodeArray.length - 1].parentNode !== parentNode)
  305. continuousNodeArray.length--;
  306. // Rule [C]
  307. if (continuousNodeArray.length > 1) {
  308. var current = continuousNodeArray[0], last = continuousNodeArray[continuousNodeArray.length - 1];
  309. // Replace with the actual new continuous node set
  310. continuousNodeArray.length = 0;
  311. while (current !== last) {
  312. continuousNodeArray.push(current);
  313. current = current.nextSibling;
  314. }
  315. continuousNodeArray.push(last);
  316. }
  317. }
  318. return continuousNodeArray;
  319. },
  320. setOptionNodeSelectionState: function (optionNode, isSelected) {
  321. // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
  322. if (ieVersion < 7)
  323. optionNode.setAttribute("selected", isSelected);
  324. else
  325. optionNode.selected = isSelected;
  326. },
  327. stringTrim: function (string) {
  328. return string === null || string === undefined ? '' :
  329. string.trim ?
  330. string.trim() :
  331. string.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
  332. },
  333. stringStartsWith: function (string, startsWith) {
  334. string = string || "";
  335. if (startsWith.length > string.length)
  336. return false;
  337. return string.substring(0, startsWith.length) === startsWith;
  338. },
  339. domNodeIsContainedBy: function (node, containedByNode) {
  340. if (node === containedByNode)
  341. return true;
  342. if (node.nodeType === 11)
  343. return false; // Fixes issue #1162 - can't use node.contains for document fragments on IE8
  344. if (containedByNode.contains)
  345. return containedByNode.contains(node.nodeType !== 1 ? node.parentNode : node);
  346. if (containedByNode.compareDocumentPosition)
  347. return (containedByNode.compareDocumentPosition(node) & 16) == 16;
  348. while (node && node != containedByNode) {
  349. node = node.parentNode;
  350. }
  351. return !!node;
  352. },
  353. domNodeIsAttachedToDocument: function (node) {
  354. return ko.utils.domNodeIsContainedBy(node, node.ownerDocument.documentElement);
  355. },
  356. anyDomNodeIsAttachedToDocument: function(nodes) {
  357. return !!ko.utils.arrayFirst(nodes, ko.utils.domNodeIsAttachedToDocument);
  358. },
  359. tagNameLower: function(element) {
  360. // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
  361. // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
  362. // we don't need to do the .toLowerCase() as it will always be lower case anyway.
  363. return element && element.tagName && element.tagName.toLowerCase();
  364. },
  365. catchFunctionErrors: function (delegate) {
  366. return ko['onError'] ? function () {
  367. try {
  368. return delegate.apply(this, arguments);
  369. } catch (e) {
  370. ko['onError'] && ko['onError'](e);
  371. throw e;
  372. }
  373. } : delegate;
  374. },
  375. setTimeout: function (handler, timeout) {
  376. return setTimeout(ko.utils.catchFunctionErrors(handler), timeout);
  377. },
  378. deferError: function (error) {
  379. setTimeout(function () {
  380. ko['onError'] && ko['onError'](error);
  381. throw error;
  382. }, 0);
  383. },
  384. registerEventHandler: function (element, eventType, handler) {
  385. var wrappedHandler = ko.utils.catchFunctionErrors(handler);
  386. var mustUseAttachEvent = eventsThatMustBeRegisteredUsingAttachEvent[eventType];
  387. if (!ko.options['useOnlyNativeEvents'] && !mustUseAttachEvent && jQueryInstance) {
  388. if (!jQueryEventAttachName) {
  389. jQueryEventAttachName = (typeof jQueryInstance(element)['on'] == 'function') ? 'on' : 'bind';
  390. }
  391. jQueryInstance(element)[jQueryEventAttachName](eventType, wrappedHandler);
  392. } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
  393. element.addEventListener(eventType, wrappedHandler, false);
  394. else if (typeof element.attachEvent != "undefined") {
  395. var attachEventHandler = function (event) { wrappedHandler.call(element, event); },
  396. attachEventName = "on" + eventType;
  397. element.attachEvent(attachEventName, attachEventHandler);
  398. // IE does not dispose attachEvent handlers automatically (unlike with addEventListener)
  399. // so to avoid leaks, we have to remove them manually. See bug #856
  400. ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
  401. element.detachEvent(attachEventName, attachEventHandler);
  402. });
  403. } else
  404. throw new Error("Browser doesn't support addEventListener or attachEvent");
  405. },
  406. triggerEvent: function (element, eventType) {
  407. if (!(element && element.nodeType))
  408. throw new Error("element must be a DOM node when calling triggerEvent");
  409. // For click events on checkboxes and radio buttons, jQuery toggles the element checked state *after* the
  410. // event handler runs instead of *before*. (This was fixed in 1.9 for checkboxes but not for radio buttons.)
  411. // IE doesn't change the checked state when you trigger the click event using "fireEvent".
  412. // In both cases, we'll use the click method instead.
  413. var useClickWorkaround = isClickOnCheckableElement(element, eventType);
  414. if (!ko.options['useOnlyNativeEvents'] && jQueryInstance && !useClickWorkaround) {
  415. jQueryInstance(element)['trigger'](eventType);
  416. } else if (typeof document.createEvent == "function") {
  417. if (typeof element.dispatchEvent == "function") {
  418. var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
  419. var event = document.createEvent(eventCategory);
  420. event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
  421. element.dispatchEvent(event);
  422. }
  423. else
  424. throw new Error("The supplied element doesn't support dispatchEvent");
  425. } else if (useClickWorkaround && element.click) {
  426. element.click();
  427. } else if (typeof element.fireEvent != "undefined") {
  428. element.fireEvent("on" + eventType);
  429. } else {
  430. throw new Error("Browser doesn't support triggering events");
  431. }
  432. },
  433. unwrapObservable: function (value) {
  434. return ko.isObservable(value) ? value() : value;
  435. },
  436. peekObservable: function (value) {
  437. return ko.isObservable(value) ? value.peek() : value;
  438. },
  439. toggleDomNodeCssClass: toggleDomNodeCssClass,
  440. setTextContent: function(element, textContent) {
  441. var value = ko.utils.unwrapObservable(textContent);
  442. if ((value === null) || (value === undefined))
  443. value = "";
  444. // We need there to be exactly one child: a text node.
  445. // If there are no children, more than one, or if it's not a text node,
  446. // we'll clear everything and create a single text node.
  447. var innerTextNode = ko.virtualElements.firstChild(element);
  448. if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
  449. ko.virtualElements.setDomNodeChildren(element, [element.ownerDocument.createTextNode(value)]);
  450. } else {
  451. innerTextNode.data = value;
  452. }
  453. ko.utils.forceRefresh(element);
  454. },
  455. setElementName: function(element, name) {
  456. element.name = name;
  457. // Workaround IE 6/7 issue
  458. // - https://github.com/SteveSanderson/knockout/issues/197
  459. // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
  460. if (ieVersion <= 7) {
  461. try {
  462. var escapedName = element.name.replace(/[&<>'"]/g, function(r){ return "&#" + r.charCodeAt(0) + ";"; });
  463. element.mergeAttributes(document.createElement("<input name='" + escapedName + "'/>"), false);
  464. }
  465. catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
  466. }
  467. },
  468. forceRefresh: function(node) {
  469. // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
  470. if (ieVersion >= 9) {
  471. // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
  472. var elem = node.nodeType == 1 ? node : node.parentNode;
  473. if (elem.style)
  474. elem.style.zoom = elem.style.zoom;
  475. }
  476. },
  477. ensureSelectElementIsRenderedCorrectly: function(selectElement) {
  478. // 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.
  479. // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
  480. // Also fixes IE7 and IE8 bug that causes selects to be zero width if enclosed by 'if' or 'with'. (See issue #839)
  481. if (ieVersion) {
  482. var originalWidth = selectElement.style.width;
  483. selectElement.style.width = 0;
  484. selectElement.style.width = originalWidth;
  485. }
  486. },
  487. range: function (min, max) {
  488. min = ko.utils.unwrapObservable(min);
  489. max = ko.utils.unwrapObservable(max);
  490. var result = [];
  491. for (var i = min; i <= max; i++)
  492. result.push(i);
  493. return result;
  494. },
  495. makeArray: function(arrayLikeObject) {
  496. var result = [];
  497. for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
  498. result.push(arrayLikeObject[i]);
  499. };
  500. return result;
  501. },
  502. createSymbolOrString: function(identifier) {
  503. return canUseSymbols ? Symbol(identifier) : identifier;
  504. },
  505. isIe6 : isIe6,
  506. isIe7 : isIe7,
  507. ieVersion : ieVersion,
  508. getFormFields: function(form, fieldName) {
  509. var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
  510. var isMatchingField = (typeof fieldName == 'string')
  511. ? function(field) { return field.name === fieldName }
  512. : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
  513. var matches = [];
  514. for (var i = fields.length - 1; i >= 0; i--) {
  515. if (isMatchingField(fields[i]))
  516. matches.push(fields[i]);
  517. };
  518. return matches;
  519. },
  520. parseJson: function (jsonString) {
  521. if (typeof jsonString == "string") {
  522. jsonString = ko.utils.stringTrim(jsonString);
  523. if (jsonString) {
  524. if (JSON && JSON.parse) // Use native parsing where available
  525. return JSON.parse(jsonString);
  526. return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
  527. }
  528. }
  529. return null;
  530. },
  531. stringifyJson: function (data, replacer, space) { // replacer and space are optional
  532. if (!JSON || !JSON.stringify)
  533. 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");
  534. return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
  535. },
  536. postJson: function (urlOrForm, data, options) {
  537. options = options || {};
  538. var params = options['params'] || {};
  539. var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
  540. var url = urlOrForm;
  541. // If we were given a form, use its 'action' URL and pick out any requested field values
  542. if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
  543. var originalForm = urlOrForm;
  544. url = originalForm.action;
  545. for (var i = includeFields.length - 1; i >= 0; i--) {
  546. var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
  547. for (var j = fields.length - 1; j >= 0; j--)
  548. params[fields[j].name] = fields[j].value;
  549. }
  550. }
  551. data = ko.utils.unwrapObservable(data);
  552. var form = document.createElement("form");
  553. form.style.display = "none";
  554. form.action = url;
  555. form.method = "post";
  556. for (var key in data) {
  557. // Since 'data' this is a model object, we include all properties including those inherited from its prototype
  558. var input = document.createElement("input");
  559. input.type = "hidden";
  560. input.name = key;
  561. input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
  562. form.appendChild(input);
  563. }
  564. objectForEach(params, function(key, value) {
  565. var input = document.createElement("input");
  566. input.type = "hidden";
  567. input.name = key;
  568. input.value = value;
  569. form.appendChild(input);
  570. });
  571. document.body.appendChild(form);
  572. options['submitter'] ? options['submitter'](form) : form.submit();
  573. setTimeout(function () { form.parentNode.removeChild(form); }, 0);
  574. }
  575. }
  576. }());
  577. ko.exportSymbol('utils', ko.utils);
  578. ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
  579. ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
  580. ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
  581. ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
  582. ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
  583. ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
  584. ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
  585. ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
  586. ko.exportSymbol('utils.cloneNodes', ko.utils.cloneNodes);
  587. ko.exportSymbol('utils.createSymbolOrString', ko.utils.createSymbolOrString);
  588. ko.exportSymbol('utils.extend', ko.utils.extend);
  589. ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
  590. ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
  591. ko.exportSymbol('utils.objectMap', ko.utils.objectMap);
  592. ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
  593. ko.exportSymbol('utils.postJson', ko.utils.postJson);
  594. ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
  595. ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
  596. ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
  597. ko.exportSymbol('utils.range', ko.utils.range);
  598. ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
  599. ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
  600. ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
  601. ko.exportSymbol('utils.objectForEach', ko.utils.objectForEach);
  602. ko.exportSymbol('utils.addOrRemoveItem', ko.utils.addOrRemoveItem);
  603. ko.exportSymbol('utils.setTextContent', ko.utils.setTextContent);
  604. ko.exportSymbol('unwrap', ko.utils.unwrapObservable); // Convenient shorthand, because this is used so commonly
  605. if (!Function.prototype['bind']) {
  606. // 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)
  607. // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
  608. Function.prototype['bind'] = function (object) {
  609. var originalFunction = this;
  610. if (arguments.length === 1) {
  611. return function () {
  612. return originalFunction.apply(object, arguments);
  613. };
  614. } else {
  615. var partialArgs = Array.prototype.slice.call(arguments, 1);
  616. return function () {
  617. var args = partialArgs.slice(0);
  618. args.push.apply(args, arguments);
  619. return originalFunction.apply(object, args);
  620. };
  621. }
  622. };
  623. }
  624. ko.utils.domData = new (function () {
  625. var uniqueId = 0;
  626. var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
  627. var dataStore = {};
  628. var getDataForNode, clear;
  629. if (!ko.utils.ieVersion) {
  630. // We considered using WeakMap, but it has a problem in IE 11 and Edge that prevents using
  631. // it cross-window, so instead we just store the data directly on the node.
  632. // See https://github.com/knockout/knockout/issues/2141
  633. getDataForNode = function (node, createIfNotFound) {
  634. var dataForNode = node[dataStoreKeyExpandoPropertyName];
  635. if (!dataForNode && createIfNotFound) {
  636. dataForNode = node[dataStoreKeyExpandoPropertyName] = {};
  637. }
  638. return dataForNode;
  639. };
  640. clear = function (node) {
  641. if (node[dataStoreKeyExpandoPropertyName]) {
  642. delete node[dataStoreKeyExpandoPropertyName];
  643. return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
  644. }
  645. return false;
  646. };
  647. } else {
  648. // Old IE versions have memory issues if you store objects on the node, so we use a
  649. // separate data storage and link to it from the node using a string key.
  650. getDataForNode = function (node, createIfNotFound) {
  651. var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
  652. var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
  653. if (!hasExistingDataStore) {
  654. if (!createIfNotFound)
  655. return undefined;
  656. dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
  657. dataStore[dataStoreKey] = {};
  658. }
  659. return dataStore[dataStoreKey];
  660. };
  661. clear = function (node) {
  662. var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
  663. if (dataStoreKey) {
  664. delete dataStore[dataStoreKey];
  665. node[dataStoreKeyExpandoPropertyName] = null;
  666. return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
  667. }
  668. return false;
  669. };
  670. }
  671. return {
  672. get: function (node, key) {
  673. var dataForNode = getDataForNode(node, false);
  674. return dataForNode && dataForNode[key];
  675. },
  676. set: function (node, key, value) {
  677. // Make sure we don't actually create a new domData key if we are actually deleting a value
  678. var dataForNode = getDataForNode(node, value !== undefined /* createIfNotFound */);
  679. dataForNode && (dataForNode[key] = value);
  680. },
  681. getOrSet: function (node, key, value) {
  682. var dataForNode = getDataForNode(node, true /* createIfNotFound */);
  683. return dataForNode[key] || (dataForNode[key] = value);
  684. },
  685. clear: clear,
  686. nextKey: function () {
  687. return (uniqueId++) + dataStoreKeyExpandoPropertyName;
  688. }
  689. };
  690. })();
  691. ko.exportSymbol('utils.domData', ko.utils.domData);
  692. ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
  693. ko.utils.domNodeDisposal = new (function () {
  694. var domDataKey = ko.utils.domData.nextKey();
  695. var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
  696. var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
  697. function getDisposeCallbacksCollection(node, createIfNotFound) {
  698. var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
  699. if ((allDisposeCallbacks === undefined) && createIfNotFound) {
  700. allDisposeCallbacks = [];
  701. ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
  702. }
  703. return allDisposeCallbacks;
  704. }
  705. function destroyCallbacksCollection(node) {
  706. ko.utils.domData.set(node, domDataKey, undefined);
  707. }
  708. function cleanSingleNode(node) {
  709. // Run all the dispose callbacks
  710. var callbacks = getDisposeCallbacksCollection(node, false);
  711. if (callbacks) {
  712. callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
  713. for (var i = 0; i < callbacks.length; i++)
  714. callbacks[i](node);
  715. }
  716. // Erase the DOM data
  717. ko.utils.domData.clear(node);
  718. // Perform cleanup needed by external libraries (currently only jQuery, but can be extended)
  719. ko.utils.domNodeDisposal["cleanExternalData"](node);
  720. // Clear any immediate-child comment nodes, as these wouldn't have been found by
  721. // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
  722. if (cleanableNodeTypesWithDescendants[node.nodeType]) {
  723. cleanNodesInList(node.childNodes, true/*onlyComments*/);
  724. }
  725. }
  726. function cleanNodesInList(nodeList, onlyComments) {
  727. var cleanedNodes = [], lastCleanedNode;
  728. for (var i = 0; i < nodeList.length; i++) {
  729. if (!onlyComments || nodeList[i].nodeType === 8) {
  730. cleanSingleNode(cleanedNodes[cleanedNodes.length] = lastCleanedNode = nodeList[i]);
  731. if (nodeList[i] !== lastCleanedNode) {
  732. while (i-- && ko.utils.arrayIndexOf(cleanedNodes, nodeList[i]) == -1) {}
  733. }
  734. }
  735. }
  736. }
  737. return {
  738. addDisposeCallback : function(node, callback) {
  739. if (typeof callback != "function")
  740. throw new Error("Callback must be a function");
  741. getDisposeCallbacksCollection(node, true).push(callback);
  742. },
  743. removeDisposeCallback : function(node, callback) {
  744. var callbacksCollection = getDisposeCallbacksCollection(node, false);
  745. if (callbacksCollection) {
  746. ko.utils.arrayRemoveItem(callbacksCollection, callback);
  747. if (callbacksCollection.length == 0)
  748. destroyCallbacksCollection(node);
  749. }
  750. },
  751. cleanNode : function(node) {
  752. ko.dependencyDetection.ignore(function () {
  753. // First clean this node, where applicable
  754. if (cleanableNodeTypes[node.nodeType]) {
  755. cleanSingleNode(node);
  756. // ... then its descendants, where applicable
  757. if (cleanableNodeTypesWithDescendants[node.nodeType]) {
  758. cleanNodesInList(node.getElementsByTagName("*"));
  759. }
  760. }
  761. });
  762. return node;
  763. },
  764. removeNode : function(node) {
  765. ko.cleanNode(node);
  766. if (node.parentNode)
  767. node.parentNode.removeChild(node);
  768. },
  769. "cleanExternalData" : function (node) {
  770. // Special support for jQuery here because it's so commonly used.
  771. // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
  772. // so notify it to tear down any resources associated with the node & descendants here.
  773. if (jQueryInstance && (typeof jQueryInstance['cleanData'] == "function"))
  774. jQueryInstance['cleanData']([node]);
  775. }
  776. };
  777. })();
  778. ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
  779. ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
  780. ko.exportSymbol('cleanNode', ko.cleanNode);
  781. ko.exportSymbol('removeNode', ko.removeNode);
  782. ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
  783. ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
  784. ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
  785. (function () {
  786. var none = [0, "", ""],
  787. table = [1, "<table>", "</table>"],
  788. tbody = [2, "<table><tbody>", "</tbody></table>"],
  789. tr = [3, "<table><tbody><tr>", "</tr></tbody></table>"],
  790. select = [1, "<select multiple='multiple'>", "</select>"],
  791. lookup = {
  792. 'thead': table,
  793. 'tbody': table,
  794. 'tfoot': table,
  795. 'tr': tbody,
  796. 'td': tr,
  797. 'th': tr,
  798. 'option': select,
  799. 'optgroup': select
  800. },
  801. // This is needed for old IE if you're *not* using either jQuery or innerShiv. Doesn't affect other cases.
  802. mayRequireCreateElementHack = ko.utils.ieVersion <= 8;
  803. function getWrap(tags) {
  804. var m = tags.match(/^(?:<!--.*?-->\s*?)*?<([a-z]+)[\s>]/);
  805. return (m && lookup[m[1]]) || none;
  806. }
  807. function simpleHtmlParse(html, documentContext) {
  808. documentContext || (documentContext = document);
  809. var windowContext = documentContext['parentWindow'] || documentContext['defaultView'] || window;
  810. // Based on jQuery's "clean" function, but only accounting for table-related elements.
  811. // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
  812. // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
  813. // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
  814. // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
  815. // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
  816. // Trim whitespace, otherwise indexOf won't work as expected
  817. var tags = ko.utils.stringTrim(html).toLowerCase(), div = documentContext.createElement("div"),
  818. wrap = getWrap(tags),
  819. depth = wrap[0];
  820. // Go to html and back, then peel off extra wrappers
  821. // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
  822. var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
  823. if (typeof windowContext['innerShiv'] == "function") {
  824. // Note that innerShiv is deprecated in favour of html5shiv. We should consider adding
  825. // support for html5shiv (except if no explicit support is needed, e.g., if html5shiv
  826. // somehow shims the native APIs so it just works anyway)
  827. div.appendChild(windowContext['innerShiv'](markup));
  828. } else {
  829. if (mayRequireCreateElementHack) {
  830. // The document.createElement('my-element') trick to enable custom elements in IE6-8
  831. // only works if we assign innerHTML on an element associated with that document.
  832. documentContext.body.appendChild(div);
  833. }
  834. div.innerHTML = markup;
  835. if (mayRequireCreateElementHack) {
  836. div.parentNode.removeChild(div);
  837. }
  838. }
  839. // Move to the right depth
  840. while (depth--)
  841. div = div.lastChild;
  842. return ko.utils.makeArray(div.lastChild.childNodes);
  843. }
  844. function jQueryHtmlParse(html, documentContext) {
  845. // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
  846. if (jQueryInstance['parseHTML']) {
  847. return jQueryInstance['parseHTML'](html, documentContext) || []; // Ensure we always return an array and never null
  848. } else {
  849. // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
  850. var elems = jQueryInstance['clean']([html], documentContext);
  851. // 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.
  852. // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
  853. // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
  854. if (elems && elems[0]) {
  855. // Find the top-most parent element that's a direct child of a document fragment
  856. var elem = elems[0];
  857. while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
  858. elem = elem.parentNode;
  859. // ... then detach it
  860. if (elem.parentNode)
  861. elem.parentNode.removeChild(elem);
  862. }
  863. return elems;
  864. }
  865. }
  866. ko.utils.parseHtmlFragment = function(html, documentContext) {
  867. return jQueryInstance ?
  868. jQueryHtmlParse(html, documentContext) : // As below, benefit from jQuery's optimisations where possible
  869. simpleHtmlParse(html, documentContext); // ... otherwise, this simple logic will do in most common cases.
  870. };
  871. ko.utils.parseHtmlForTemplateNodes = function(html, documentContext) {
  872. var nodes = ko.utils.parseHtmlFragment(html, documentContext);
  873. return (nodes.length && nodes[0].parentElement) || ko.utils.moveCleanedNodesToContainerElement(nodes);
  874. };
  875. ko.utils.setHtml = function(node, html) {
  876. ko.utils.emptyDomNode(node);
  877. // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
  878. html = ko.utils.unwrapObservable(html);
  879. if ((html !== null) && (html !== undefined)) {
  880. if (typeof html != 'string')
  881. html = html.toString();
  882. // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
  883. // for example <tr> elements which are not normally allowed to exist on their own.
  884. // If you've referenced jQuery we'll use that rather than duplicating its code.
  885. if (jQueryInstance) {
  886. jQueryInstance(node)['html'](html);
  887. } else {
  888. // ... otherwise, use KO's own parsing logic.
  889. var parsedNodes = ko.utils.parseHtmlFragment(html, node.ownerDocument);
  890. for (var i = 0; i < parsedNodes.length; i++)
  891. node.appendChild(parsedNodes[i]);
  892. }
  893. }
  894. };
  895. })();
  896. ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
  897. ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
  898. ko.memoization = (function () {
  899. var memos = {};
  900. function randomMax8HexChars() {
  901. return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
  902. }
  903. function generateRandomId() {
  904. return randomMax8HexChars() + randomMax8HexChars();
  905. }
  906. function findMemoNodes(rootNode, appendToArray) {
  907. if (!rootNode)
  908. return;
  909. if (rootNode.nodeType == 8) {
  910. var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
  911. if (memoId != null)
  912. appendToArray.push({ domNode: rootNode, memoId: memoId });
  913. } else if (rootNode.nodeType == 1) {
  914. for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
  915. findMemoNodes(childNodes[i], appendToArray);
  916. }
  917. }
  918. return {
  919. memoize: function (callback) {
  920. if (typeof callback != "function")
  921. throw new Error("You can only pass a function to ko.memoization.memoize()");
  922. var memoId = generateRandomId();
  923. memos[memoId] = callback;
  924. return "<!--[ko_memo:" + memoId + "]-->";
  925. },
  926. unmemoize: function (memoId, callbackParams) {
  927. var callback = memos[memoId];
  928. if (callback === undefined)
  929. throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
  930. try {
  931. callback.apply(null, callbackParams || []);
  932. return true;
  933. }
  934. finally { delete memos[memoId]; }
  935. },
  936. unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
  937. var memos = [];
  938. findMemoNodes(domNode, memos);
  939. for (var i = 0, j = memos.length; i < j; i++) {
  940. var node = memos[i].domNode;
  941. var combinedParams = [node];
  942. if (extraCallbackParamsArray)
  943. ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
  944. ko.memoization.unmemoize(memos[i].memoId, combinedParams);
  945. node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
  946. if (node.parentNode)
  947. 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)
  948. }
  949. },
  950. parseMemoText: function (memoText) {
  951. var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
  952. return match ? match[1] : null;
  953. }
  954. };
  955. })();
  956. ko.exportSymbol('memoization', ko.memoization);
  957. ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
  958. ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
  959. ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
  960. ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
  961. ko.tasks = (function () {
  962. var scheduler,
  963. taskQueue = [],
  964. taskQueueLength = 0,
  965. nextHandle = 1,
  966. nextIndexToProcess = 0;
  967. if (window['MutationObserver']) {
  968. // Chrome 27+, Firefox 14+, IE 11+, Opera 15+, Safari 6.1+
  969. // From https://github.com/petkaantonov/bluebird * Copyright (c) 2014 Petka Antonov * License: MIT
  970. scheduler = (function (callback) {
  971. var div = document.createElement("div");
  972. new MutationObserver(callback).observe(div, {attributes: true});
  973. return function () { div.classList.toggle("foo"); };
  974. })(scheduledProcess);
  975. } else if (document && "onreadystatechange" in document.createElement("script")) {
  976. // IE 6-10
  977. // From https://github.com/YuzuJS/setImmediate * Copyright (c) 2012 Barnesandnoble.com, llc, Donavon West, and Domenic Denicola * License: MIT
  978. scheduler = function (callback) {
  979. var script = document.createElement("script");
  980. script.onreadystatechange = function () {
  981. script.onreadystatechange = null;
  982. document.documentElement.removeChild(script);
  983. script = null;
  984. callback();
  985. };
  986. document.documentElement.appendChild(script);
  987. };
  988. } else {
  989. scheduler = function (callback) {
  990. setTimeout(callback, 0);
  991. };
  992. }
  993. function processTasks() {
  994. if (taskQueueLength) {
  995. // Each mark represents the end of a logical group of tasks and the number of these groups is
  996. // limited to prevent unchecked recursion.
  997. var mark = taskQueueLength, countMarks = 0;
  998. // nextIndexToProcess keeps track of where we are in the queue; processTasks can be called recursively without issue
  999. for (var task; nextIndexToProcess < taskQueueLength; ) {
  1000. if (task = taskQueue[nextIndexToProcess++]) {
  1001. if (nextIndexToProcess > mark) {
  1002. if (++countMarks >= 5000) {
  1003. nextIndexToProcess = taskQueueLength; // skip all tasks remaining in the queue since any of them could be causing the recursion
  1004. ko.utils.deferError(Error("'Too much recursion' after processing " + countMarks + " task groups."));
  1005. break;
  1006. }
  1007. mark = taskQueueLength;
  1008. }
  1009. try {
  1010. task();
  1011. } catch (ex) {
  1012. ko.utils.deferError(ex);
  1013. }
  1014. }
  1015. }
  1016. }
  1017. }
  1018. function scheduledProcess() {
  1019. processTasks();
  1020. // Reset the queue
  1021. nextIndexToProcess = taskQueueLength = taskQueue.length = 0;
  1022. }
  1023. function scheduleTaskProcessing() {
  1024. ko.tasks['scheduler'](scheduledProcess);
  1025. }
  1026. var tasks = {
  1027. 'scheduler': scheduler, // Allow overriding the scheduler
  1028. schedule: function (func) {
  1029. if (!taskQueueLength) {
  1030. scheduleTaskProcessing();
  1031. }
  1032. taskQueue[taskQueueLength++] = func;
  1033. return nextHandle++;
  1034. },
  1035. cancel: function (handle) {
  1036. var index = handle - (nextHandle - taskQueueLength);
  1037. if (index >= nextIndexToProcess && index < taskQueueLength) {
  1038. taskQueue[index] = null;
  1039. }
  1040. },
  1041. // For testing only: reset the queue and return the previous queue length
  1042. 'resetForTesting': function () {
  1043. var length = taskQueueLength - nextIndexToProcess;
  1044. nextIndexToProcess = taskQueueLength = taskQueue.length = 0;
  1045. return length;
  1046. },
  1047. runEarly: processTasks
  1048. };
  1049. return tasks;
  1050. })();
  1051. ko.exportSymbol('tasks', ko.tasks);
  1052. ko.exportSymbol('tasks.schedule', ko.tasks.schedule);
  1053. //ko.exportSymbol('tasks.cancel', ko.tasks.cancel); "cancel" isn't minified
  1054. ko.exportSymbol('tasks.runEarly', ko.tasks.runEarly);
  1055. ko.extenders = {
  1056. 'throttle': function(target, timeout) {
  1057. // Throttling means two things:
  1058. // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
  1059. // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
  1060. target['throttleEvaluation'] = timeout;
  1061. // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
  1062. // so the target cannot change value synchronously or faster than a certain rate
  1063. var writeTimeoutInstance = null;
  1064. return ko.dependentObservable({
  1065. 'read': target,
  1066. 'write': function(value) {
  1067. clearTimeout(writeTimeoutInstance);
  1068. writeTimeoutInstance = ko.utils.setTimeout(function() {
  1069. target(value);
  1070. }, timeout);
  1071. }
  1072. });
  1073. },
  1074. 'rateLimit': function(target, options) {
  1075. var timeout, method, limitFunction;
  1076. if (typeof options == 'number') {
  1077. timeout = options;
  1078. } else {
  1079. timeout = options['timeout'];
  1080. method = options['method'];
  1081. }
  1082. // rateLimit supersedes deferred updates
  1083. target._deferUpdates = false;
  1084. limitFunction = typeof method == 'function' ? method : method == 'notifyWhenChangesStop' ? debounce : throttle;
  1085. target.limit(function(callback) {
  1086. return limitFunction(callback, timeout, options);
  1087. });
  1088. },
  1089. 'deferred': function(target, options) {
  1090. if (options !== true) {
  1091. throw new Error('The \'deferred\' extender only accepts the value \'true\', because it is not supported to turn deferral off once enabled.')
  1092. }
  1093. if (!target._deferUpdates) {
  1094. target._deferUpdates = true;
  1095. target.limit(function (callback) {
  1096. var handle,
  1097. ignoreUpdates = false;
  1098. return function () {
  1099. if (!ignoreUpdates) {
  1100. ko.tasks.cancel(handle);
  1101. handle = ko.tasks.schedule(callback);
  1102. try {
  1103. ignoreUpdates = true;
  1104. target['notifySubscribers'](undefined, 'dirty');
  1105. } finally {
  1106. ignoreUpdates = false;
  1107. }
  1108. }
  1109. };
  1110. });
  1111. }
  1112. },
  1113. 'notify': function(target, notifyWhen) {
  1114. target["equalityComparer"] = notifyWhen == "always" ?
  1115. null : // null equalityComparer means to always notify
  1116. valuesArePrimitiveAndEqual;
  1117. }
  1118. };
  1119. var primitiveTypes = { 'undefined':1, 'boolean':1, 'number':1, 'string':1 };
  1120. function valuesArePrimitiveAndEqual(a, b) {
  1121. var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
  1122. return oldValueIsPrimitive ? (a === b) : false;
  1123. }
  1124. function throttle(callback, timeout) {
  1125. var timeoutInstance;
  1126. return function () {
  1127. if (!timeoutInstance) {
  1128. timeoutInstance = ko.utils.setTimeout(function () {
  1129. timeoutInstance = undefined;
  1130. callback();
  1131. }, timeout);
  1132. }
  1133. };
  1134. }
  1135. function debounce(callback, timeout) {
  1136. var timeoutInstance;
  1137. return function () {
  1138. clearTimeout(timeoutInstance);
  1139. timeoutInstance = ko.utils.setTimeout(callback, timeout);
  1140. };
  1141. }
  1142. function applyExtenders(requestedExtenders) {
  1143. var target = this;
  1144. if (requestedExtenders) {
  1145. ko.utils.objectForEach(requestedExtenders, function(key, value) {
  1146. var extenderHandler = ko.extenders[key];
  1147. if (typeof extenderHandler == 'function') {
  1148. target = extenderHandler(target, value) || target;
  1149. }
  1150. });
  1151. }
  1152. return target;
  1153. }
  1154. ko.exportSymbol('extenders', ko.extenders);
  1155. ko.subscription = function (target, callback, disposeCallback) {
  1156. this._target = target;
  1157. this._callback = callback;
  1158. this._disposeCallback = disposeCallback;
  1159. this._isDisposed = false;
  1160. this._node = null;
  1161. this._domNodeDisposalCallback = null;
  1162. ko.exportProperty(this, 'dispose', this.dispose);
  1163. ko.exportProperty(this, 'disposeWhenNodeIsRemoved', this.disposeWhenNodeIsRemoved);
  1164. };
  1165. ko.subscription.prototype.dispose = function () {
  1166. var self = this;
  1167. if (!self._isDisposed) {
  1168. if (self._domNodeDisposalCallback) {
  1169. ko.utils.domNodeDisposal.removeDisposeCallback(self._node, self._domNodeDisposalCallback);
  1170. }
  1171. self._isDisposed = true;
  1172. self._disposeCallback();
  1173. self._target = self._callback = self._disposeCallback = self._node = self._domNodeDisposalCallback = null;
  1174. }
  1175. };
  1176. ko.subscription.prototype.disposeWhenNodeIsRemoved = function (node) {
  1177. this._node = node;
  1178. ko.utils.domNodeDisposal.addDisposeCallback(node, this._domNodeDisposalCallback = this.dispose.bind(this));
  1179. };
  1180. ko.subscribable = function () {
  1181. ko.utils.setPrototypeOfOrExtend(this, ko_subscribable_fn);
  1182. ko_subscribable_fn.init(this);
  1183. }
  1184. var defaultEvent = "change";
  1185. // Moved out of "limit" to avoid the extra closure
  1186. function limitNotifySubscribers(value, event) {
  1187. if (!event || event === defaultEvent) {
  1188. this._limitChange(value);
  1189. } else if (event === 'beforeChange') {
  1190. this._limitBeforeChange(value);
  1191. } else {
  1192. this._origNotifySubscribers(value, event);
  1193. }
  1194. }
  1195. var ko_subscribable_fn = {
  1196. init: function(instance) {
  1197. instance._subscriptions = { "change": [] };
  1198. instance._versionNumber = 1;
  1199. },
  1200. subscribe: function (callback, callbackTarget, event) {
  1201. var self = this;
  1202. event = event || defaultEvent;
  1203. var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
  1204. var subscription = new ko.subscription(self, boundCallback, function () {
  1205. ko.utils.arrayRemoveItem(self._subscriptions[event], subscription);
  1206. if (self.afterSubscriptionRemove)
  1207. self.afterSubscriptionRemove(event);
  1208. });
  1209. if (self.beforeSubscriptionAdd)
  1210. self.beforeSubscriptionAdd(event);
  1211. if (!self._subscriptions[event])
  1212. self._subscriptions[event] = [];
  1213. self._subscriptions[event].push(subscription);
  1214. return subscription;
  1215. },
  1216. "notifySubscribers": function (valueToNotify, event) {
  1217. event = event || defaultEvent;
  1218. if (event === defaultEvent) {
  1219. this.updateVersion();
  1220. }
  1221. if (this.hasSubscriptionsForEvent(event)) {
  1222. var subs = event === defaultEvent && this._changeSubscriptions || this._subscriptions[event].slice(0);
  1223. try {
  1224. ko.dependencyDetection.begin(); // Begin suppressing dependency detection (by setting the top frame to undefined)
  1225. for (var i = 0, subscription; subscription = subs[i]; ++i) {
  1226. // In case a subscription was disposed during the arrayForEach cycle, check
  1227. // for isDisposed on each subscription before invoking its callback
  1228. if (!subscription._isDisposed)
  1229. subscription._callback(valueToNotify);
  1230. }
  1231. } finally {
  1232. ko.dependencyDetection.end(); // End suppressing dependency detection
  1233. }
  1234. }
  1235. },
  1236. getVersion: function () {
  1237. return this._versionNumber;
  1238. },
  1239. hasChanged: function (versionToCheck) {
  1240. return this.getVersion() !== versionToCheck;
  1241. },
  1242. updateVersion: function () {
  1243. ++this._versionNumber;
  1244. },
  1245. limit: function(limitFunction) {
  1246. var self = this, selfIsObservable = ko.isObservable(self),
  1247. ignoreBeforeChange, notifyNextChange, previousValue, pendingValue, didUpdate,
  1248. beforeChange = 'beforeChange';
  1249. if (!self._origNotifySubscribers) {
  1250. self._origNotifySubscribers = self["notifySubscribers"];
  1251. self["notifySubscribers"] = limitNotifySubscribers;
  1252. }
  1253. var finish = limitFunction(function() {
  1254. self._notificationIsPending = false;
  1255. // If an observable provided a reference to itself, access it to get the latest value.
  1256. // This allows computed observables to delay calculating their value until needed.
  1257. if (selfIsObservable && pendingValue === self) {
  1258. pendingValue = self._evalIfChanged ? self._evalIfChanged() : self();
  1259. }
  1260. var shouldNotify = notifyNextChange || (didUpdate && self.isDifferent(previousValue, pendingValue));
  1261. didUpdate = notifyNextChange = ignoreBeforeChange = false;
  1262. if (shouldNotify) {
  1263. self._origNotifySubscribers(previousValue = pendingValue);
  1264. }
  1265. });
  1266. self._limitChange = function(value, isDirty) {
  1267. if (!isDirty || !self._notificationIsPending) {
  1268. didUpdate = !isDirty;
  1269. }
  1270. self._changeSubscriptions = self._subscriptions[defaultEvent].slice(0);
  1271. self._notificationIsPending = ignoreBeforeChange = true;
  1272. pendingValue = value;
  1273. finish();
  1274. };
  1275. self._limitBeforeChange = function(value) {
  1276. if (!ignoreBeforeChange) {
  1277. previousValue = value;
  1278. self._origNotifySubscribers(value, beforeChange);
  1279. }
  1280. };
  1281. self._recordUpdate = function() {
  1282. didUpdate = true;
  1283. };
  1284. self._notifyNextChangeIfValueIsDifferent = function() {
  1285. if (self.isDifferent(previousValue, self.peek(true /*evaluate*/))) {
  1286. notifyNextChange = true;
  1287. }
  1288. };
  1289. },
  1290. hasSubscriptionsForEvent: function(event) {
  1291. return this._subscriptions[event] && this._subscriptions[event].length;
  1292. },
  1293. getSubscriptionsCount: function (event) {
  1294. if (event) {
  1295. return this._subscriptions[event] && this._subscriptions[event].length || 0;
  1296. } else {
  1297. var total = 0;
  1298. ko.utils.objectForEach(this._subscriptions, function(eventName, subscriptions) {
  1299. if (eventName !== 'dirty')
  1300. total += subscriptions.length;
  1301. });
  1302. return total;
  1303. }
  1304. },
  1305. isDifferent: function(oldValue, newValue) {
  1306. return !this['equalityComparer'] || !this['equalityComparer'](oldValue, newValue);
  1307. },
  1308. toString: function() {
  1309. return '[object Object]'
  1310. },
  1311. extend: applyExtenders
  1312. };
  1313. ko.exportProperty(ko_subscribable_fn, 'init', ko_subscribable_fn.init);
  1314. ko.exportProperty(ko_subscribable_fn, 'subscribe', ko_subscribable_fn.subscribe);
  1315. ko.exportProperty(ko_subscribable_fn, 'extend', ko_subscribable_fn.extend);
  1316. ko.exportProperty(ko_subscribable_fn, 'getSubscriptionsCount', ko_subscribable_fn.getSubscriptionsCount);
  1317. // For browsers that support proto assignment, we overwrite the prototype of each
  1318. // observable instance. Since observables are functions, we need Function.prototype
  1319. // to still be in the prototype chain.
  1320. if (ko.utils.canSetPrototype) {
  1321. ko.utils.setPrototypeOf(ko_subscribable_fn, Function.prototype);
  1322. }
  1323. ko.subscribable['fn'] = ko_subscribable_fn;
  1324. ko.isSubscribable = function (instance) {
  1325. return instance != null && typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
  1326. };
  1327. ko.exportSymbol('subscribable', ko.subscribable);
  1328. ko.exportSymbol('isSubscribable', ko.isSubscribable);
  1329. ko.computedContext = ko.dependencyDetection = (function () {
  1330. var outerFrames = [],
  1331. currentFrame,
  1332. lastId = 0;
  1333. // Return a unique ID that can be assigned to an observable for dependency tracking.
  1334. // Theoretically, you could eventually overflow the number storage size, resulting
  1335. // in duplicate IDs. But in JavaScript, the largest exact integral value is 2^53
  1336. // or 9,007,199,254,740,992. If you created 1,000,000 IDs per second, it would
  1337. // take over 285 years to reach that number.
  1338. // Reference http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html
  1339. function getId() {
  1340. return ++lastId;
  1341. }
  1342. function begin(options) {
  1343. outerFrames.push(currentFrame);
  1344. currentFrame = options;
  1345. }
  1346. function end() {
  1347. currentFrame = outerFrames.pop();
  1348. }
  1349. return {
  1350. begin: begin,
  1351. end: end,
  1352. registerDependency: function (subscribable) {
  1353. if (currentFrame) {
  1354. if (!ko.isSubscribable(subscribable))
  1355. throw new Error("Only subscribable things can act as dependencies");
  1356. currentFrame.callback.call(currentFrame.callbackTarget, subscribable, subscribable._id || (subscribable._id = getId()));
  1357. }
  1358. },
  1359. ignore: function (callback, callbackTarget, callbackArgs) {
  1360. try {
  1361. begin();
  1362. return callback.apply(callbackTarget, callbackArgs || []);
  1363. } finally {
  1364. end();
  1365. }
  1366. },
  1367. getDependenciesCount: function () {
  1368. if (currentFrame)
  1369. return currentFrame.computed.getDependenciesCount();
  1370. },
  1371. getDependencies: function () {
  1372. if (currentFrame)
  1373. return currentFrame.computed.getDependencies();
  1374. },
  1375. isInitial: function() {
  1376. if (currentFrame)
  1377. return currentFrame.isInitial;
  1378. },
  1379. computed: function() {
  1380. if (currentFrame)
  1381. return currentFrame.computed;
  1382. }
  1383. };
  1384. })();
  1385. ko.exportSymbol('computedContext', ko.computedContext);
  1386. ko.exportSymbol('computedContext.getDependenciesCount', ko.computedContext.getDependenciesCount);
  1387. ko.exportSymbol('computedContext.getDependencies', ko.computedContext.getDependencies);
  1388. ko.exportSymbol('computedContext.isInitial', ko.computedContext.isInitial);
  1389. ko.exportSymbol('computedContext.registerDependency', ko.computedContext.registerDependency);
  1390. ko.exportSymbol('ignoreDependencies', ko.ignoreDependencies = ko.dependencyDetection.ignore);
  1391. var observableLatestValue = ko.utils.createSymbolOrString('_latestValue');
  1392. ko.observable = function (initialValue) {
  1393. function observable() {
  1394. if (arguments.length > 0) {
  1395. // Write
  1396. // Ignore writes if the value hasn't changed
  1397. if (observable.isDifferent(observable[observableLatestValue], arguments[0])) {
  1398. observable.valueWillMutate();
  1399. observable[observableLatestValue] = arguments[0];
  1400. observable.valueHasMutated();
  1401. }
  1402. return this; // Permits chained assignments
  1403. }
  1404. else {
  1405. // Read
  1406. ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
  1407. return observable[observableLatestValue];
  1408. }
  1409. }
  1410. observable[observableLatestValue] = initialValue;
  1411. // Inherit from 'subscribable'
  1412. if (!ko.utils.canSetPrototype) {
  1413. // 'subscribable' won't be on the prototype chain unless we put it there directly
  1414. ko.utils.extend(observable, ko.subscribable['fn']);
  1415. }
  1416. ko.subscribable['fn'].init(observable);
  1417. // Inherit from 'observable'
  1418. ko.utils.setPrototypeOfOrExtend(observable, observableFn);
  1419. if (ko.options['deferUpdates']) {
  1420. ko.extenders['deferred'](observable, true);
  1421. }
  1422. return observable;
  1423. }
  1424. // Define prototype for observables
  1425. var observableFn = {
  1426. 'equalityComparer': valuesArePrimitiveAndEqual,
  1427. peek: function() { return this[observableLatestValue]; },
  1428. valueHasMutated: function () {
  1429. this['notifySubscribers'](this[observableLatestValue], 'spectate');
  1430. this['notifySubscribers'](this[observableLatestValue]);
  1431. },
  1432. valueWillMutate: function () { this['notifySubscribers'](this[observableLatestValue], 'beforeChange'); }
  1433. };
  1434. // Note that for browsers that don't support proto assignment, the
  1435. // inheritance chain is created manually in the ko.observable constructor
  1436. if (ko.utils.canSetPrototype) {
  1437. ko.utils.setPrototypeOf(observableFn, ko.subscribable['fn']);
  1438. }
  1439. var protoProperty = ko.observable.protoProperty = '__ko_proto__';
  1440. observableFn[protoProperty] = ko.observable;
  1441. ko.isObservable = function (instance) {
  1442. var proto = typeof instance == 'function' && instance[protoProperty];
  1443. if (proto && proto !== observableFn[protoProperty] && proto !== ko.computed['fn'][protoProperty]) {
  1444. throw Error("Invalid object that looks like an observable; possibly from another Knockout instance");
  1445. }
  1446. return !!proto;
  1447. };
  1448. ko.isWriteableObservable = function (instance) {
  1449. return (typeof instance == 'function' && (
  1450. (instance[protoProperty] === observableFn[protoProperty]) || // Observable
  1451. (instance[protoProperty] === ko.computed['fn'][protoProperty] && instance.hasWriteFunction))); // Writable computed observable
  1452. };
  1453. ko.exportSymbol('observable', ko.observable);
  1454. ko.exportSymbol('isObservable', ko.isObservable);
  1455. ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
  1456. ko.exportSymbol('isWritableObservable', ko.isWriteableObservable);
  1457. ko.exportSymbol('observable.fn', observableFn);
  1458. ko.exportProperty(observableFn, 'peek', observableFn.peek);
  1459. ko.exportProperty(observableFn, 'valueHasMutated', observableFn.valueHasMutated);
  1460. ko.exportProperty(observableFn, 'valueWillMutate', observableFn.valueWillMutate);
  1461. ko.observableArray = function (initialValues) {
  1462. initialValues = initialValues || [];
  1463. if (typeof initialValues != 'object' || !('length' in initialValues))
  1464. throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
  1465. var result = ko.observable(initialValues);
  1466. ko.utils.setPrototypeOfOrExtend(result, ko.observableArray['fn']);
  1467. return result.extend({'trackArrayChanges':true});
  1468. };
  1469. ko.observableArray['fn'] = {
  1470. 'remove': function (valueOrPredicate) {
  1471. var underlyingArray = this.peek();
  1472. var removedValues = [];
  1473. var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
  1474. for (var i = 0; i < underlyingArray.length; i++) {
  1475. var value = underlyingArray[i];
  1476. if (predicate(value)) {
  1477. if (removedValues.length === 0) {
  1478. this.valueWillMutate();
  1479. }
  1480. if (underlyingArray[i] !== value) {
  1481. throw Error("Array modified during remove; cannot remove item");
  1482. }
  1483. removedValues.push(value);
  1484. underlyingArray.splice(i, 1);
  1485. i--;
  1486. }
  1487. }
  1488. if (removedValues.length) {
  1489. this.valueHasMutated();
  1490. }
  1491. return removedValues;
  1492. },
  1493. 'removeAll': function (arrayOfValues) {
  1494. // If you passed zero args, we remove everything
  1495. if (arrayOfValues === undefined) {
  1496. var underlyingArray = this.peek();
  1497. var allValues = underlyingArray.slice(0);
  1498. this.valueWillMutate();
  1499. underlyingArray.splice(0, underlyingArray.length);
  1500. this.valueHasMutated();
  1501. return allValues;
  1502. }
  1503. // If you passed an arg, we interpret it as an array of entries to remove
  1504. if (!arrayOfValues)
  1505. return [];
  1506. return this['remove'](function (value) {
  1507. return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
  1508. });
  1509. },
  1510. 'destroy': function (valueOrPredicate) {
  1511. var underlyingArray = this.peek();
  1512. var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
  1513. this.valueWillMutate();
  1514. for (var i = underlyingArray.length - 1; i >= 0; i--) {
  1515. var value = underlyingArray[i];
  1516. if (predicate(value))
  1517. value["_destroy"] = true;
  1518. }
  1519. this.valueHasMutated();
  1520. },
  1521. 'destroyAll': function (arrayOfValues) {
  1522. // If you passed zero args, we destroy everything
  1523. if (arrayOfValues === undefined)
  1524. return this['destroy'](function() { return true });
  1525. // If you passed an arg, we interpret it as an array of entries to destroy
  1526. if (!arrayOfValues)
  1527. return [];
  1528. return this['destroy'](function (value) {
  1529. return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
  1530. });
  1531. },
  1532. 'indexOf': function (item) {
  1533. var underlyingArray = this();
  1534. return ko.utils.arrayIndexOf(underlyingArray, item);
  1535. },
  1536. 'replace': function(oldItem, newItem) {
  1537. var index = this['indexOf'](oldItem);
  1538. if (index >= 0) {
  1539. this.valueWillMutate();
  1540. this.peek()[index] = newItem;
  1541. this.valueHasMutated();
  1542. }
  1543. },
  1544. 'sorted': function (compareFunction) {
  1545. var arrayCopy = this().slice(0);
  1546. return compareFunction ? arrayCopy.sort(compareFunction) : arrayCopy.sort();
  1547. },
  1548. 'reversed': function () {
  1549. return this().slice(0).reverse();
  1550. }
  1551. };
  1552. // Note that for browsers that don't support proto assignment, the
  1553. // inheritance chain is created manually in the ko.observableArray constructor
  1554. if (ko.utils.canSetPrototype) {
  1555. ko.utils.setPrototypeOf(ko.observableArray['fn'], ko.observable['fn']);
  1556. }
  1557. // Populate ko.observableArray.fn with read/write functions from native arrays
  1558. // Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
  1559. // because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
  1560. ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
  1561. ko.observableArray['fn'][methodName] = function () {
  1562. // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
  1563. // (for consistency with mutating regular observables)
  1564. var underlyingArray = this.peek();
  1565. this.valueWillMutate();
  1566. this.cacheDiffForKnownOperation(underlyingArray, methodName, arguments);
  1567. var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
  1568. this.valueHasMutated();
  1569. // The native sort and reverse methods return a reference to the array, but it makes more sense to return the observable array instead.
  1570. return methodCallResult === underlyingArray ? this : methodCallResult;
  1571. };
  1572. });
  1573. // Populate ko.observableArray.fn with read-only functions from native arrays
  1574. ko.utils.arrayForEach(["slice"], function (methodName) {
  1575. ko.observableArray['fn'][methodName] = function () {
  1576. var underlyingArray = this();
  1577. return underlyingArray[methodName].apply(underlyingArray, arguments);
  1578. };
  1579. });
  1580. ko.isObservableArray = function (instance) {
  1581. return ko.isObservable(instance)
  1582. && typeof instance["remove"] == "function"
  1583. && typeof instance["push"] == "function";
  1584. };
  1585. ko.exportSymbol('observableArray', ko.observableArray);
  1586. ko.exportSymbol('isObservableArray', ko.isObservableArray);
  1587. var arrayChangeEventName = 'arrayChange';
  1588. ko.extenders['trackArrayChanges'] = function(target, options) {
  1589. // Use the provided options--each call to trackArrayChanges overwrites the previously set options
  1590. target.compareArrayOptions = {};
  1591. if (options && typeof options == "object") {
  1592. ko.utils.extend(target.compareArrayOptions, options);
  1593. }
  1594. target.compareArrayOptions['sparse'] = true;
  1595. // Only modify the target observable once
  1596. if (target.cacheDiffForKnownOperation) {
  1597. return;
  1598. }
  1599. var trackingChanges = false,
  1600. cachedDiff = null,
  1601. changeSubscription,
  1602. spectateSubscription,
  1603. pendingChanges = 0,
  1604. previousContents,
  1605. underlyingBeforeSubscriptionAddFunction = target.beforeSubscriptionAdd,
  1606. underlyingAfterSubscriptionRemoveFunction = target.afterSubscriptionRemove;
  1607. // Watch "subscribe" calls, and for array change events, ensure change tracking is enabled
  1608. target.beforeSubscriptionAdd = function (event) {
  1609. if (underlyingBeforeSubscriptionAddFunction) {
  1610. underlyingBeforeSubscriptionAddFunction.call(target, event);
  1611. }
  1612. if (event === arrayChangeEventName) {
  1613. trackChanges();
  1614. }
  1615. };
  1616. // Watch "dispose" calls, and for array change events, ensure change tracking is disabled when all are disposed
  1617. target.afterSubscriptionRemove = function (event) {
  1618. if (underlyingAfterSubscriptionRemoveFunction) {
  1619. underlyingAfterSubscriptionRemoveFunction.call(target, event);
  1620. }
  1621. if (event === arrayChangeEventName && !target.hasSubscriptionsForEvent(arrayChangeEventName)) {
  1622. if (changeSubscription) {
  1623. changeSubscription.dispose();
  1624. }
  1625. if (spectateSubscription) {
  1626. spectateSubscription.dispose();
  1627. }
  1628. spectateSubscription = changeSubscription = null;
  1629. trackingChanges = false;
  1630. previousContents = undefined;
  1631. }
  1632. };
  1633. function trackChanges() {
  1634. if (trackingChanges) {
  1635. // Whenever there's a new subscription and there are pending notifications, make sure all previous
  1636. // subscriptions are notified of the change so that all subscriptions are in sync.
  1637. notifyChanges();
  1638. return;
  1639. }
  1640. trackingChanges = true;
  1641. // Track how many times the array actually changed value
  1642. spectateSubscription = target.subscribe(function () {
  1643. ++pendingChanges;
  1644. }, null, "spectate");
  1645. // Each time the array changes value, capture a clone so that on the next
  1646. // change it's possible to produce a diff
  1647. previousContents = [].concat(target.peek() || []);
  1648. cachedDiff = null;
  1649. changeSubscription = target.subscribe(notifyChanges);
  1650. function notifyChanges() {
  1651. if (pendingChanges) {
  1652. // Make a copy of the current contents and ensure it's an array
  1653. var currentContents = [].concat(target.peek() || []), changes;
  1654. // Compute the diff and issue notifications, but only if someone is listening
  1655. if (target.hasSubscriptionsForEvent(arrayChangeEventName)) {
  1656. changes = getChanges(previousContents, currentContents);
  1657. }
  1658. // Eliminate references to the old, removed items, so they can be GCed
  1659. previousContents = currentContents;
  1660. cachedDiff = null;
  1661. pendingChanges = 0;
  1662. if (changes && changes.length) {
  1663. target['notifySubscribers'](changes, arrayChangeEventName);
  1664. }
  1665. }
  1666. }
  1667. }
  1668. function getChanges(previousContents, currentContents) {
  1669. // We try to re-use cached diffs.
  1670. // The scenarios where pendingChanges > 1 are when using rate limiting or deferred updates,
  1671. // which without this check would not be compatible with arrayChange notifications. Normally,
  1672. // notifications are issued immediately so we wouldn't be queueing up more than one.
  1673. if (!cachedDiff || pendingChanges > 1) {
  1674. cachedDiff = ko.utils.compareArrays(previousContents, currentContents, target.compareArrayOptions);
  1675. }
  1676. return cachedDiff;
  1677. }
  1678. target.cacheDiffForKnownOperation = function(rawArray, operationName, args) {
  1679. // Only run if we're currently tracking changes for this observable array
  1680. // and there aren't any pending deferred notifications.
  1681. if (!trackingChanges || pendingChanges) {
  1682. return;
  1683. }
  1684. var diff = [],
  1685. arrayLength = rawArray.length,
  1686. argsLength = args.length,
  1687. offset = 0;
  1688. function pushDiff(status, value, index) {
  1689. return diff[diff.length] = { 'status': status, 'value': value, 'index': index };
  1690. }
  1691. switch (operationName) {
  1692. case 'push':
  1693. offset = arrayLength;
  1694. case 'unshift':
  1695. for (var index = 0; index < argsLength; index++) {
  1696. pushDiff('added', args[index], offset + index);
  1697. }
  1698. break;
  1699. case 'pop':
  1700. offset = arrayLength - 1;
  1701. case 'shift':
  1702. if (arrayLength) {
  1703. pushDiff('deleted', rawArray[offset], offset);
  1704. }
  1705. break;
  1706. case 'splice':
  1707. // Negative start index means 'from end of array'. After that we clamp to [0...arrayLength].
  1708. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
  1709. var startIndex = Math.min(Math.max(0, args[0] < 0 ? arrayLength + args[0] : args[0]), arrayLength),
  1710. endDeleteIndex = argsLength === 1 ? arrayLength : Math.min(startIndex + (args[1] || 0), arrayLength),
  1711. endAddIndex = startIndex + argsLength - 2,
  1712. endIndex = Math.max(endDeleteIndex, endAddIndex),
  1713. additions = [], deletions = [];
  1714. for (var index = startIndex, argsIndex = 2; index < endIndex; ++index, ++argsIndex) {
  1715. if (index < endDeleteIndex)
  1716. deletions.push(pushDiff('deleted', rawArray[index], index));
  1717. if (index < endAddIndex)
  1718. additions.push(pushDiff('added', args[argsIndex], index));
  1719. }
  1720. ko.utils.findMovesInArrayComparison(deletions, additions);
  1721. break;
  1722. default:
  1723. return;
  1724. }
  1725. cachedDiff = diff;
  1726. };
  1727. };
  1728. var computedState = ko.utils.createSymbolOrString('_state');
  1729. ko.computed = ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
  1730. if (typeof evaluatorFunctionOrOptions === "object") {
  1731. // Single-parameter syntax - everything is on this "options" param
  1732. options = evaluatorFunctionOrOptions;
  1733. } else {
  1734. // Multi-parameter syntax - construct the options according to the params passed
  1735. options = options || {};
  1736. if (evaluatorFunctionOrOptions) {
  1737. options["read"] = evaluatorFunctionOrOptions;
  1738. }
  1739. }
  1740. if (typeof options["read"] != "function")
  1741. throw Error("Pass a function that returns the value of the ko.computed");
  1742. var writeFunction = options["write"];
  1743. var state = {
  1744. latestValue: undefined,
  1745. isStale: true,
  1746. isDirty: true,
  1747. isBeingEvaluated: false,
  1748. suppressDisposalUntilDisposeWhenReturnsFalse: false,
  1749. isDisposed: false,
  1750. pure: false,
  1751. isSleeping: false,
  1752. readFunction: options["read"],
  1753. evaluatorFunctionTarget: evaluatorFunctionTarget || options["owner"],
  1754. disposeWhenNodeIsRemoved: options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
  1755. disposeWhen: options["disposeWhen"] || options.disposeWhen,
  1756. domNodeDisposalCallback: null,
  1757. dependencyTracking: {},
  1758. dependenciesCount: 0,
  1759. evaluationTimeoutInstance: null
  1760. };
  1761. function computedObservable() {
  1762. if (arguments.length > 0) {
  1763. if (typeof writeFunction === "function") {
  1764. // Writing a value
  1765. writeFunction.apply(state.evaluatorFunctionTarget, arguments);
  1766. } else {
  1767. 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.");
  1768. }
  1769. return this; // Permits chained assignments
  1770. } else {
  1771. // Reading the value
  1772. if (!state.isDisposed) {
  1773. ko.dependencyDetection.registerDependency(computedObservable);
  1774. }
  1775. if (state.isDirty || (state.isSleeping && computedObservable.haveDependenciesChanged())) {
  1776. computedObservable.evaluateImmediate();
  1777. }
  1778. return state.latestValue;
  1779. }
  1780. }
  1781. computedObservable[computedState] = state;
  1782. computedObservable.hasWriteFunction = typeof writeFunction === "function";
  1783. // Inherit from 'subscribable'
  1784. if (!ko.utils.canSetPrototype) {
  1785. // 'subscribable' won't be on the prototype chain unless we put it there directly
  1786. ko.utils.extend(computedObservable, ko.subscribable['fn']);
  1787. }
  1788. ko.subscribable['fn'].init(computedObservable);
  1789. // Inherit from 'computed'
  1790. ko.utils.setPrototypeOfOrExtend(computedObservable, computedFn);
  1791. if (options['pure']) {
  1792. state.pure = true;
  1793. state.isSleeping = true; // Starts off sleeping; will awake on the first subscription
  1794. ko.utils.extend(computedObservable, pureComputedOverrides);
  1795. } else if (options['deferEvaluation']) {
  1796. ko.utils.extend(computedObservable, deferEvaluationOverrides);
  1797. }
  1798. if (ko.options['deferUpdates']) {
  1799. ko.extenders['deferred'](computedObservable, true);
  1800. }
  1801. if (DEBUG) {
  1802. // #1731 - Aid debugging by exposing the computed's options
  1803. computedObservable["_options"] = options;
  1804. }
  1805. if (state.disposeWhenNodeIsRemoved) {
  1806. // Since this computed is associated with a DOM node, and we don't want to dispose the computed
  1807. // until the DOM node is *removed* from the document (as opposed to never having been in the document),
  1808. // we'll prevent disposal until "disposeWhen" first returns false.
  1809. state.suppressDisposalUntilDisposeWhenReturnsFalse = true;
  1810. // disposeWhenNodeIsRemoved: true can be used to opt into the "only dispose after first false result"
  1811. // behaviour even if there's no specific node to watch. In that case, clear the option so we don't try
  1812. // to watch for a non-node's disposal. This technique is intended for KO's internal use only and shouldn't
  1813. // be documented or used by application code, as it's likely to change in a future version of KO.
  1814. if (!state.disposeWhenNodeIsRemoved.nodeType) {
  1815. state.disposeWhenNodeIsRemoved = null;
  1816. }
  1817. }
  1818. // Evaluate, unless sleeping or deferEvaluation is true
  1819. if (!state.isSleeping && !options['deferEvaluation']) {
  1820. computedObservable.evaluateImmediate();
  1821. }
  1822. // Attach a DOM node disposal callback so that the computed will be proactively disposed as soon as the node is
  1823. // removed using ko.removeNode. But skip if isActive is false (there will never be any dependencies to dispose).
  1824. if (state.disposeWhenNodeIsRemoved && computedObservable.isActive()) {
  1825. ko.utils.domNodeDisposal.addDisposeCallback(state.disposeWhenNodeIsRemoved, state.domNodeDisposalCallback = function () {
  1826. computedObservable.dispose();
  1827. });
  1828. }
  1829. return computedObservable;
  1830. };
  1831. // Utility function that disposes a given dependencyTracking entry
  1832. function computedDisposeDependencyCallback(id, entryToDispose) {
  1833. if (entryToDispose !== null && entryToDispose.dispose) {
  1834. entryToDispose.dispose();
  1835. }
  1836. }
  1837. // This function gets called each time a dependency is detected while evaluating a computed.
  1838. // It's factored out as a shared function to avoid creating unnecessary function instances during evaluation.
  1839. function computedBeginDependencyDetectionCallback(subscribable, id) {
  1840. var computedObservable = this.computedObservable,
  1841. state = computedObservable[computedState];
  1842. if (!state.isDisposed) {
  1843. if (this.disposalCount && this.disposalCandidates[id]) {
  1844. // Don't want to dispose this subscription, as it's still being used
  1845. computedObservable.addDependencyTracking(id, subscribable, this.disposalCandidates[id]);
  1846. this.disposalCandidates[id] = null; // No need to actually delete the property - disposalCandidates is a transient object anyway
  1847. --this.disposalCount;
  1848. } else if (!state.dependencyTracking[id]) {
  1849. // Brand new subscription - add it
  1850. computedObservable.addDependencyTracking(id, subscribable, state.isSleeping ? { _target: subscribable } : computedObservable.subscribeToDependency(subscribable));
  1851. }
  1852. // If the observable we've accessed has a pending notification, ensure we get notified of the actual final value (bypass equality checks)
  1853. if (subscribable._notificationIsPending) {
  1854. subscribable._notifyNextChangeIfValueIsDifferent();
  1855. }
  1856. }
  1857. }
  1858. var computedFn = {
  1859. "equalityComparer": valuesArePrimitiveAndEqual,
  1860. getDependenciesCount: function () {
  1861. return this[computedState].dependenciesCount;
  1862. },
  1863. getDependencies: function () {
  1864. var dependencyTracking = this[computedState].dependencyTracking, dependentObservables = [];
  1865. ko.utils.objectForEach(dependencyTracking, function (id, dependency) {
  1866. dependentObservables[dependency._order] = dependency._target;
  1867. });
  1868. return dependentObservables;
  1869. },
  1870. hasAncestorDependency: function (obs) {
  1871. if (!this[computedState].dependenciesCount) {
  1872. return false;
  1873. }
  1874. var dependencies = this.getDependencies();
  1875. if (ko.utils.arrayIndexOf(dependencies, obs) !== -1) {
  1876. return true;
  1877. }
  1878. return !!ko.utils.arrayFirst(dependencies, function (dep) {
  1879. return dep.hasAncestorDependency && dep.hasAncestorDependency(obs);
  1880. });
  1881. },
  1882. addDependencyTracking: function (id, target, trackingObj) {
  1883. if (this[computedState].pure && target === this) {
  1884. throw Error("A 'pure' computed must not be called recursively");
  1885. }
  1886. this[computedState].dependencyTracking[id] = trackingObj;
  1887. trackingObj._order = this[computedState].dependenciesCount++;
  1888. trackingObj._version = target.getVersion();
  1889. },
  1890. haveDependenciesChanged: function () {
  1891. var id, dependency, dependencyTracking = this[computedState].dependencyTracking;
  1892. for (id in dependencyTracking) {
  1893. if (Object.prototype.hasOwnProperty.call(dependencyTracking, id)) {
  1894. dependency = dependencyTracking[id];
  1895. if ((this._evalDelayed && dependency._target._notificationIsPending) || dependency._target.hasChanged(dependency._version)) {
  1896. return true;
  1897. }
  1898. }
  1899. }
  1900. },
  1901. markDirty: function () {
  1902. // Process "dirty" events if we can handle delayed notifications
  1903. if (this._evalDelayed && !this[computedState].isBeingEvaluated) {
  1904. this._evalDelayed(false /*isChange*/);
  1905. }
  1906. },
  1907. isActive: function () {
  1908. var state = this[computedState];
  1909. return state.isDirty || state.dependenciesCount > 0;
  1910. },
  1911. respondToChange: function () {
  1912. // Ignore "change" events if we've already scheduled a delayed notification
  1913. if (!this._notificationIsPending) {
  1914. this.evaluatePossiblyAsync();
  1915. } else if (this[computedState].isDirty) {
  1916. this[computedState].isStale = true;
  1917. }
  1918. },
  1919. subscribeToDependency: function (target) {
  1920. if (target._deferUpdates) {
  1921. var dirtySub = target.subscribe(this.markDirty, this, 'dirty'),
  1922. changeSub = target.subscribe(this.respondToChange, this);
  1923. return {
  1924. _target: target,
  1925. dispose: function () {
  1926. dirtySub.dispose();
  1927. changeSub.dispose();
  1928. }
  1929. };
  1930. } else {
  1931. return target.subscribe(this.evaluatePossiblyAsync, this);
  1932. }
  1933. },
  1934. evaluatePossiblyAsync: function () {
  1935. var computedObservable = this,
  1936. throttleEvaluationTimeout = computedObservable['throttleEvaluation'];
  1937. if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
  1938. clearTimeout(this[computedState].evaluationTimeoutInstance);
  1939. this[computedState].evaluationTimeoutInstance = ko.utils.setTimeout(function () {
  1940. computedObservable.evaluateImmediate(true /*notifyChange*/);
  1941. }, throttleEvaluationTimeout);
  1942. } else if (computedObservable._evalDelayed) {
  1943. computedObservable._evalDelayed(true /*isChange*/);
  1944. } else {
  1945. computedObservable.evaluateImmediate(true /*notifyChange*/);
  1946. }
  1947. },
  1948. evaluateImmediate: function (notifyChange) {
  1949. var computedObservable = this,
  1950. state = computedObservable[computedState],
  1951. disposeWhen = state.disposeWhen,
  1952. changed = false;
  1953. if (state.isBeingEvaluated) {
  1954. // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
  1955. // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
  1956. // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
  1957. // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
  1958. return;
  1959. }
  1960. // Do not evaluate (and possibly capture new dependencies) if disposed
  1961. if (state.isDisposed) {
  1962. return;
  1963. }
  1964. if (state.disposeWhenNodeIsRemoved && !ko.utils.domNodeIsAttachedToDocument(state.disposeWhenNodeIsRemoved) || disposeWhen && disposeWhen()) {
  1965. // See comment above about suppressDisposalUntilDisposeWhenReturnsFalse
  1966. if (!state.suppressDisposalUntilDisposeWhenReturnsFalse) {
  1967. computedObservable.dispose();
  1968. return;
  1969. }
  1970. } else {
  1971. // It just did return false, so we can stop suppressing now
  1972. state.suppressDisposalUntilDisposeWhenReturnsFalse = false;
  1973. }
  1974. state.isBeingEvaluated = true;
  1975. try {
  1976. changed = this.evaluateImmediate_CallReadWithDependencyDetection(notifyChange);
  1977. } finally {
  1978. state.isBeingEvaluated = false;
  1979. }
  1980. return changed;
  1981. },
  1982. evaluateImmediate_CallReadWithDependencyDetection: function (notifyChange) {
  1983. // This function is really just part of the evaluateImmediate logic. You would never call it from anywhere else.
  1984. // Factoring it out into a separate function means it can be independent of the try/catch block in evaluateImmediate,
  1985. // which contributes to saving about 40% off the CPU overhead of computed evaluation (on V8 at least).
  1986. var computedObservable = this,
  1987. state = computedObservable[computedState],
  1988. changed = false;
  1989. // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
  1990. // Then, during evaluation, we cross off any that are in fact still being used.
  1991. var isInitial = state.pure ? undefined : !state.dependenciesCount, // If we're evaluating when there are no previous dependencies, it must be the first time
  1992. dependencyDetectionContext = {
  1993. computedObservable: computedObservable,
  1994. disposalCandidates: state.dependencyTracking,
  1995. disposalCount: state.dependenciesCount
  1996. };
  1997. ko.dependencyDetection.begin({
  1998. callbackTarget: dependencyDetectionContext,
  1999. callback: computedBeginDependencyDetectionCallback,
  2000. computed: computedObservable,
  2001. isInitial: isInitial
  2002. });
  2003. state.dependencyTracking = {};
  2004. state.dependenciesCount = 0;
  2005. var newValue = this.evaluateImmediate_CallReadThenEndDependencyDetection(state, dependencyDetectionContext);
  2006. if (!state.dependenciesCount) {
  2007. computedObservable.dispose();
  2008. changed = true; // When evaluation causes a disposal, make sure all dependent computeds get notified so they'll see the new state
  2009. } else {
  2010. changed = computedObservable.isDifferent(state.latestValue, newValue);
  2011. }
  2012. if (changed) {
  2013. if (!state.isSleeping) {
  2014. computedObservable["notifySubscribers"](state.latestValue, "beforeChange");
  2015. } else {
  2016. computedObservable.updateVersion();
  2017. }
  2018. state.latestValue = newValue;
  2019. if (DEBUG) computedObservable._latestValue = newValue;
  2020. computedObservable["notifySubscribers"](state.latestValue, "spectate");
  2021. if (!state.isSleeping && notifyChange) {
  2022. computedObservable["notifySubscribers"](state.latestValue);
  2023. }
  2024. if (computedObservable._recordUpdate) {
  2025. computedObservable._recordUpdate();
  2026. }
  2027. }
  2028. if (isInitial) {
  2029. computedObservable["notifySubscribers"](state.latestValue, "awake");
  2030. }
  2031. return changed;
  2032. },
  2033. evaluateImmediate_CallReadThenEndDependencyDetection: function (state, dependencyDetectionContext) {
  2034. // This function is really part of the evaluateImmediate_CallReadWithDependencyDetection logic.
  2035. // You'd never call it from anywhere else. Factoring it out means that evaluateImmediate_CallReadWithDependencyDetection
  2036. // can be independent of try/finally blocks, which contributes to saving about 40% off the CPU
  2037. // overhead of computed evaluation (on V8 at least).
  2038. try {
  2039. var readFunction = state.readFunction;
  2040. return state.evaluatorFunctionTarget ? readFunction.call(state.evaluatorFunctionTarget) : readFunction();
  2041. } finally {
  2042. ko.dependencyDetection.end();
  2043. // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
  2044. if (dependencyDetectionContext.disposalCount && !state.isSleeping) {
  2045. ko.utils.objectForEach(dependencyDetectionContext.disposalCandidates, computedDisposeDependencyCallback);
  2046. }
  2047. state.isStale = state.isDirty = false;
  2048. }
  2049. },
  2050. peek: function (evaluate) {
  2051. // By default, peek won't re-evaluate, except while the computed is sleeping or to get the initial value when "deferEvaluation" is set.
  2052. // Pass in true to evaluate if needed.
  2053. var state = this[computedState];
  2054. if ((state.isDirty && (evaluate || !state.dependenciesCount)) || (state.isSleeping && this.haveDependenciesChanged())) {
  2055. this.evaluateImmediate();
  2056. }
  2057. return state.latestValue;
  2058. },
  2059. limit: function (limitFunction) {
  2060. // Override the limit function with one that delays evaluation as well
  2061. ko.subscribable['fn'].limit.call(this, limitFunction);
  2062. this._evalIfChanged = function () {
  2063. if (!this[computedState].isSleeping) {
  2064. if (this[computedState].isStale) {
  2065. this.evaluateImmediate();
  2066. } else {
  2067. this[computedState].isDirty = false;
  2068. }
  2069. }
  2070. return this[computedState].latestValue;
  2071. };
  2072. this._evalDelayed = function (isChange) {
  2073. this._limitBeforeChange(this[computedState].latestValue);
  2074. // Mark as dirty
  2075. this[computedState].isDirty = true;
  2076. if (isChange) {
  2077. this[computedState].isStale = true;
  2078. }
  2079. // Pass the observable to the "limit" code, which will evaluate it when
  2080. // it's time to do the notification.
  2081. this._limitChange(this, !isChange /* isDirty */);
  2082. };
  2083. },
  2084. dispose: function () {
  2085. var state = this[computedState];
  2086. if (!state.isSleeping && state.dependencyTracking) {
  2087. ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) {
  2088. if (dependency.dispose)
  2089. dependency.dispose();
  2090. });
  2091. }
  2092. if (state.disposeWhenNodeIsRemoved && state.domNodeDisposalCallback) {
  2093. ko.utils.domNodeDisposal.removeDisposeCallback(state.disposeWhenNodeIsRemoved, state.domNodeDisposalCallback);
  2094. }
  2095. state.dependencyTracking = undefined;
  2096. state.dependenciesCount = 0;
  2097. state.isDisposed = true;
  2098. state.isStale = false;
  2099. state.isDirty = false;
  2100. state.isSleeping = false;
  2101. state.disposeWhenNodeIsRemoved = undefined;
  2102. state.disposeWhen = undefined;
  2103. state.readFunction = undefined;
  2104. if (!this.hasWriteFunction) {
  2105. state.evaluatorFunctionTarget = undefined;
  2106. }
  2107. }
  2108. };
  2109. var pureComputedOverrides = {
  2110. beforeSubscriptionAdd: function (event) {
  2111. // If asleep, wake up the computed by subscribing to any dependencies.
  2112. var computedObservable = this,
  2113. state = computedObservable[computedState];
  2114. if (!state.isDisposed && state.isSleeping && event == 'change') {
  2115. state.isSleeping = false;
  2116. if (state.isStale || computedObservable.haveDependenciesChanged()) {
  2117. state.dependencyTracking = null;
  2118. state.dependenciesCount = 0;
  2119. if (computedObservable.evaluateImmediate()) {
  2120. computedObservable.updateVersion();
  2121. }
  2122. } else {
  2123. // First put the dependencies in order
  2124. var dependenciesOrder = [];
  2125. ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) {
  2126. dependenciesOrder[dependency._order] = id;
  2127. });
  2128. // Next, subscribe to each one
  2129. ko.utils.arrayForEach(dependenciesOrder, function (id, order) {
  2130. var dependency = state.dependencyTracking[id],
  2131. subscription = computedObservable.subscribeToDependency(dependency._target);
  2132. subscription._order = order;
  2133. subscription._version = dependency._version;
  2134. state.dependencyTracking[id] = subscription;
  2135. });
  2136. // Waking dependencies may have triggered effects
  2137. if (computedObservable.haveDependenciesChanged()) {
  2138. if (computedObservable.evaluateImmediate()) {
  2139. computedObservable.updateVersion();
  2140. }
  2141. }
  2142. }
  2143. if (!state.isDisposed) { // test since evaluating could trigger disposal
  2144. computedObservable["notifySubscribers"](state.latestValue, "awake");
  2145. }
  2146. }
  2147. },
  2148. afterSubscriptionRemove: function (event) {
  2149. var state = this[computedState];
  2150. if (!state.isDisposed && event == 'change' && !this.hasSubscriptionsForEvent('change')) {
  2151. ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) {
  2152. if (dependency.dispose) {
  2153. state.dependencyTracking[id] = {
  2154. _target: dependency._target,
  2155. _order: dependency._order,
  2156. _version: dependency._version
  2157. };
  2158. dependency.dispose();
  2159. }
  2160. });
  2161. state.isSleeping = true;
  2162. this["notifySubscribers"](undefined, "asleep");
  2163. }
  2164. },
  2165. getVersion: function () {
  2166. // Because a pure computed is not automatically updated while it is sleeping, we can't
  2167. // simply return the version number. Instead, we check if any of the dependencies have
  2168. // changed and conditionally re-evaluate the computed observable.
  2169. var state = this[computedState];
  2170. if (state.isSleeping && (state.isStale || this.haveDependenciesChanged())) {
  2171. this.evaluateImmediate();
  2172. }
  2173. return ko.subscribable['fn'].getVersion.call(this);
  2174. }
  2175. };
  2176. var deferEvaluationOverrides = {
  2177. beforeSubscriptionAdd: function (event) {
  2178. // This will force a computed with deferEvaluation to evaluate when the first subscription is registered.
  2179. if (event == 'change' || event == 'beforeChange') {
  2180. this.peek();
  2181. }
  2182. }
  2183. };
  2184. // Note that for browsers that don't support proto assignment, the
  2185. // inheritance chain is created manually in the ko.computed constructor
  2186. if (ko.utils.canSetPrototype) {
  2187. ko.utils.setPrototypeOf(computedFn, ko.subscribable['fn']);
  2188. }
  2189. // Set the proto values for ko.computed
  2190. var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
  2191. computedFn[protoProp] = ko.computed;
  2192. ko.isComputed = function (instance) {
  2193. return (typeof instance == 'function' && instance[protoProp] === computedFn[protoProp]);
  2194. };
  2195. ko.isPureComputed = function (instance) {
  2196. return ko.isComputed(instance) && instance[computedState] && instance[computedState].pure;
  2197. };
  2198. ko.exportSymbol('computed', ko.computed);
  2199. ko.exportSymbol('dependentObservable', ko.computed); // export ko.dependentObservable for backwards compatibility (1.x)
  2200. ko.exportSymbol('isComputed', ko.isComputed);
  2201. ko.exportSymbol('isPureComputed', ko.isPureComputed);
  2202. ko.exportSymbol('computed.fn', computedFn);
  2203. ko.exportProperty(computedFn, 'peek', computedFn.peek);
  2204. ko.exportProperty(computedFn, 'dispose', computedFn.dispose);
  2205. ko.exportProperty(computedFn, 'isActive', computedFn.isActive);
  2206. ko.exportProperty(computedFn, 'getDependenciesCount', computedFn.getDependenciesCount);
  2207. ko.exportProperty(computedFn, 'getDependencies', computedFn.getDependencies);
  2208. ko.pureComputed = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget) {
  2209. if (typeof evaluatorFunctionOrOptions === 'function') {
  2210. return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget, {'pure':true});
  2211. } else {
  2212. evaluatorFunctionOrOptions = ko.utils.extend({}, evaluatorFunctionOrOptions); // make a copy of the parameter object
  2213. evaluatorFunctionOrOptions['pure'] = true;
  2214. return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget);
  2215. }
  2216. }
  2217. ko.exportSymbol('pureComputed', ko.pureComputed);
  2218. (function() {
  2219. var maxNestedObservableDepth = 10; // Escape the (unlikely) pathological case where an observable's current value is itself (or similar reference cycle)
  2220. ko.toJS = function(rootObject) {
  2221. if (arguments.length == 0)
  2222. throw new Error("When calling ko.toJS, pass the object you want to convert.");
  2223. // We just unwrap everything at every level in the object graph
  2224. return mapJsObjectGraph(rootObject, function(valueToMap) {
  2225. // Loop because an observable's value might in turn be another observable wrapper
  2226. for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
  2227. valueToMap = valueToMap();
  2228. return valueToMap;
  2229. });
  2230. };
  2231. ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
  2232. var plainJavaScriptObject = ko.toJS(rootObject);
  2233. return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
  2234. };
  2235. function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
  2236. visitedObjects = visitedObjects || new objectLookup();
  2237. rootObject = mapInputCallback(rootObject);
  2238. var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof RegExp)) && (!(rootObject instanceof Date)) && (!(rootObject instanceof String)) && (!(rootObject instanceof Number)) && (!(rootObject instanceof Boolean));
  2239. if (!canHaveProperties)
  2240. return rootObject;
  2241. var outputProperties = rootObject instanceof Array ? [] : {};
  2242. visitedObjects.save(rootObject, outputProperties);
  2243. visitPropertiesOrArrayEntries(rootObject, function(indexer) {
  2244. var propertyValue = mapInputCallback(rootObject[indexer]);
  2245. switch (typeof propertyValue) {
  2246. case "boolean":
  2247. case "number":
  2248. case "string":
  2249. case "function":
  2250. outputProperties[indexer] = propertyValue;
  2251. break;
  2252. case "object":
  2253. case "undefined":
  2254. var previouslyMappedValue = visitedObjects.get(propertyValue);
  2255. outputProperties[indexer] = (previouslyMappedValue !== undefined)
  2256. ? previouslyMappedValue
  2257. : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
  2258. break;
  2259. }
  2260. });
  2261. return outputProperties;
  2262. }
  2263. function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
  2264. if (rootObject instanceof Array) {
  2265. for (var i = 0; i < rootObject.length; i++)
  2266. visitorCallback(i);
  2267. // For arrays, also respect toJSON property for custom mappings (fixes #278)
  2268. if (typeof rootObject['toJSON'] == 'function')
  2269. visitorCallback('toJSON');
  2270. } else {
  2271. for (var propertyName in rootObject) {
  2272. visitorCallback(propertyName);
  2273. }
  2274. }
  2275. };
  2276. function objectLookup() {
  2277. this.keys = [];
  2278. this.values = [];
  2279. };
  2280. objectLookup.prototype = {
  2281. constructor: objectLookup,
  2282. save: function(key, value) {
  2283. var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
  2284. if (existingIndex >= 0)
  2285. this.values[existingIndex] = value;
  2286. else {
  2287. this.keys.push(key);
  2288. this.values.push(value);
  2289. }
  2290. },
  2291. get: function(key) {
  2292. var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
  2293. return (existingIndex >= 0) ? this.values[existingIndex] : undefined;
  2294. }
  2295. };
  2296. })();
  2297. ko.exportSymbol('toJS', ko.toJS);
  2298. ko.exportSymbol('toJSON', ko.toJSON);
  2299. ko.when = function(predicate, callback, context) {
  2300. function kowhen (resolve) {
  2301. var observable = ko.pureComputed(predicate, context).extend({notify:'always'});
  2302. var subscription = observable.subscribe(function(value) {
  2303. if (value) {
  2304. subscription.dispose();
  2305. resolve(value);
  2306. }
  2307. });
  2308. // In case the initial value is true, process it right away
  2309. observable['notifySubscribers'](observable.peek());
  2310. return subscription;
  2311. }
  2312. if (typeof Promise === "function" && !callback) {
  2313. return new Promise(kowhen);
  2314. } else {
  2315. return kowhen(callback.bind(context));
  2316. }
  2317. };
  2318. ko.exportSymbol('when', ko.when);
  2319. (function () {
  2320. var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
  2321. // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
  2322. // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
  2323. // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
  2324. ko.selectExtensions = {
  2325. readValue : function(element) {
  2326. switch (ko.utils.tagNameLower(element)) {
  2327. case 'option':
  2328. if (element[hasDomDataExpandoProperty] === true)
  2329. return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
  2330. return ko.utils.ieVersion <= 7
  2331. ? (element.getAttributeNode('value') && element.getAttributeNode('value').specified ? element.value : element.text)
  2332. : element.value;
  2333. case 'select':
  2334. return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
  2335. default:
  2336. return element.value;
  2337. }
  2338. },
  2339. writeValue: function(element, value, allowUnset) {
  2340. switch (ko.utils.tagNameLower(element)) {
  2341. case 'option':
  2342. if (typeof value === "string") {
  2343. ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
  2344. if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
  2345. delete element[hasDomDataExpandoProperty];
  2346. }
  2347. element.value = value;
  2348. }
  2349. else {
  2350. // Store arbitrary object using DomData
  2351. ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
  2352. element[hasDomDataExpandoProperty] = true;
  2353. // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
  2354. element.value = typeof value === "number" ? value : "";
  2355. }
  2356. break;
  2357. case 'select':
  2358. if (value === "" || value === null) // A blank string or null value will select the caption
  2359. value = undefined;
  2360. var selection = -1;
  2361. for (var i = 0, n = element.options.length, optionValue; i < n; ++i) {
  2362. optionValue = ko.selectExtensions.readValue(element.options[i]);
  2363. // Include special check to handle selecting a caption with a blank string value
  2364. if (optionValue == value || (optionValue === "" && value === undefined)) {
  2365. selection = i;
  2366. break;
  2367. }
  2368. }
  2369. if (allowUnset || selection >= 0 || (value === undefined && element.size > 1)) {
  2370. element.selectedIndex = selection;
  2371. if (ko.utils.ieVersion === 6) {
  2372. // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
  2373. // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
  2374. // to apply the value as well.
  2375. ko.utils.setTimeout(function () {
  2376. element.selectedIndex = selection;
  2377. }, 0);
  2378. }
  2379. }
  2380. break;
  2381. default:
  2382. if ((value === null) || (value === undefined))
  2383. value = "";
  2384. element.value = value;
  2385. break;
  2386. }
  2387. }
  2388. };
  2389. })();
  2390. ko.exportSymbol('selectExtensions', ko.selectExtensions);
  2391. ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
  2392. ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
  2393. ko.expressionRewriting = (function () {
  2394. var javaScriptReservedWords = ["true", "false", "null", "undefined"];
  2395. // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
  2396. // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
  2397. // This also will not properly handle nested brackets (e.g., obj1[obj2['prop']]; see #911).
  2398. var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
  2399. function getWriteableValue(expression) {
  2400. if (ko.utils.arrayIndexOf(javaScriptReservedWords, expression) >= 0)
  2401. return false;
  2402. var match = expression.match(javaScriptAssignmentTarget);
  2403. return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
  2404. }
  2405. // The following regular expressions will be used to split an object-literal string into tokens
  2406. var specials = ',"\'`{}()/:[\\]', // These characters have special meaning to the parser and must not appear in the middle of a token, except as part of a string.
  2407. // Create the actual regular expression by or-ing the following regex strings. The order is important.
  2408. bindingToken = RegExp([
  2409. // These match strings, either with double quotes, single quotes, or backticks
  2410. '"(?:\\\\.|[^"])*"',
  2411. "'(?:\\\\.|[^'])*'",
  2412. "`(?:\\\\.|[^`])*`",
  2413. // Match C style comments
  2414. "/\\*(?:[^*]|\\*+[^*/])*\\*+/",
  2415. // Match C++ style comments
  2416. "//.*\n",
  2417. // Match a regular expression (text enclosed by slashes), but will also match sets of divisions
  2418. // as a regular expression (this is handled by the parsing loop below).
  2419. '/(?:\\\\.|[^/])+/\w*',
  2420. // Match text (at least two characters) that does not contain any of the above special characters,
  2421. // although some of the special characters are allowed to start it (all but the colon and comma).
  2422. // The text can contain spaces, but leading or trailing spaces are skipped.
  2423. '[^\\s:,/][^' + specials + ']*[^\\s' + specials + ']',
  2424. // Match any non-space character not matched already. This will match colons and commas, since they're
  2425. // not matched by "everyThingElse", but will also match any other single character that wasn't already
  2426. // matched (for example: in "a: 1, b: 2", each of the non-space characters will be matched by oneNotSpace).
  2427. '[^\\s]'
  2428. ].join('|'), 'g'),
  2429. // Match end of previous token to determine whether a slash is a division or regex.
  2430. divisionLookBehind = /[\])"'A-Za-z0-9_$]+$/,
  2431. keywordRegexLookBehind = {'in':1,'return':1,'typeof':1};
  2432. function parseObjectLiteral(objectLiteralString) {
  2433. // Trim leading and trailing spaces from the string
  2434. var str = ko.utils.stringTrim(objectLiteralString);
  2435. // Trim braces '{' surrounding the whole object literal
  2436. if (str.charCodeAt(0) === 123) str = str.slice(1, -1);
  2437. // Add a newline to correctly match a C++ style comment at the end of the string and
  2438. // add a comma so that we don't need a separate code block to deal with the last item
  2439. str += "\n,";
  2440. // Split into tokens
  2441. var result = [], toks = str.match(bindingToken), key, values = [], depth = 0;
  2442. if (toks.length > 1) {
  2443. for (var i = 0, tok; tok = toks[i]; ++i) {
  2444. var c = tok.charCodeAt(0);
  2445. // A comma signals the end of a key/value pair if depth is zero
  2446. if (c === 44) { // ","
  2447. if (depth <= 0) {
  2448. result.push((key && values.length) ? {key: key, value: values.join('')} : {'unknown': key || values.join('')});
  2449. key = depth = 0;
  2450. values = [];
  2451. continue;
  2452. }
  2453. // Simply skip the colon that separates the name and value
  2454. } else if (c === 58) { // ":"
  2455. if (!depth && !key && values.length === 1) {
  2456. key = values.pop();
  2457. continue;
  2458. }
  2459. // Comments: skip them
  2460. } else if (c === 47 && tok.length > 1 && (tok.charCodeAt(1) === 47 || tok.charCodeAt(1) === 42)) { // "//" or "/*"
  2461. continue;
  2462. // A set of slashes is initially matched as a regular expression, but could be division
  2463. } else if (c === 47 && i && tok.length > 1) { // "/"
  2464. // Look at the end of the previous token to determine if the slash is actually division
  2465. var match = toks[i-1].match(divisionLookBehind);
  2466. if (match && !keywordRegexLookBehind[match[0]]) {
  2467. // The slash is actually a division punctuator; re-parse the remainder of the string (not including the slash)
  2468. str = str.substr(str.indexOf(tok) + 1);
  2469. toks = str.match(bindingToken);
  2470. i = -1;
  2471. // Continue with just the slash
  2472. tok = '/';
  2473. }
  2474. // Increment depth for parentheses, braces, and brackets so that interior commas are ignored
  2475. } else if (c === 40 || c === 123 || c === 91) { // '(', '{', '['
  2476. ++depth;
  2477. } else if (c === 41 || c === 125 || c === 93) { // ')', '}', ']'
  2478. --depth;
  2479. // The key will be the first token; if it's a string, trim the quotes
  2480. } else if (!key && !values.length && (c === 34 || c === 39)) { // '"', "'"
  2481. tok = tok.slice(1, -1);
  2482. }
  2483. values.push(tok);
  2484. }
  2485. if (depth > 0) {
  2486. throw Error("Unbalanced parentheses, braces, or brackets");
  2487. }
  2488. }
  2489. return result;
  2490. }
  2491. // Two-way bindings include a write function that allow the handler to update the value even if it's not an observable.
  2492. var twoWayBindings = {};
  2493. function preProcessBindings(bindingsStringOrKeyValueArray, bindingOptions) {
  2494. bindingOptions = bindingOptions || {};
  2495. function processKeyValue(key, val) {
  2496. var writableVal;
  2497. function callPreprocessHook(obj) {
  2498. return (obj && obj['preprocess']) ? (val = obj['preprocess'](val, key, processKeyValue)) : true;
  2499. }
  2500. if (!bindingParams) {
  2501. if (!callPreprocessHook(ko['getBindingHandler'](key)))
  2502. return;
  2503. if (twoWayBindings[key] && (writableVal = getWriteableValue(val))) {
  2504. // For two-way bindings, provide a write method in case the value
  2505. // isn't a writable observable.
  2506. var writeKey = typeof twoWayBindings[key] == 'string' ? twoWayBindings[key] : key;
  2507. propertyAccessorResultStrings.push("'" + writeKey + "':function(_z){" + writableVal + "=_z}");
  2508. }
  2509. }
  2510. // Values are wrapped in a function so that each value can be accessed independently
  2511. if (makeValueAccessors) {
  2512. val = 'function(){return ' + val + ' }';
  2513. }
  2514. resultStrings.push("'" + key + "':" + val);
  2515. }
  2516. var resultStrings = [],
  2517. propertyAccessorResultStrings = [],
  2518. makeValueAccessors = bindingOptions['valueAccessors'],
  2519. bindingParams = bindingOptions['bindingParams'],
  2520. keyValueArray = typeof bindingsStringOrKeyValueArray === "string" ?
  2521. parseObjectLiteral(bindingsStringOrKeyValueArray) : bindingsStringOrKeyValueArray;
  2522. ko.utils.arrayForEach(keyValueArray, function(keyValue) {
  2523. processKeyValue(keyValue.key || keyValue['unknown'], keyValue.value);
  2524. });
  2525. if (propertyAccessorResultStrings.length)
  2526. processKeyValue('_ko_property_writers', "{" + propertyAccessorResultStrings.join(",") + " }");
  2527. return resultStrings.join(",");
  2528. }
  2529. return {
  2530. bindingRewriteValidators: [],
  2531. twoWayBindings: twoWayBindings,
  2532. parseObjectLiteral: parseObjectLiteral,
  2533. preProcessBindings: preProcessBindings,
  2534. keyValueArrayContainsKey: function(keyValueArray, key) {
  2535. for (var i = 0; i < keyValueArray.length; i++)
  2536. if (keyValueArray[i]['key'] == key)
  2537. return true;
  2538. return false;
  2539. },
  2540. // Internal, private KO utility for updating model properties from within bindings
  2541. // property: If the property being updated is (or might be) an observable, pass it here
  2542. // If it turns out to be a writable observable, it will be written to directly
  2543. // allBindings: An object with a get method to retrieve bindings in the current execution context.
  2544. // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
  2545. // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
  2546. // value: The value to be written
  2547. // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
  2548. // it is !== existing value on that writable observable
  2549. writeValueToProperty: function(property, allBindings, key, value, checkIfDifferent) {
  2550. if (!property || !ko.isObservable(property)) {
  2551. var propWriters = allBindings.get('_ko_property_writers');
  2552. if (propWriters && propWriters[key])
  2553. propWriters[key](value);
  2554. } else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {
  2555. property(value);
  2556. }
  2557. }
  2558. };
  2559. })();
  2560. ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
  2561. ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
  2562. ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
  2563. ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
  2564. // Making bindings explicitly declare themselves as "two way" isn't ideal in the long term (it would be better if
  2565. // all bindings could use an official 'property writer' API without needing to declare that they might). However,
  2566. // since this is not, and has never been, a public API (_ko_property_writers was never documented), it's acceptable
  2567. // as an internal implementation detail in the short term.
  2568. // For those developers who rely on _ko_property_writers in their custom bindings, we expose _twoWayBindings as an
  2569. // undocumented feature that makes it relatively easy to upgrade to KO 3.0. However, this is still not an official
  2570. // public API, and we reserve the right to remove it at any time if we create a real public property writers API.
  2571. ko.exportSymbol('expressionRewriting._twoWayBindings', ko.expressionRewriting.twoWayBindings);
  2572. // For backward compatibility, define the following aliases. (Previously, these function names were misleading because
  2573. // they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
  2574. ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
  2575. ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);
  2576. (function() {
  2577. // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
  2578. // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
  2579. // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
  2580. // of that virtual hierarchy
  2581. //
  2582. // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
  2583. // without having to scatter special cases all over the binding and templating code.
  2584. // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
  2585. // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
  2586. // So, use node.text where available, and node.nodeValue elsewhere
  2587. var commentNodesHaveTextProperty = document && document.createComment("test").text === "<!--test-->";
  2588. var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/;
  2589. var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
  2590. var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
  2591. function isStartComment(node) {
  2592. return (node.nodeType == 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
  2593. }
  2594. function isEndComment(node) {
  2595. return (node.nodeType == 8) && endCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
  2596. }
  2597. function isUnmatchedEndComment(node) {
  2598. return isEndComment(node) && !(ko.utils.domData.get(node, matchedEndCommentDataKey));
  2599. }
  2600. var matchedEndCommentDataKey = "__ko_matchedEndComment__"
  2601. function getVirtualChildren(startComment, allowUnbalanced) {
  2602. var currentNode = startComment;
  2603. var depth = 1;
  2604. var children = [];
  2605. while (currentNode = currentNode.nextSibling) {
  2606. if (isEndComment(currentNode)) {
  2607. ko.utils.domData.set(currentNode, matchedEndCommentDataKey, true);
  2608. depth--;
  2609. if (depth === 0)
  2610. return children;
  2611. }
  2612. children.push(currentNode);
  2613. if (isStartComment(currentNode))
  2614. depth++;
  2615. }
  2616. if (!allowUnbalanced)
  2617. throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
  2618. return null;
  2619. }
  2620. function getMatchingEndComment(startComment, allowUnbalanced) {
  2621. var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
  2622. if (allVirtualChildren) {
  2623. if (allVirtualChildren.length > 0)
  2624. return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
  2625. return startComment.nextSibling;
  2626. } else
  2627. return null; // Must have no matching end comment, and allowUnbalanced is true
  2628. }
  2629. function getUnbalancedChildTags(node) {
  2630. // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
  2631. // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
  2632. var childNode = node.firstChild, captureRemaining = null;
  2633. if (childNode) {
  2634. do {
  2635. if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
  2636. captureRemaining.push(childNode);
  2637. else if (isStartComment(childNode)) {
  2638. var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
  2639. if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
  2640. childNode = matchingEndComment;
  2641. else
  2642. captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
  2643. } else if (isEndComment(childNode)) {
  2644. captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
  2645. }
  2646. } while (childNode = childNode.nextSibling);
  2647. }
  2648. return captureRemaining;
  2649. }
  2650. ko.virtualElements = {
  2651. allowedBindings: {},
  2652. childNodes: function(node) {
  2653. return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
  2654. },
  2655. emptyNode: function(node) {
  2656. if (!isStartComment(node))
  2657. ko.utils.emptyDomNode(node);
  2658. else {
  2659. var virtualChildren = ko.virtualElements.childNodes(node);
  2660. for (var i = 0, j = virtualChildren.length; i < j; i++)
  2661. ko.removeNode(virtualChildren[i]);
  2662. }
  2663. },
  2664. setDomNodeChildren: function(node, childNodes) {
  2665. if (!isStartComment(node))
  2666. ko.utils.setDomNodeChildren(node, childNodes);
  2667. else {
  2668. ko.virtualElements.emptyNode(node);
  2669. var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
  2670. for (var i = 0, j = childNodes.length; i < j; i++)
  2671. endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
  2672. }
  2673. },
  2674. prepend: function(containerNode, nodeToPrepend) {
  2675. var insertBeforeNode;
  2676. if (isStartComment(containerNode)) {
  2677. // Start comments must always have a parent and at least one following sibling (the end comment)
  2678. insertBeforeNode = containerNode.nextSibling;
  2679. containerNode = containerNode.parentNode;
  2680. } else {
  2681. insertBeforeNode = containerNode.firstChild;
  2682. }
  2683. if (!insertBeforeNode) {
  2684. containerNode.appendChild(nodeToPrepend);
  2685. } else if (nodeToPrepend !== insertBeforeNode) { // IE will sometimes crash if you try to insert a node before itself
  2686. containerNode.insertBefore(nodeToPrepend, insertBeforeNode);
  2687. }
  2688. },
  2689. insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
  2690. if (!insertAfterNode) {
  2691. ko.virtualElements.prepend(containerNode, nodeToInsert);
  2692. } else {
  2693. // Children of start comments must always have a parent and at least one following sibling (the end comment)
  2694. var insertBeforeNode = insertAfterNode.nextSibling;
  2695. if (isStartComment(containerNode)) {
  2696. containerNode = containerNode.parentNode;
  2697. }
  2698. if (!insertBeforeNode) {
  2699. containerNode.appendChild(nodeToInsert);
  2700. } else if (nodeToInsert !== insertBeforeNode) { // IE will sometimes crash if you try to insert a node before itself
  2701. containerNode.insertBefore(nodeToInsert, insertBeforeNode);
  2702. }
  2703. }
  2704. },
  2705. firstChild: function(node) {
  2706. if (!isStartComment(node)) {
  2707. if (node.firstChild && isEndComment(node.firstChild)) {
  2708. throw new Error("Found invalid end comment, as the first child of " + node);
  2709. }
  2710. return node.firstChild;
  2711. } else if (!node.nextSibling || isEndComment(node.nextSibling)) {
  2712. return null;
  2713. } else {
  2714. return node.nextSibling;
  2715. }
  2716. },
  2717. nextSibling: function(node) {
  2718. if (isStartComment(node)) {
  2719. node = getMatchingEndComment(node);
  2720. }
  2721. if (node.nextSibling && isEndComment(node.nextSibling)) {
  2722. if (isUnmatchedEndComment(node.nextSibling)) {
  2723. throw Error("Found end comment without a matching opening comment, as child of " + node);
  2724. } else {
  2725. return null;
  2726. }
  2727. } else {
  2728. return node.nextSibling;
  2729. }
  2730. },
  2731. hasBindingValue: isStartComment,
  2732. virtualNodeBindingValue: function(node) {
  2733. var regexMatch = (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
  2734. return regexMatch ? regexMatch[1] : null;
  2735. },
  2736. normaliseVirtualElementDomStructure: function(elementVerified) {
  2737. // Workaround for https://github.com/SteveSanderson/knockout/issues/155
  2738. // (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
  2739. // that are direct descendants of <ul> into the preceding <li>)
  2740. if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
  2741. return;
  2742. // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
  2743. // must be intended to appear *after* that child, so move them there.
  2744. var childNode = elementVerified.firstChild;
  2745. if (childNode) {
  2746. do {
  2747. if (childNode.nodeType === 1) {
  2748. var unbalancedTags = getUnbalancedChildTags(childNode);
  2749. if (unbalancedTags) {
  2750. // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
  2751. var nodeToInsertBefore = childNode.nextSibling;
  2752. for (var i = 0; i < unbalancedTags.length; i++) {
  2753. if (nodeToInsertBefore)
  2754. elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
  2755. else
  2756. elementVerified.appendChild(unbalancedTags[i]);
  2757. }
  2758. }
  2759. }
  2760. } while (childNode = childNode.nextSibling);
  2761. }
  2762. }
  2763. };
  2764. })();
  2765. ko.exportSymbol('virtualElements', ko.virtualElements);
  2766. ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
  2767. ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
  2768. //ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
  2769. ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
  2770. //ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
  2771. ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
  2772. ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
  2773. (function() {
  2774. var defaultBindingAttributeName = "data-bind";
  2775. ko.bindingProvider = function() {
  2776. this.bindingCache = {};
  2777. };
  2778. ko.utils.extend(ko.bindingProvider.prototype, {
  2779. 'nodeHasBindings': function(node) {
  2780. switch (node.nodeType) {
  2781. case 1: // Element
  2782. return node.getAttribute(defaultBindingAttributeName) != null
  2783. || ko.components['getComponentNameForNode'](node);
  2784. case 8: // Comment node
  2785. return ko.virtualElements.hasBindingValue(node);
  2786. default: return false;
  2787. }
  2788. },
  2789. 'getBindings': function(node, bindingContext) {
  2790. var bindingsString = this['getBindingsString'](node, bindingContext),
  2791. parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
  2792. return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ false);
  2793. },
  2794. 'getBindingAccessors': function(node, bindingContext) {
  2795. var bindingsString = this['getBindingsString'](node, bindingContext),
  2796. parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node, { 'valueAccessors': true }) : null;
  2797. return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ true);
  2798. },
  2799. // The following function is only used internally by this default provider.
  2800. // It's not part of the interface definition for a general binding provider.
  2801. 'getBindingsString': function(node, bindingContext) {
  2802. switch (node.nodeType) {
  2803. case 1: return node.getAttribute(defaultBindingAttributeName); // Element
  2804. case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
  2805. default: return null;
  2806. }
  2807. },
  2808. // The following function is only used internally by this default provider.
  2809. // It's not part of the interface definition for a general binding provider.
  2810. 'parseBindingsString': function(bindingsString, bindingContext, node, options) {
  2811. try {
  2812. var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache, options);
  2813. return bindingFunction(bindingContext, node);
  2814. } catch (ex) {
  2815. ex.message = "Unable to parse bindings.\nBindings value: " + bindingsString + "\nMessage: " + ex.message;
  2816. throw ex;
  2817. }
  2818. }
  2819. });
  2820. ko.bindingProvider['instance'] = new ko.bindingProvider();
  2821. function createBindingsStringEvaluatorViaCache(bindingsString, cache, options) {
  2822. var cacheKey = bindingsString + (options && options['valueAccessors'] || '');
  2823. return cache[cacheKey]
  2824. || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, options));
  2825. }
  2826. function createBindingsStringEvaluator(bindingsString, options) {
  2827. // Build the source for a function that evaluates "expression"
  2828. // For each scope variable, add an extra level of "with" nesting
  2829. // Example result: with(sc1) { with(sc0) { return (expression) } }
  2830. var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString, options),
  2831. functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
  2832. return new Function("$context", "$element", functionBody);
  2833. }
  2834. })();
  2835. ko.exportSymbol('bindingProvider', ko.bindingProvider);
  2836. (function () {
  2837. // Hide or don't minify context properties, see https://github.com/knockout/knockout/issues/2294
  2838. var contextSubscribable = ko.utils.createSymbolOrString('_subscribable');
  2839. var contextAncestorBindingInfo = ko.utils.createSymbolOrString('_ancestorBindingInfo');
  2840. var contextDataDependency = ko.utils.createSymbolOrString('_dataDependency');
  2841. ko.bindingHandlers = {};
  2842. // The following element types will not be recursed into during binding.
  2843. var bindingDoesNotRecurseIntoElementTypes = {
  2844. // Don't want bindings that operate on text nodes to mutate <script> and <textarea> contents,
  2845. // because it's unexpected and a potential XSS issue.
  2846. // Also bindings should not operate on <template> elements since this breaks in Internet Explorer
  2847. // and because such elements' contents are always intended to be bound in a different context
  2848. // from where they appear in the document.
  2849. 'script': true,
  2850. 'textarea': true,
  2851. 'template': true
  2852. };
  2853. // Use an overridable method for retrieving binding handlers so that plugins may support dynamically created handlers
  2854. ko['getBindingHandler'] = function(bindingKey) {
  2855. return ko.bindingHandlers[bindingKey];
  2856. };
  2857. var inheritParentVm = {};
  2858. // The ko.bindingContext constructor is only called directly to create the root context. For child
  2859. // contexts, use bindingContext.createChildContext or bindingContext.extend.
  2860. ko.bindingContext = function(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback, options) {
  2861. // The binding context object includes static properties for the current, parent, and root view models.
  2862. // If a view model is actually stored in an observable, the corresponding binding context object, and
  2863. // any child contexts, must be updated when the view model is changed.
  2864. function updateContext() {
  2865. // Most of the time, the context will directly get a view model object, but if a function is given,
  2866. // we call the function to retrieve the view model. If the function accesses any observables or returns
  2867. // an observable, the dependency is tracked, and those observables can later cause the binding
  2868. // context to be updated.
  2869. var dataItemOrObservable = isFunc ? realDataItemOrAccessor() : realDataItemOrAccessor,
  2870. dataItem = ko.utils.unwrapObservable(dataItemOrObservable);
  2871. if (parentContext) {
  2872. // Copy $root and any custom properties from the parent context
  2873. ko.utils.extend(self, parentContext);
  2874. // Copy Symbol properties
  2875. if (contextAncestorBindingInfo in parentContext) {
  2876. self[contextAncestorBindingInfo] = parentContext[contextAncestorBindingInfo];
  2877. }
  2878. } else {
  2879. self['$parents'] = [];
  2880. self['$root'] = dataItem;
  2881. // Export 'ko' in the binding context so it will be available in bindings and templates
  2882. // even if 'ko' isn't exported as a global, such as when using an AMD loader.
  2883. // See https://github.com/SteveSanderson/knockout/issues/490
  2884. self['ko'] = ko;
  2885. }
  2886. self[contextSubscribable] = subscribable;
  2887. if (shouldInheritData) {
  2888. dataItem = self['$data'];
  2889. } else {
  2890. self['$rawData'] = dataItemOrObservable;
  2891. self['$data'] = dataItem;
  2892. }
  2893. if (dataItemAlias)
  2894. self[dataItemAlias] = dataItem;
  2895. // The extendCallback function is provided when creating a child context or extending a context.
  2896. // It handles the specific actions needed to finish setting up the binding context. Actions in this
  2897. // function could also add dependencies to this binding context.
  2898. if (extendCallback)
  2899. extendCallback(self, parentContext, dataItem);
  2900. // When a "parent" context is given and we don't already have a dependency on its context, register a dependency on it.
  2901. // Thus whenever the parent context is updated, this context will also be updated.
  2902. if (parentContext && parentContext[contextSubscribable] && !ko.computedContext.computed().hasAncestorDependency(parentContext[contextSubscribable])) {
  2903. parentContext[contextSubscribable]();
  2904. }
  2905. if (dataDependency) {
  2906. self[contextDataDependency] = dataDependency;
  2907. }
  2908. return self['$data'];
  2909. }
  2910. var self = this,
  2911. shouldInheritData = dataItemOrAccessor === inheritParentVm,
  2912. realDataItemOrAccessor = shouldInheritData ? undefined : dataItemOrAccessor,
  2913. isFunc = typeof(realDataItemOrAccessor) == "function" && !ko.isObservable(realDataItemOrAccessor),
  2914. nodes,
  2915. subscribable,
  2916. dataDependency = options && options['dataDependency'];
  2917. if (options && options['exportDependencies']) {
  2918. // The "exportDependencies" option means that the calling code will track any dependencies and re-create
  2919. // the binding context when they change.
  2920. updateContext();
  2921. } else {
  2922. subscribable = ko.pureComputed(updateContext);
  2923. subscribable.peek();
  2924. // At this point, the binding context has been initialized, and the "subscribable" computed observable is
  2925. // subscribed to any observables that were accessed in the process. If there is nothing to track, the
  2926. // computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
  2927. // the context object.
  2928. if (subscribable.isActive()) {
  2929. // Always notify because even if the model ($data) hasn't changed, other context properties might have changed
  2930. subscribable['equalityComparer'] = null;
  2931. } else {
  2932. self[contextSubscribable] = undefined;
  2933. }
  2934. }
  2935. }
  2936. // Extend the binding context hierarchy with a new view model object. If the parent context is watching
  2937. // any observables, the new child context will automatically get a dependency on the parent context.
  2938. // But this does not mean that the $data value of the child context will also get updated. If the child
  2939. // view model also depends on the parent view model, you must provide a function that returns the correct
  2940. // view model on each update.
  2941. ko.bindingContext.prototype['createChildContext'] = function (dataItemOrAccessor, dataItemAlias, extendCallback, options) {
  2942. if (!options && dataItemAlias && typeof dataItemAlias == "object") {
  2943. options = dataItemAlias;
  2944. dataItemAlias = options['as'];
  2945. extendCallback = options['extend'];
  2946. }
  2947. if (dataItemAlias && options && options['noChildContext']) {
  2948. var isFunc = typeof(dataItemOrAccessor) == "function" && !ko.isObservable(dataItemOrAccessor);
  2949. return new ko.bindingContext(inheritParentVm, this, null, function (self) {
  2950. if (extendCallback)
  2951. extendCallback(self);
  2952. self[dataItemAlias] = isFunc ? dataItemOrAccessor() : dataItemOrAccessor;
  2953. }, options);
  2954. }
  2955. return new ko.bindingContext(dataItemOrAccessor, this, dataItemAlias, function (self, parentContext) {
  2956. // Extend the context hierarchy by setting the appropriate pointers
  2957. self['$parentContext'] = parentContext;
  2958. self['$parent'] = parentContext['$data'];
  2959. self['$parents'] = (parentContext['$parents'] || []).slice(0);
  2960. self['$parents'].unshift(self['$parent']);
  2961. if (extendCallback)
  2962. extendCallback(self);
  2963. }, options);
  2964. };
  2965. // Extend the binding context with new custom properties. This doesn't change the context hierarchy.
  2966. // Similarly to "child" contexts, provide a function here to make sure that the correct values are set
  2967. // when an observable view model is updated.
  2968. ko.bindingContext.prototype['extend'] = function(properties, options) {
  2969. return new ko.bindingContext(inheritParentVm, this, null, function(self, parentContext) {
  2970. ko.utils.extend(self, typeof(properties) == "function" ? properties(self) : properties);
  2971. }, options);
  2972. };
  2973. var boundElementDomDataKey = ko.utils.domData.nextKey();
  2974. function asyncContextDispose(node) {
  2975. var bindingInfo = ko.utils.domData.get(node, boundElementDomDataKey),
  2976. asyncContext = bindingInfo && bindingInfo.asyncContext;
  2977. if (asyncContext) {
  2978. bindingInfo.asyncContext = null;
  2979. asyncContext.notifyAncestor();
  2980. }
  2981. }
  2982. function AsyncCompleteContext(node, bindingInfo, ancestorBindingInfo) {
  2983. this.node = node;
  2984. this.bindingInfo = bindingInfo;
  2985. this.asyncDescendants = [];
  2986. this.childrenComplete = false;
  2987. if (!bindingInfo.asyncContext) {
  2988. ko.utils.domNodeDisposal.addDisposeCallback(node, asyncContextDispose);
  2989. }
  2990. if (ancestorBindingInfo && ancestorBindingInfo.asyncContext) {
  2991. ancestorBindingInfo.asyncContext.asyncDescendants.push(node);
  2992. this.ancestorBindingInfo = ancestorBindingInfo;
  2993. }
  2994. }
  2995. AsyncCompleteContext.prototype.notifyAncestor = function () {
  2996. if (this.ancestorBindingInfo && this.ancestorBindingInfo.asyncContext) {
  2997. this.ancestorBindingInfo.asyncContext.descendantComplete(this.node);
  2998. }
  2999. };
  3000. AsyncCompleteContext.prototype.descendantComplete = function (node) {
  3001. ko.utils.arrayRemoveItem(this.asyncDescendants, node);
  3002. if (!this.asyncDescendants.length && this.childrenComplete) {
  3003. this.completeChildren();
  3004. }
  3005. };
  3006. AsyncCompleteContext.prototype.completeChildren = function () {
  3007. this.childrenComplete = true;
  3008. if (this.bindingInfo.asyncContext && !this.asyncDescendants.length) {
  3009. this.bindingInfo.asyncContext = null;
  3010. ko.utils.domNodeDisposal.removeDisposeCallback(this.node, asyncContextDispose);
  3011. ko.bindingEvent.notify(this.node, ko.bindingEvent.descendantsComplete);
  3012. this.notifyAncestor();
  3013. }
  3014. };
  3015. ko.bindingEvent = {
  3016. childrenComplete: "childrenComplete",
  3017. descendantsComplete : "descendantsComplete",
  3018. subscribe: function (node, event, callback, context, options) {
  3019. var bindingInfo = ko.utils.domData.getOrSet(node, boundElementDomDataKey, {});
  3020. if (!bindingInfo.eventSubscribable) {
  3021. bindingInfo.eventSubscribable = new ko.subscribable;
  3022. }
  3023. if (options && options['notifyImmediately'] && bindingInfo.notifiedEvents[event]) {
  3024. ko.dependencyDetection.ignore(callback, context, [node]);
  3025. }
  3026. return bindingInfo.eventSubscribable.subscribe(callback, context, event);
  3027. },
  3028. notify: function (node, event) {
  3029. var bindingInfo = ko.utils.domData.get(node, boundElementDomDataKey);
  3030. if (bindingInfo) {
  3031. bindingInfo.notifiedEvents[event] = true;
  3032. if (bindingInfo.eventSubscribable) {
  3033. bindingInfo.eventSubscribable['notifySubscribers'](node, event);
  3034. }
  3035. if (event == ko.bindingEvent.childrenComplete) {
  3036. if (bindingInfo.asyncContext) {
  3037. bindingInfo.asyncContext.completeChildren();
  3038. } else if (bindingInfo.asyncContext === undefined && bindingInfo.eventSubscribable && bindingInfo.eventSubscribable.hasSubscriptionsForEvent(ko.bindingEvent.descendantsComplete)) {
  3039. // It's currently an error to register a descendantsComplete handler for a node that was never registered as completing asynchronously.
  3040. // That's because without the asyncContext, we don't have a way to know that all descendants have completed.
  3041. throw new Error("descendantsComplete event not supported for bindings on this node");
  3042. }
  3043. }
  3044. }
  3045. },
  3046. startPossiblyAsyncContentBinding: function (node, bindingContext) {
  3047. var bindingInfo = ko.utils.domData.getOrSet(node, boundElementDomDataKey, {});
  3048. if (!bindingInfo.asyncContext) {
  3049. bindingInfo.asyncContext = new AsyncCompleteContext(node, bindingInfo, bindingContext[contextAncestorBindingInfo]);
  3050. }
  3051. // If the provided context was already extended with this node's binding info, just return the extended context
  3052. if (bindingContext[contextAncestorBindingInfo] == bindingInfo) {
  3053. return bindingContext;
  3054. }
  3055. return bindingContext['extend'](function (ctx) {
  3056. ctx[contextAncestorBindingInfo] = bindingInfo;
  3057. });
  3058. }
  3059. };
  3060. // Returns the valueAccessor function for a binding value
  3061. function makeValueAccessor(value) {
  3062. return function() {
  3063. return value;
  3064. };
  3065. }
  3066. // Returns the value of a valueAccessor function
  3067. function evaluateValueAccessor(valueAccessor) {
  3068. return valueAccessor();
  3069. }
  3070. // Given a function that returns bindings, create and return a new object that contains
  3071. // binding value-accessors functions. Each accessor function calls the original function
  3072. // so that it always gets the latest value and all dependencies are captured. This is used
  3073. // by ko.applyBindingsToNode and getBindingsAndMakeAccessors.
  3074. function makeAccessorsFromFunction(callback) {
  3075. return ko.utils.objectMap(ko.dependencyDetection.ignore(callback), function(value, key) {
  3076. return function() {
  3077. return callback()[key];
  3078. };
  3079. });
  3080. }
  3081. // Given a bindings function or object, create and return a new object that contains
  3082. // binding value-accessors functions. This is used by ko.applyBindingsToNode.
  3083. function makeBindingAccessors(bindings, context, node) {
  3084. if (typeof bindings === 'function') {
  3085. return makeAccessorsFromFunction(bindings.bind(null, context, node));
  3086. } else {
  3087. return ko.utils.objectMap(bindings, makeValueAccessor);
  3088. }
  3089. }
  3090. // This function is used if the binding provider doesn't include a getBindingAccessors function.
  3091. // It must be called with 'this' set to the provider instance.
  3092. function getBindingsAndMakeAccessors(node, context) {
  3093. return makeAccessorsFromFunction(this['getBindings'].bind(this, node, context));
  3094. }
  3095. function validateThatBindingIsAllowedForVirtualElements(bindingName) {
  3096. var validator = ko.virtualElements.allowedBindings[bindingName];
  3097. if (!validator)
  3098. throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
  3099. }
  3100. function applyBindingsToDescendantsInternal(bindingContext, elementOrVirtualElement) {
  3101. var nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
  3102. if (nextInQueue) {
  3103. var currentChild,
  3104. provider = ko.bindingProvider['instance'],
  3105. preprocessNode = provider['preprocessNode'];
  3106. // Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's
  3107. // possible to insert new siblings after it, and/or replace the node with a different one. This can be used to
  3108. // implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that
  3109. // trigger insertion of <template> contents at that point in the document.
  3110. if (preprocessNode) {
  3111. while (currentChild = nextInQueue) {
  3112. nextInQueue = ko.virtualElements.nextSibling(currentChild);
  3113. preprocessNode.call(provider, currentChild);
  3114. }
  3115. // Reset nextInQueue for the next loop
  3116. nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
  3117. }
  3118. while (currentChild = nextInQueue) {
  3119. // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
  3120. nextInQueue = ko.virtualElements.nextSibling(currentChild);
  3121. applyBindingsToNodeAndDescendantsInternal(bindingContext, currentChild);
  3122. }
  3123. }
  3124. ko.bindingEvent.notify(elementOrVirtualElement, ko.bindingEvent.childrenComplete);
  3125. }
  3126. function applyBindingsToNodeAndDescendantsInternal(bindingContext, nodeVerified) {
  3127. var bindingContextForDescendants = bindingContext;
  3128. var isElement = (nodeVerified.nodeType === 1);
  3129. if (isElement) // Workaround IE <= 8 HTML parsing weirdness
  3130. ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
  3131. // Perf optimisation: Apply bindings only if...
  3132. // (1) We need to store the binding info for the node (all element nodes)
  3133. // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
  3134. var shouldApplyBindings = isElement || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified);
  3135. if (shouldApplyBindings)
  3136. bindingContextForDescendants = applyBindingsToNodeInternal(nodeVerified, null, bindingContext)['bindingContextForDescendants'];
  3137. if (bindingContextForDescendants && !bindingDoesNotRecurseIntoElementTypes[ko.utils.tagNameLower(nodeVerified)]) {
  3138. applyBindingsToDescendantsInternal(bindingContextForDescendants, nodeVerified);
  3139. }
  3140. }
  3141. function topologicalSortBindings(bindings) {
  3142. // Depth-first sort
  3143. var result = [], // The list of key/handler pairs that we will return
  3144. bindingsConsidered = {}, // A temporary record of which bindings are already in 'result'
  3145. cyclicDependencyStack = []; // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it
  3146. ko.utils.objectForEach(bindings, function pushBinding(bindingKey) {
  3147. if (!bindingsConsidered[bindingKey]) {
  3148. var binding = ko['getBindingHandler'](bindingKey);
  3149. if (binding) {
  3150. // First add dependencies (if any) of the current binding
  3151. if (binding['after']) {
  3152. cyclicDependencyStack.push(bindingKey);
  3153. ko.utils.arrayForEach(binding['after'], function(bindingDependencyKey) {
  3154. if (bindings[bindingDependencyKey]) {
  3155. if (ko.utils.arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) {
  3156. throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + cyclicDependencyStack.join(", "));
  3157. } else {
  3158. pushBinding(bindingDependencyKey);
  3159. }
  3160. }
  3161. });
  3162. cyclicDependencyStack.length--;
  3163. }
  3164. // Next add the current binding
  3165. result.push({ key: bindingKey, handler: binding });
  3166. }
  3167. bindingsConsidered[bindingKey] = true;
  3168. }
  3169. });
  3170. return result;
  3171. }
  3172. function applyBindingsToNodeInternal(node, sourceBindings, bindingContext) {
  3173. var bindingInfo = ko.utils.domData.getOrSet(node, boundElementDomDataKey, {});
  3174. // Prevent multiple applyBindings calls for the same node, except when a binding value is specified
  3175. var alreadyBound = bindingInfo.alreadyBound;
  3176. if (!sourceBindings) {
  3177. if (alreadyBound) {
  3178. throw Error("You cannot apply bindings multiple times to the same element.");
  3179. }
  3180. bindingInfo.alreadyBound = true;
  3181. }
  3182. if (!alreadyBound) {
  3183. bindingInfo.context = bindingContext;
  3184. }
  3185. if (!bindingInfo.notifiedEvents) {
  3186. bindingInfo.notifiedEvents = {};
  3187. }
  3188. // Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings
  3189. var bindings;
  3190. if (sourceBindings && typeof sourceBindings !== 'function') {
  3191. bindings = sourceBindings;
  3192. } else {
  3193. var provider = ko.bindingProvider['instance'],
  3194. getBindings = provider['getBindingAccessors'] || getBindingsAndMakeAccessors;
  3195. // Get the binding from the provider within a computed observable so that we can update the bindings whenever
  3196. // the binding context is updated or if the binding provider accesses observables.
  3197. var bindingsUpdater = ko.dependentObservable(
  3198. function() {
  3199. bindings = sourceBindings ? sourceBindings(bindingContext, node) : getBindings.call(provider, node, bindingContext);
  3200. // Register a dependency on the binding context to support observable view models.
  3201. if (bindings) {
  3202. if (bindingContext[contextSubscribable]) {
  3203. bindingContext[contextSubscribable]();
  3204. }
  3205. if (bindingContext[contextDataDependency]) {
  3206. bindingContext[contextDataDependency]();
  3207. }
  3208. }
  3209. return bindings;
  3210. },
  3211. null, { disposeWhenNodeIsRemoved: node }
  3212. );
  3213. if (!bindings || !bindingsUpdater.isActive())
  3214. bindingsUpdater = null;
  3215. }
  3216. var contextToExtend = bindingContext;
  3217. var bindingHandlerThatControlsDescendantBindings;
  3218. if (bindings) {
  3219. // Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding
  3220. // context update), just return the value accessor from the binding. Otherwise, return a function that always gets
  3221. // the latest binding value and registers a dependency on the binding updater.
  3222. var getValueAccessor = bindingsUpdater
  3223. ? function(bindingKey) {
  3224. return function() {
  3225. return evaluateValueAccessor(bindingsUpdater()[bindingKey]);
  3226. };
  3227. } : function(bindingKey) {
  3228. return bindings[bindingKey];
  3229. };
  3230. // Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated
  3231. function allBindings() {
  3232. return ko.utils.objectMap(bindingsUpdater ? bindingsUpdater() : bindings, evaluateValueAccessor);
  3233. }
  3234. // The following is the 3.x allBindings API
  3235. allBindings['get'] = function(key) {
  3236. return bindings[key] && evaluateValueAccessor(getValueAccessor(key));
  3237. };
  3238. allBindings['has'] = function(key) {
  3239. return key in bindings;
  3240. };
  3241. if (ko.bindingEvent.childrenComplete in bindings) {
  3242. ko.bindingEvent.subscribe(node, ko.bindingEvent.childrenComplete, function () {
  3243. var callback = evaluateValueAccessor(bindings[ko.bindingEvent.childrenComplete]);
  3244. if (callback) {
  3245. var nodes = ko.virtualElements.childNodes(node);
  3246. if (nodes.length) {
  3247. callback(nodes, ko.dataFor(nodes[0]));
  3248. }
  3249. }
  3250. });
  3251. }
  3252. if (ko.bindingEvent.descendantsComplete in bindings) {
  3253. contextToExtend = ko.bindingEvent.startPossiblyAsyncContentBinding(node, bindingContext);
  3254. ko.bindingEvent.subscribe(node, ko.bindingEvent.descendantsComplete, function () {
  3255. var callback = evaluateValueAccessor(bindings[ko.bindingEvent.descendantsComplete]);
  3256. if (callback && ko.virtualElements.firstChild(node)) {
  3257. callback(node);
  3258. }
  3259. });
  3260. }
  3261. // First put the bindings into the right order
  3262. var orderedBindings = topologicalSortBindings(bindings);
  3263. // Go through the sorted bindings, calling init and update for each
  3264. ko.utils.arrayForEach(orderedBindings, function(bindingKeyAndHandler) {
  3265. // Note that topologicalSortBindings has already filtered out any nonexistent binding handlers,
  3266. // so bindingKeyAndHandler.handler will always be nonnull.
  3267. var handlerInitFn = bindingKeyAndHandler.handler["init"],
  3268. handlerUpdateFn = bindingKeyAndHandler.handler["update"],
  3269. bindingKey = bindingKeyAndHandler.key;
  3270. if (node.nodeType === 8) {
  3271. validateThatBindingIsAllowedForVirtualElements(bindingKey);
  3272. }
  3273. try {
  3274. // Run init, ignoring any dependencies
  3275. if (typeof handlerInitFn == "function") {
  3276. ko.dependencyDetection.ignore(function() {
  3277. var initResult = handlerInitFn(node, getValueAccessor(bindingKey), allBindings, contextToExtend['$data'], contextToExtend);
  3278. // If this binding handler claims to control descendant bindings, make a note of this
  3279. if (initResult && initResult['controlsDescendantBindings']) {
  3280. if (bindingHandlerThatControlsDescendantBindings !== undefined)
  3281. 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.");
  3282. bindingHandlerThatControlsDescendantBindings = bindingKey;
  3283. }
  3284. });
  3285. }
  3286. // Run update in its own computed wrapper
  3287. if (typeof handlerUpdateFn == "function") {
  3288. ko.dependentObservable(
  3289. function() {
  3290. handlerUpdateFn(node, getValueAccessor(bindingKey), allBindings, contextToExtend['$data'], contextToExtend);
  3291. },
  3292. null,
  3293. { disposeWhenNodeIsRemoved: node }
  3294. );
  3295. }
  3296. } catch (ex) {
  3297. ex.message = "Unable to process binding \"" + bindingKey + ": " + bindings[bindingKey] + "\"\nMessage: " + ex.message;
  3298. throw ex;
  3299. }
  3300. });
  3301. }
  3302. var shouldBindDescendants = bindingHandlerThatControlsDescendantBindings === undefined;
  3303. return {
  3304. 'shouldBindDescendants': shouldBindDescendants,
  3305. 'bindingContextForDescendants': shouldBindDescendants && contextToExtend
  3306. };
  3307. };
  3308. ko.storedBindingContextForNode = function (node) {
  3309. var bindingInfo = ko.utils.domData.get(node, boundElementDomDataKey);
  3310. return bindingInfo && bindingInfo.context;
  3311. }
  3312. function getBindingContext(viewModelOrBindingContext, extendContextCallback) {
  3313. return viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
  3314. ? viewModelOrBindingContext
  3315. : new ko.bindingContext(viewModelOrBindingContext, undefined, undefined, extendContextCallback);
  3316. }
  3317. ko.applyBindingAccessorsToNode = function (node, bindings, viewModelOrBindingContext) {
  3318. if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
  3319. ko.virtualElements.normaliseVirtualElementDomStructure(node);
  3320. return applyBindingsToNodeInternal(node, bindings, getBindingContext(viewModelOrBindingContext));
  3321. };
  3322. ko.applyBindingsToNode = function (node, bindings, viewModelOrBindingContext) {
  3323. var context = getBindingContext(viewModelOrBindingContext);
  3324. return ko.applyBindingAccessorsToNode(node, makeBindingAccessors(bindings, context, node), context);
  3325. };
  3326. ko.applyBindingsToDescendants = function(viewModelOrBindingContext, rootNode) {
  3327. if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
  3328. applyBindingsToDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode);
  3329. };
  3330. ko.applyBindings = function (viewModelOrBindingContext, rootNode, extendContextCallback) {
  3331. // If jQuery is loaded after Knockout, we won't initially have access to it. So save it here.
  3332. if (!jQueryInstance && window['jQuery']) {
  3333. jQueryInstance = window['jQuery'];
  3334. }
  3335. if (arguments.length < 2) {
  3336. rootNode = document.body;
  3337. if (!rootNode) {
  3338. throw Error("ko.applyBindings: could not find document.body; has the document been loaded?");
  3339. }
  3340. } else if (!rootNode || (rootNode.nodeType !== 1 && rootNode.nodeType !== 8)) {
  3341. throw Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
  3342. }
  3343. applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext, extendContextCallback), rootNode);
  3344. };
  3345. // Retrieving binding context from arbitrary nodes
  3346. ko.contextFor = function(node) {
  3347. // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
  3348. if (node && (node.nodeType === 1 || node.nodeType === 8)) {
  3349. return ko.storedBindingContextForNode(node);
  3350. }
  3351. return undefined;
  3352. };
  3353. ko.dataFor = function(node) {
  3354. var context = ko.contextFor(node);
  3355. return context ? context['$data'] : undefined;
  3356. };
  3357. ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
  3358. ko.exportSymbol('bindingEvent', ko.bindingEvent);
  3359. ko.exportSymbol('bindingEvent.subscribe', ko.bindingEvent.subscribe);
  3360. ko.exportSymbol('bindingEvent.startPossiblyAsyncContentBinding', ko.bindingEvent.startPossiblyAsyncContentBinding);
  3361. ko.exportSymbol('applyBindings', ko.applyBindings);
  3362. ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
  3363. ko.exportSymbol('applyBindingAccessorsToNode', ko.applyBindingAccessorsToNode);
  3364. ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
  3365. ko.exportSymbol('contextFor', ko.contextFor);
  3366. ko.exportSymbol('dataFor', ko.dataFor);
  3367. })();
  3368. (function(undefined) {
  3369. var loadingSubscribablesCache = {}, // Tracks component loads that are currently in flight
  3370. loadedDefinitionsCache = {}; // Tracks component loads that have already completed
  3371. ko.components = {
  3372. get: function(componentName, callback) {
  3373. var cachedDefinition = getObjectOwnProperty(loadedDefinitionsCache, componentName);
  3374. if (cachedDefinition) {
  3375. // It's already loaded and cached. Reuse the same definition object.
  3376. // Note that for API consistency, even cache hits complete asynchronously by default.
  3377. // You can bypass this by putting synchronous:true on your component config.
  3378. if (cachedDefinition.isSynchronousComponent) {
  3379. ko.dependencyDetection.ignore(function() { // See comment in loaderRegistryBehaviors.js for reasoning
  3380. callback(cachedDefinition.definition);
  3381. });
  3382. } else {
  3383. ko.tasks.schedule(function() { callback(cachedDefinition.definition); });
  3384. }
  3385. } else {
  3386. // Join the loading process that is already underway, or start a new one.
  3387. loadComponentAndNotify(componentName, callback);
  3388. }
  3389. },
  3390. clearCachedDefinition: function(componentName) {
  3391. delete loadedDefinitionsCache[componentName];
  3392. },
  3393. _getFirstResultFromLoaders: getFirstResultFromLoaders
  3394. };
  3395. function getObjectOwnProperty(obj, propName) {
  3396. return Object.prototype.hasOwnProperty.call(obj, propName) ? obj[propName] : undefined;
  3397. }
  3398. function loadComponentAndNotify(componentName, callback) {
  3399. var subscribable = getObjectOwnProperty(loadingSubscribablesCache, componentName),
  3400. completedAsync;
  3401. if (!subscribable) {
  3402. // It's not started loading yet. Start loading, and when it's done, move it to loadedDefinitionsCache.
  3403. subscribable = loadingSubscribablesCache[componentName] = new ko.subscribable();
  3404. subscribable.subscribe(callback);
  3405. beginLoadingComponent(componentName, function(definition, config) {
  3406. var isSynchronousComponent = !!(config && config['synchronous']);
  3407. loadedDefinitionsCache[componentName] = { definition: definition, isSynchronousComponent: isSynchronousComponent };
  3408. delete loadingSubscribablesCache[componentName];
  3409. // For API consistency, all loads complete asynchronously. However we want to avoid
  3410. // adding an extra task schedule if it's unnecessary (i.e., the completion is already
  3411. // async).
  3412. //
  3413. // You can bypass the 'always asynchronous' feature by putting the synchronous:true
  3414. // flag on your component configuration when you register it.
  3415. if (completedAsync || isSynchronousComponent) {
  3416. // Note that notifySubscribers ignores any dependencies read within the callback.
  3417. // See comment in loaderRegistryBehaviors.js for reasoning
  3418. subscribable['notifySubscribers'](definition);
  3419. } else {
  3420. ko.tasks.schedule(function() {
  3421. subscribable['notifySubscribers'](definition);
  3422. });
  3423. }
  3424. });
  3425. completedAsync = true;
  3426. } else {
  3427. subscribable.subscribe(callback);
  3428. }
  3429. }
  3430. function beginLoadingComponent(componentName, callback) {
  3431. getFirstResultFromLoaders('getConfig', [componentName], function(config) {
  3432. if (config) {
  3433. // We have a config, so now load its definition
  3434. getFirstResultFromLoaders('loadComponent', [componentName, config], function(definition) {
  3435. callback(definition, config);
  3436. });
  3437. } else {
  3438. // The component has no config - it's unknown to all the loaders.
  3439. // Note that this is not an error (e.g., a module loading error) - that would abort the
  3440. // process and this callback would not run. For this callback to run, all loaders must
  3441. // have confirmed they don't know about this component.
  3442. callback(null, null);
  3443. }
  3444. });
  3445. }
  3446. function getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders) {
  3447. // On the first call in the stack, start with the full set of loaders
  3448. if (!candidateLoaders) {
  3449. candidateLoaders = ko.components['loaders'].slice(0); // Use a copy, because we'll be mutating this array
  3450. }
  3451. // Try the next candidate
  3452. var currentCandidateLoader = candidateLoaders.shift();
  3453. if (currentCandidateLoader) {
  3454. var methodInstance = currentCandidateLoader[methodName];
  3455. if (methodInstance) {
  3456. var wasAborted = false,
  3457. synchronousReturnValue = methodInstance.apply(currentCandidateLoader, argsExceptCallback.concat(function(result) {
  3458. if (wasAborted) {
  3459. callback(null);
  3460. } else if (result !== null) {
  3461. // This candidate returned a value. Use it.
  3462. callback(result);
  3463. } else {
  3464. // Try the next candidate
  3465. getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);
  3466. }
  3467. }));
  3468. // Currently, loaders may not return anything synchronously. This leaves open the possibility
  3469. // that we'll extend the API to support synchronous return values in the future. It won't be
  3470. // a breaking change, because currently no loader is allowed to return anything except undefined.
  3471. if (synchronousReturnValue !== undefined) {
  3472. wasAborted = true;
  3473. // Method to suppress exceptions will remain undocumented. This is only to keep
  3474. // KO's specs running tidily, since we can observe the loading got aborted without
  3475. // having exceptions cluttering up the console too.
  3476. if (!currentCandidateLoader['suppressLoaderExceptions']) {
  3477. throw new Error('Component loaders must supply values by invoking the callback, not by returning values synchronously.');
  3478. }
  3479. }
  3480. } else {
  3481. // This candidate doesn't have the relevant handler. Synchronously move on to the next one.
  3482. getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);
  3483. }
  3484. } else {
  3485. // No candidates returned a value
  3486. callback(null);
  3487. }
  3488. }
  3489. // Reference the loaders via string name so it's possible for developers
  3490. // to replace the whole array by assigning to ko.components.loaders
  3491. ko.components['loaders'] = [];
  3492. ko.exportSymbol('components', ko.components);
  3493. ko.exportSymbol('components.get', ko.components.get);
  3494. ko.exportSymbol('components.clearCachedDefinition', ko.components.clearCachedDefinition);
  3495. })();
  3496. (function(undefined) {
  3497. // The default loader is responsible for two things:
  3498. // 1. Maintaining the default in-memory registry of component configuration objects
  3499. // (i.e., the thing you're writing to when you call ko.components.register(someName, ...))
  3500. // 2. Answering requests for components by fetching configuration objects
  3501. // from that default in-memory registry and resolving them into standard
  3502. // component definition objects (of the form { createViewModel: ..., template: ... })
  3503. // Custom loaders may override either of these facilities, i.e.,
  3504. // 1. To supply configuration objects from some other source (e.g., conventions)
  3505. // 2. Or, to resolve configuration objects by loading viewmodels/templates via arbitrary logic.
  3506. var defaultConfigRegistry = {};
  3507. ko.components.register = function(componentName, config) {
  3508. if (!config) {
  3509. throw new Error('Invalid configuration for ' + componentName);
  3510. }
  3511. if (ko.components.isRegistered(componentName)) {
  3512. throw new Error('Component ' + componentName + ' is already registered');
  3513. }
  3514. defaultConfigRegistry[componentName] = config;
  3515. };
  3516. ko.components.isRegistered = function(componentName) {
  3517. return Object.prototype.hasOwnProperty.call(defaultConfigRegistry, componentName);
  3518. };
  3519. ko.components.unregister = function(componentName) {
  3520. delete defaultConfigRegistry[componentName];
  3521. ko.components.clearCachedDefinition(componentName);
  3522. };
  3523. ko.components.defaultLoader = {
  3524. 'getConfig': function(componentName, callback) {
  3525. var result = ko.components.isRegistered(componentName)
  3526. ? defaultConfigRegistry[componentName]
  3527. : null;
  3528. callback(result);
  3529. },
  3530. 'loadComponent': function(componentName, config, callback) {
  3531. var errorCallback = makeErrorCallback(componentName);
  3532. possiblyGetConfigFromAmd(errorCallback, config, function(loadedConfig) {
  3533. resolveConfig(componentName, errorCallback, loadedConfig, callback);
  3534. });
  3535. },
  3536. 'loadTemplate': function(componentName, templateConfig, callback) {
  3537. resolveTemplate(makeErrorCallback(componentName), templateConfig, callback);
  3538. },
  3539. 'loadViewModel': function(componentName, viewModelConfig, callback) {
  3540. resolveViewModel(makeErrorCallback(componentName), viewModelConfig, callback);
  3541. }
  3542. };
  3543. var createViewModelKey = 'createViewModel';
  3544. // Takes a config object of the form { template: ..., viewModel: ... }, and asynchronously convert it
  3545. // into the standard component definition format:
  3546. // { template: <ArrayOfDomNodes>, createViewModel: function(params, componentInfo) { ... } }.
  3547. // Since both template and viewModel may need to be resolved asynchronously, both tasks are performed
  3548. // in parallel, and the results joined when both are ready. We don't depend on any promises infrastructure,
  3549. // so this is implemented manually below.
  3550. function resolveConfig(componentName, errorCallback, config, callback) {
  3551. var result = {},
  3552. makeCallBackWhenZero = 2,
  3553. tryIssueCallback = function() {
  3554. if (--makeCallBackWhenZero === 0) {
  3555. callback(result);
  3556. }
  3557. },
  3558. templateConfig = config['template'],
  3559. viewModelConfig = config['viewModel'];
  3560. if (templateConfig) {
  3561. possiblyGetConfigFromAmd(errorCallback, templateConfig, function(loadedConfig) {
  3562. ko.components._getFirstResultFromLoaders('loadTemplate', [componentName, loadedConfig], function(resolvedTemplate) {
  3563. result['template'] = resolvedTemplate;
  3564. tryIssueCallback();
  3565. });
  3566. });
  3567. } else {
  3568. tryIssueCallback();
  3569. }
  3570. if (viewModelConfig) {
  3571. possiblyGetConfigFromAmd(errorCallback, viewModelConfig, function(loadedConfig) {
  3572. ko.components._getFirstResultFromLoaders('loadViewModel', [componentName, loadedConfig], function(resolvedViewModel) {
  3573. result[createViewModelKey] = resolvedViewModel;
  3574. tryIssueCallback();
  3575. });
  3576. });
  3577. } else {
  3578. tryIssueCallback();
  3579. }
  3580. }
  3581. function resolveTemplate(errorCallback, templateConfig, callback) {
  3582. if (typeof templateConfig === 'string') {
  3583. // Markup - parse it
  3584. callback(ko.utils.parseHtmlFragment(templateConfig));
  3585. } else if (templateConfig instanceof Array) {
  3586. // Assume already an array of DOM nodes - pass through unchanged
  3587. callback(templateConfig);
  3588. } else if (isDocumentFragment(templateConfig)) {
  3589. // Document fragment - use its child nodes
  3590. callback(ko.utils.makeArray(templateConfig.childNodes));
  3591. } else if (templateConfig['element']) {
  3592. var element = templateConfig['element'];
  3593. if (isDomElement(element)) {
  3594. // Element instance - copy its child nodes
  3595. callback(cloneNodesFromTemplateSourceElement(element));
  3596. } else if (typeof element === 'string') {
  3597. // Element ID - find it, then copy its child nodes
  3598. var elemInstance = document.getElementById(element);
  3599. if (elemInstance) {
  3600. callback(cloneNodesFromTemplateSourceElement(elemInstance));
  3601. } else {
  3602. errorCallback('Cannot find element with ID ' + element);
  3603. }
  3604. } else {
  3605. errorCallback('Unknown element type: ' + element);
  3606. }
  3607. } else {
  3608. errorCallback('Unknown template value: ' + templateConfig);
  3609. }
  3610. }
  3611. function resolveViewModel(errorCallback, viewModelConfig, callback) {
  3612. if (typeof viewModelConfig === 'function') {
  3613. // Constructor - convert to standard factory function format
  3614. // By design, this does *not* supply componentInfo to the constructor, as the intent is that
  3615. // componentInfo contains non-viewmodel data (e.g., the component's element) that should only
  3616. // be used in factory functions, not viewmodel constructors.
  3617. callback(function (params /*, componentInfo */) {
  3618. return new viewModelConfig(params);
  3619. });
  3620. } else if (typeof viewModelConfig[createViewModelKey] === 'function') {
  3621. // Already a factory function - use it as-is
  3622. callback(viewModelConfig[createViewModelKey]);
  3623. } else if ('instance' in viewModelConfig) {
  3624. // Fixed object instance - promote to createViewModel format for API consistency
  3625. var fixedInstance = viewModelConfig['instance'];
  3626. callback(function (params, componentInfo) {
  3627. return fixedInstance;
  3628. });
  3629. } else if ('viewModel' in viewModelConfig) {
  3630. // Resolved AMD module whose value is of the form { viewModel: ... }
  3631. resolveViewModel(errorCallback, viewModelConfig['viewModel'], callback);
  3632. } else {
  3633. errorCallback('Unknown viewModel value: ' + viewModelConfig);
  3634. }
  3635. }
  3636. function cloneNodesFromTemplateSourceElement(elemInstance) {
  3637. switch (ko.utils.tagNameLower(elemInstance)) {
  3638. case 'script':
  3639. return ko.utils.parseHtmlFragment(elemInstance.text);
  3640. case 'textarea':
  3641. return ko.utils.parseHtmlFragment(elemInstance.value);
  3642. case 'template':
  3643. // For browsers with proper <template> element support (i.e., where the .content property
  3644. // gives a document fragment), use that document fragment.
  3645. if (isDocumentFragment(elemInstance.content)) {
  3646. return ko.utils.cloneNodes(elemInstance.content.childNodes);
  3647. }
  3648. }
  3649. // Regular elements such as <div>, and <template> elements on old browsers that don't really
  3650. // understand <template> and just treat it as a regular container
  3651. return ko.utils.cloneNodes(elemInstance.childNodes);
  3652. }
  3653. function isDomElement(obj) {
  3654. if (window['HTMLElement']) {
  3655. return obj instanceof HTMLElement;
  3656. } else {
  3657. return obj && obj.tagName && obj.nodeType === 1;
  3658. }
  3659. }
  3660. function isDocumentFragment(obj) {
  3661. if (window['DocumentFragment']) {
  3662. return obj instanceof DocumentFragment;
  3663. } else {
  3664. return obj && obj.nodeType === 11;
  3665. }
  3666. }
  3667. function possiblyGetConfigFromAmd(errorCallback, config, callback) {
  3668. if (typeof config['require'] === 'string') {
  3669. // The config is the value of an AMD module
  3670. if (amdRequire || window['require']) {
  3671. (amdRequire || window['require'])([config['require']], function (module) {
  3672. if (module && typeof module === 'object' && module.__esModule && module.default) {
  3673. module = module.default;
  3674. }
  3675. callback(module);
  3676. });
  3677. } else {
  3678. errorCallback('Uses require, but no AMD loader is present');
  3679. }
  3680. } else {
  3681. callback(config);
  3682. }
  3683. }
  3684. function makeErrorCallback(componentName) {
  3685. return function (message) {
  3686. throw new Error('Component \'' + componentName + '\': ' + message);
  3687. };
  3688. }
  3689. ko.exportSymbol('components.register', ko.components.register);
  3690. ko.exportSymbol('components.isRegistered', ko.components.isRegistered);
  3691. ko.exportSymbol('components.unregister', ko.components.unregister);
  3692. // Expose the default loader so that developers can directly ask it for configuration
  3693. // or to resolve configuration
  3694. ko.exportSymbol('components.defaultLoader', ko.components.defaultLoader);
  3695. // By default, the default loader is the only registered component loader
  3696. ko.components['loaders'].push(ko.components.defaultLoader);
  3697. // Privately expose the underlying config registry for use in old-IE shim
  3698. ko.components._allRegisteredComponents = defaultConfigRegistry;
  3699. })();
  3700. (function (undefined) {
  3701. // Overridable API for determining which component name applies to a given node. By overriding this,
  3702. // you can for example map specific tagNames to components that are not preregistered.
  3703. ko.components['getComponentNameForNode'] = function(node) {
  3704. var tagNameLower = ko.utils.tagNameLower(node);
  3705. if (ko.components.isRegistered(tagNameLower)) {
  3706. // Try to determine that this node can be considered a *custom* element; see https://github.com/knockout/knockout/issues/1603
  3707. if (tagNameLower.indexOf('-') != -1 || ('' + node) == "[object HTMLUnknownElement]" || (ko.utils.ieVersion <= 8 && node.tagName === tagNameLower)) {
  3708. return tagNameLower;
  3709. }
  3710. }
  3711. };
  3712. ko.components.addBindingsForCustomElement = function(allBindings, node, bindingContext, valueAccessors) {
  3713. // Determine if it's really a custom element matching a component
  3714. if (node.nodeType === 1) {
  3715. var componentName = ko.components['getComponentNameForNode'](node);
  3716. if (componentName) {
  3717. // It does represent a component, so add a component binding for it
  3718. allBindings = allBindings || {};
  3719. if (allBindings['component']) {
  3720. // Avoid silently overwriting some other 'component' binding that may already be on the element
  3721. throw new Error('Cannot use the "component" binding on a custom element matching a component');
  3722. }
  3723. var componentBindingValue = { 'name': componentName, 'params': getComponentParamsFromCustomElement(node, bindingContext) };
  3724. allBindings['component'] = valueAccessors
  3725. ? function() { return componentBindingValue; }
  3726. : componentBindingValue;
  3727. }
  3728. }
  3729. return allBindings;
  3730. }
  3731. var nativeBindingProviderInstance = new ko.bindingProvider();
  3732. function getComponentParamsFromCustomElement(elem, bindingContext) {
  3733. var paramsAttribute = elem.getAttribute('params');
  3734. if (paramsAttribute) {
  3735. var params = nativeBindingProviderInstance['parseBindingsString'](paramsAttribute, bindingContext, elem, { 'valueAccessors': true, 'bindingParams': true }),
  3736. rawParamComputedValues = ko.utils.objectMap(params, function(paramValue, paramName) {
  3737. return ko.computed(paramValue, null, { disposeWhenNodeIsRemoved: elem });
  3738. }),
  3739. result = ko.utils.objectMap(rawParamComputedValues, function(paramValueComputed, paramName) {
  3740. var paramValue = paramValueComputed.peek();
  3741. // Does the evaluation of the parameter value unwrap any observables?
  3742. if (!paramValueComputed.isActive()) {
  3743. // No it doesn't, so there's no need for any computed wrapper. Just pass through the supplied value directly.
  3744. // Example: "someVal: firstName, age: 123" (whether or not firstName is an observable/computed)
  3745. return paramValue;
  3746. } else {
  3747. // Yes it does. Supply a computed property that unwraps both the outer (binding expression)
  3748. // level of observability, and any inner (resulting model value) level of observability.
  3749. // This means the component doesn't have to worry about multiple unwrapping. If the value is a
  3750. // writable observable, the computed will also be writable and pass the value on to the observable.
  3751. return ko.computed({
  3752. 'read': function() {
  3753. return ko.utils.unwrapObservable(paramValueComputed());
  3754. },
  3755. 'write': ko.isWriteableObservable(paramValue) && function(value) {
  3756. paramValueComputed()(value);
  3757. },
  3758. disposeWhenNodeIsRemoved: elem
  3759. });
  3760. }
  3761. });
  3762. // Give access to the raw computeds, as long as that wouldn't overwrite any custom param also called '$raw'
  3763. // This is in case the developer wants to react to outer (binding) observability separately from inner
  3764. // (model value) observability, or in case the model value observable has subobservables.
  3765. if (!Object.prototype.hasOwnProperty.call(result, '$raw')) {
  3766. result['$raw'] = rawParamComputedValues;
  3767. }
  3768. return result;
  3769. } else {
  3770. // For consistency, absence of a "params" attribute is treated the same as the presence of
  3771. // any empty one. Otherwise component viewmodels need special code to check whether or not
  3772. // 'params' or 'params.$raw' is null/undefined before reading subproperties, which is annoying.
  3773. return { '$raw': {} };
  3774. }
  3775. }
  3776. // --------------------------------------------------------------------------------
  3777. // Compatibility code for older (pre-HTML5) IE browsers
  3778. if (ko.utils.ieVersion < 9) {
  3779. // Whenever you preregister a component, enable it as a custom element in the current document
  3780. ko.components['register'] = (function(originalFunction) {
  3781. return function(componentName) {
  3782. document.createElement(componentName); // Allows IE<9 to parse markup containing the custom element
  3783. return originalFunction.apply(this, arguments);
  3784. }
  3785. })(ko.components['register']);
  3786. // Whenever you create a document fragment, enable all preregistered component names as custom elements
  3787. // This is needed to make innerShiv/jQuery HTML parsing correctly handle the custom elements
  3788. document.createDocumentFragment = (function(originalFunction) {
  3789. return function() {
  3790. var newDocFrag = originalFunction(),
  3791. allComponents = ko.components._allRegisteredComponents;
  3792. for (var componentName in allComponents) {
  3793. if (Object.prototype.hasOwnProperty.call(allComponents, componentName)) {
  3794. newDocFrag.createElement(componentName);
  3795. }
  3796. }
  3797. return newDocFrag;
  3798. };
  3799. })(document.createDocumentFragment);
  3800. }
  3801. })();(function(undefined) {
  3802. var componentLoadingOperationUniqueId = 0;
  3803. ko.bindingHandlers['component'] = {
  3804. 'init': function(element, valueAccessor, ignored1, ignored2, bindingContext) {
  3805. var currentViewModel,
  3806. currentLoadingOperationId,
  3807. afterRenderSub,
  3808. disposeAssociatedComponentViewModel = function () {
  3809. var currentViewModelDispose = currentViewModel && currentViewModel['dispose'];
  3810. if (typeof currentViewModelDispose === 'function') {
  3811. currentViewModelDispose.call(currentViewModel);
  3812. }
  3813. if (afterRenderSub) {
  3814. afterRenderSub.dispose();
  3815. }
  3816. afterRenderSub = null;
  3817. currentViewModel = null;
  3818. // Any in-flight loading operation is no longer relevant, so make sure we ignore its completion
  3819. currentLoadingOperationId = null;
  3820. },
  3821. originalChildNodes = ko.utils.makeArray(ko.virtualElements.childNodes(element));
  3822. ko.virtualElements.emptyNode(element);
  3823. ko.utils.domNodeDisposal.addDisposeCallback(element, disposeAssociatedComponentViewModel);
  3824. ko.computed(function () {
  3825. var value = ko.utils.unwrapObservable(valueAccessor()),
  3826. componentName, componentParams;
  3827. if (typeof value === 'string') {
  3828. componentName = value;
  3829. } else {
  3830. componentName = ko.utils.unwrapObservable(value['name']);
  3831. componentParams = ko.utils.unwrapObservable(value['params']);
  3832. }
  3833. if (!componentName) {
  3834. throw new Error('No component name specified');
  3835. }
  3836. var asyncContext = ko.bindingEvent.startPossiblyAsyncContentBinding(element, bindingContext);
  3837. var loadingOperationId = currentLoadingOperationId = ++componentLoadingOperationUniqueId;
  3838. ko.components.get(componentName, function(componentDefinition) {
  3839. // If this is not the current load operation for this element, ignore it.
  3840. if (currentLoadingOperationId !== loadingOperationId) {
  3841. return;
  3842. }
  3843. // Clean up previous state
  3844. disposeAssociatedComponentViewModel();
  3845. // Instantiate and bind new component. Implicitly this cleans any old DOM nodes.
  3846. if (!componentDefinition) {
  3847. throw new Error('Unknown component \'' + componentName + '\'');
  3848. }
  3849. cloneTemplateIntoElement(componentName, componentDefinition, element);
  3850. var componentInfo = {
  3851. 'element': element,
  3852. 'templateNodes': originalChildNodes
  3853. };
  3854. var componentViewModel = createViewModel(componentDefinition, componentParams, componentInfo),
  3855. childBindingContext = asyncContext['createChildContext'](componentViewModel, {
  3856. 'extend': function(ctx) {
  3857. ctx['$component'] = componentViewModel;
  3858. ctx['$componentTemplateNodes'] = originalChildNodes;
  3859. }
  3860. });
  3861. if (componentViewModel && componentViewModel['koDescendantsComplete']) {
  3862. afterRenderSub = ko.bindingEvent.subscribe(element, ko.bindingEvent.descendantsComplete, componentViewModel['koDescendantsComplete'], componentViewModel);
  3863. }
  3864. currentViewModel = componentViewModel;
  3865. ko.applyBindingsToDescendants(childBindingContext, element);
  3866. });
  3867. }, null, { disposeWhenNodeIsRemoved: element });
  3868. return { 'controlsDescendantBindings': true };
  3869. }
  3870. };
  3871. ko.virtualElements.allowedBindings['component'] = true;
  3872. function cloneTemplateIntoElement(componentName, componentDefinition, element) {
  3873. var template = componentDefinition['template'];
  3874. if (!template) {
  3875. throw new Error('Component \'' + componentName + '\' has no template');
  3876. }
  3877. var clonedNodesArray = ko.utils.cloneNodes(template);
  3878. ko.virtualElements.setDomNodeChildren(element, clonedNodesArray);
  3879. }
  3880. function createViewModel(componentDefinition, componentParams, componentInfo) {
  3881. var componentViewModelFactory = componentDefinition['createViewModel'];
  3882. return componentViewModelFactory
  3883. ? componentViewModelFactory.call(componentDefinition, componentParams, componentInfo)
  3884. : componentParams; // Template-only component
  3885. }
  3886. })();
  3887. var attrHtmlToJavaScriptMap = { 'class': 'className', 'for': 'htmlFor' };
  3888. ko.bindingHandlers['attr'] = {
  3889. 'update': function(element, valueAccessor, allBindings) {
  3890. var value = ko.utils.unwrapObservable(valueAccessor()) || {};
  3891. ko.utils.objectForEach(value, function(attrName, attrValue) {
  3892. attrValue = ko.utils.unwrapObservable(attrValue);
  3893. // Find the namespace of this attribute, if any.
  3894. var prefixLen = attrName.indexOf(':');
  3895. var namespace = "lookupNamespaceURI" in element && prefixLen > 0 && element.lookupNamespaceURI(attrName.substr(0, prefixLen));
  3896. // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
  3897. // when someProp is a "no value"-like value (strictly null, false, or undefined)
  3898. // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
  3899. var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
  3900. if (toRemove) {
  3901. namespace ? element.removeAttributeNS(namespace, attrName) : element.removeAttribute(attrName);
  3902. } else {
  3903. attrValue = attrValue.toString();
  3904. }
  3905. // In IE <= 7 and IE8 Quirks Mode, you have to use the JavaScript property name instead of the
  3906. // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
  3907. // but instead of figuring out the mode, we'll just set the attribute through the JavaScript
  3908. // property for IE <= 8.
  3909. if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavaScriptMap) {
  3910. attrName = attrHtmlToJavaScriptMap[attrName];
  3911. if (toRemove)
  3912. element.removeAttribute(attrName);
  3913. else
  3914. element[attrName] = attrValue;
  3915. } else if (!toRemove) {
  3916. namespace ? element.setAttributeNS(namespace, attrName, attrValue) : element.setAttribute(attrName, attrValue);
  3917. }
  3918. // Treat "name" specially - although you can think of it as an attribute, it also needs
  3919. // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
  3920. // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
  3921. // entirely, and there's no strong reason to allow for such casing in HTML.
  3922. if (attrName === "name") {
  3923. ko.utils.setElementName(element, toRemove ? "" : attrValue);
  3924. }
  3925. });
  3926. }
  3927. };
  3928. (function() {
  3929. ko.bindingHandlers['checked'] = {
  3930. 'after': ['value', 'attr'],
  3931. 'init': function (element, valueAccessor, allBindings) {
  3932. var checkedValue = ko.pureComputed(function() {
  3933. // Treat "value" like "checkedValue" when it is included with "checked" binding
  3934. if (allBindings['has']('checkedValue')) {
  3935. return ko.utils.unwrapObservable(allBindings.get('checkedValue'));
  3936. } else if (useElementValue) {
  3937. if (allBindings['has']('value')) {
  3938. return ko.utils.unwrapObservable(allBindings.get('value'));
  3939. } else {
  3940. return element.value;
  3941. }
  3942. }
  3943. });
  3944. function updateModel() {
  3945. // This updates the model value from the view value.
  3946. // It runs in response to DOM events (click) and changes in checkedValue.
  3947. var isChecked = element.checked,
  3948. elemValue = checkedValue();
  3949. // When we're first setting up this computed, don't change any model state.
  3950. if (ko.computedContext.isInitial()) {
  3951. return;
  3952. }
  3953. // We can ignore unchecked radio buttons, because some other radio
  3954. // button will be checked, and that one can take care of updating state.
  3955. // Also ignore value changes to an already unchecked checkbox.
  3956. if (!isChecked && (isRadio || ko.computedContext.getDependenciesCount())) {
  3957. return;
  3958. }
  3959. var modelValue = ko.dependencyDetection.ignore(valueAccessor);
  3960. if (valueIsArray) {
  3961. var writableValue = rawValueIsNonArrayObservable ? modelValue.peek() : modelValue,
  3962. saveOldValue = oldElemValue;
  3963. oldElemValue = elemValue;
  3964. if (saveOldValue !== elemValue) {
  3965. // When we're responding to the checkedValue changing, and the element is
  3966. // currently checked, replace the old elem value with the new elem value
  3967. // in the model array.
  3968. if (isChecked) {
  3969. ko.utils.addOrRemoveItem(writableValue, elemValue, true);
  3970. ko.utils.addOrRemoveItem(writableValue, saveOldValue, false);
  3971. }
  3972. } else {
  3973. // When we're responding to the user having checked/unchecked a checkbox,
  3974. // add/remove the element value to the model array.
  3975. ko.utils.addOrRemoveItem(writableValue, elemValue, isChecked);
  3976. }
  3977. if (rawValueIsNonArrayObservable && ko.isWriteableObservable(modelValue)) {
  3978. modelValue(writableValue);
  3979. }
  3980. } else {
  3981. if (isCheckbox) {
  3982. if (elemValue === undefined) {
  3983. elemValue = isChecked;
  3984. } else if (!isChecked) {
  3985. elemValue = undefined;
  3986. }
  3987. }
  3988. ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'checked', elemValue, true);
  3989. }
  3990. };
  3991. function updateView() {
  3992. // This updates the view value from the model value.
  3993. // It runs in response to changes in the bound (checked) value.
  3994. var modelValue = ko.utils.unwrapObservable(valueAccessor()),
  3995. elemValue = checkedValue();
  3996. if (valueIsArray) {
  3997. // When a checkbox is bound to an array, being checked represents its value being present in that array
  3998. element.checked = ko.utils.arrayIndexOf(modelValue, elemValue) >= 0;
  3999. oldElemValue = elemValue;
  4000. } else if (isCheckbox && elemValue === undefined) {
  4001. // When a checkbox is bound to any other value (not an array) and "checkedValue" is not defined,
  4002. // being checked represents the value being trueish
  4003. element.checked = !!modelValue;
  4004. } else {
  4005. // Otherwise, being checked means that the checkbox or radio button's value corresponds to the model value
  4006. element.checked = (checkedValue() === modelValue);
  4007. }
  4008. };
  4009. var isCheckbox = element.type == "checkbox",
  4010. isRadio = element.type == "radio";
  4011. // Only bind to check boxes and radio buttons
  4012. if (!isCheckbox && !isRadio) {
  4013. return;
  4014. }
  4015. var rawValue = valueAccessor(),
  4016. valueIsArray = isCheckbox && (ko.utils.unwrapObservable(rawValue) instanceof Array),
  4017. rawValueIsNonArrayObservable = !(valueIsArray && rawValue.push && rawValue.splice),
  4018. useElementValue = isRadio || valueIsArray,
  4019. oldElemValue = valueIsArray ? checkedValue() : undefined;
  4020. // IE 6 won't allow radio buttons to be selected unless they have a name
  4021. if (isRadio && !element.name)
  4022. ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
  4023. // Set up two computeds to update the binding:
  4024. // The first responds to changes in the checkedValue value and to element clicks
  4025. ko.computed(updateModel, null, { disposeWhenNodeIsRemoved: element });
  4026. ko.utils.registerEventHandler(element, "click", updateModel);
  4027. // The second responds to changes in the model value (the one associated with the checked binding)
  4028. ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
  4029. rawValue = undefined;
  4030. }
  4031. };
  4032. ko.expressionRewriting.twoWayBindings['checked'] = true;
  4033. ko.bindingHandlers['checkedValue'] = {
  4034. 'update': function (element, valueAccessor) {
  4035. element.value = ko.utils.unwrapObservable(valueAccessor());
  4036. }
  4037. };
  4038. })();var classesWrittenByBindingKey = '__ko__cssValue';
  4039. ko.bindingHandlers['class'] = {
  4040. 'update': function (element, valueAccessor) {
  4041. var value = ko.utils.stringTrim(ko.utils.unwrapObservable(valueAccessor()));
  4042. ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
  4043. element[classesWrittenByBindingKey] = value;
  4044. ko.utils.toggleDomNodeCssClass(element, value, true);
  4045. }
  4046. };
  4047. ko.bindingHandlers['css'] = {
  4048. 'update': function (element, valueAccessor) {
  4049. var value = ko.utils.unwrapObservable(valueAccessor());
  4050. if (value !== null && typeof value == "object") {
  4051. ko.utils.objectForEach(value, function(className, shouldHaveClass) {
  4052. shouldHaveClass = ko.utils.unwrapObservable(shouldHaveClass);
  4053. ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
  4054. });
  4055. } else {
  4056. ko.bindingHandlers['class']['update'](element, valueAccessor);
  4057. }
  4058. }
  4059. };
  4060. ko.bindingHandlers['enable'] = {
  4061. 'update': function (element, valueAccessor) {
  4062. var value = ko.utils.unwrapObservable(valueAccessor());
  4063. if (value && element.disabled)
  4064. element.removeAttribute("disabled");
  4065. else if ((!value) && (!element.disabled))
  4066. element.disabled = true;
  4067. }
  4068. };
  4069. ko.bindingHandlers['disable'] = {
  4070. 'update': function (element, valueAccessor) {
  4071. ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
  4072. }
  4073. };
  4074. // For certain common events (currently just 'click'), allow a simplified data-binding syntax
  4075. // e.g. click:handler instead of the usual full-length event:{click:handler}
  4076. function makeEventHandlerShortcut(eventName) {
  4077. ko.bindingHandlers[eventName] = {
  4078. 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  4079. var newValueAccessor = function () {
  4080. var result = {};
  4081. result[eventName] = valueAccessor();
  4082. return result;
  4083. };
  4084. return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindings, viewModel, bindingContext);
  4085. }
  4086. }
  4087. }
  4088. ko.bindingHandlers['event'] = {
  4089. 'init' : function (element, valueAccessor, allBindings, viewModel, bindingContext) {
  4090. var eventsToHandle = valueAccessor() || {};
  4091. ko.utils.objectForEach(eventsToHandle, function(eventName) {
  4092. if (typeof eventName == "string") {
  4093. ko.utils.registerEventHandler(element, eventName, function (event) {
  4094. var handlerReturnValue;
  4095. var handlerFunction = valueAccessor()[eventName];
  4096. if (!handlerFunction)
  4097. return;
  4098. try {
  4099. // Take all the event args, and prefix with the viewmodel
  4100. var argsForHandler = ko.utils.makeArray(arguments);
  4101. viewModel = bindingContext['$data'];
  4102. argsForHandler.unshift(viewModel);
  4103. handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
  4104. } finally {
  4105. if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
  4106. if (event.preventDefault)
  4107. event.preventDefault();
  4108. else
  4109. event.returnValue = false;
  4110. }
  4111. }
  4112. var bubble = allBindings.get(eventName + 'Bubble') !== false;
  4113. if (!bubble) {
  4114. event.cancelBubble = true;
  4115. if (event.stopPropagation)
  4116. event.stopPropagation();
  4117. }
  4118. });
  4119. }
  4120. });
  4121. }
  4122. };
  4123. // "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
  4124. // "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
  4125. ko.bindingHandlers['foreach'] = {
  4126. makeTemplateValueAccessor: function(valueAccessor) {
  4127. return function() {
  4128. var modelValue = valueAccessor(),
  4129. unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
  4130. // If unwrappedValue is the array, pass in the wrapped value on its own
  4131. // The value will be unwrapped and tracked within the template binding
  4132. // (See https://github.com/SteveSanderson/knockout/issues/523)
  4133. if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
  4134. return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
  4135. // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
  4136. ko.utils.unwrapObservable(modelValue);
  4137. return {
  4138. 'foreach': unwrappedValue['data'],
  4139. 'as': unwrappedValue['as'],
  4140. 'noChildContext': unwrappedValue['noChildContext'],
  4141. 'includeDestroyed': unwrappedValue['includeDestroyed'],
  4142. 'afterAdd': unwrappedValue['afterAdd'],
  4143. 'beforeRemove': unwrappedValue['beforeRemove'],
  4144. 'afterRender': unwrappedValue['afterRender'],
  4145. 'beforeMove': unwrappedValue['beforeMove'],
  4146. 'afterMove': unwrappedValue['afterMove'],
  4147. 'templateEngine': ko.nativeTemplateEngine.instance
  4148. };
  4149. };
  4150. },
  4151. 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  4152. return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
  4153. },
  4154. 'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  4155. return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindings, viewModel, bindingContext);
  4156. }
  4157. };
  4158. ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
  4159. ko.virtualElements.allowedBindings['foreach'] = true;
  4160. var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
  4161. var hasfocusLastValue = '__ko_hasfocusLastValue';
  4162. ko.bindingHandlers['hasfocus'] = {
  4163. 'init': function(element, valueAccessor, allBindings) {
  4164. var handleElementFocusChange = function(isFocused) {
  4165. // Where possible, ignore which event was raised and determine focus state using activeElement,
  4166. // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
  4167. // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
  4168. // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
  4169. // from calling 'blur()' on the element when it loses focus.
  4170. // Discussion at https://github.com/SteveSanderson/knockout/pull/352
  4171. element[hasfocusUpdatingProperty] = true;
  4172. var ownerDoc = element.ownerDocument;
  4173. if ("activeElement" in ownerDoc) {
  4174. var active;
  4175. try {
  4176. active = ownerDoc.activeElement;
  4177. } catch(e) {
  4178. // IE9 throws if you access activeElement during page load (see issue #703)
  4179. active = ownerDoc.body;
  4180. }
  4181. isFocused = (active === element);
  4182. }
  4183. var modelValue = valueAccessor();
  4184. ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'hasfocus', isFocused, true);
  4185. //cache the latest value, so we can avoid unnecessarily calling focus/blur in the update function
  4186. element[hasfocusLastValue] = isFocused;
  4187. element[hasfocusUpdatingProperty] = false;
  4188. };
  4189. var handleElementFocusIn = handleElementFocusChange.bind(null, true);
  4190. var handleElementFocusOut = handleElementFocusChange.bind(null, false);
  4191. ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
  4192. ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
  4193. ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
  4194. ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
  4195. // Assume element is not focused (prevents "blur" being called initially)
  4196. element[hasfocusLastValue] = false;
  4197. },
  4198. 'update': function(element, valueAccessor) {
  4199. var value = !!ko.utils.unwrapObservable(valueAccessor());
  4200. if (!element[hasfocusUpdatingProperty] && element[hasfocusLastValue] !== value) {
  4201. value ? element.focus() : element.blur();
  4202. // In IE, the blur method doesn't always cause the element to lose focus (for example, if the window is not in focus).
  4203. // Setting focus to the body element does seem to be reliable in IE, but should only be used if we know that the current
  4204. // element was focused already.
  4205. if (!value && element[hasfocusLastValue]) {
  4206. element.ownerDocument.body.focus();
  4207. }
  4208. // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
  4209. ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]);
  4210. }
  4211. }
  4212. };
  4213. ko.expressionRewriting.twoWayBindings['hasfocus'] = true;
  4214. ko.bindingHandlers['hasFocus'] = ko.bindingHandlers['hasfocus']; // Make "hasFocus" an alias
  4215. ko.expressionRewriting.twoWayBindings['hasFocus'] = 'hasfocus';
  4216. ko.bindingHandlers['html'] = {
  4217. 'init': function() {
  4218. // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
  4219. return { 'controlsDescendantBindings': true };
  4220. },
  4221. 'update': function (element, valueAccessor) {
  4222. // setHtml will unwrap the value if needed
  4223. ko.utils.setHtml(element, valueAccessor());
  4224. }
  4225. };
  4226. (function () {
  4227. // Makes a binding like with or if
  4228. function makeWithIfBinding(bindingKey, isWith, isNot) {
  4229. ko.bindingHandlers[bindingKey] = {
  4230. 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  4231. var didDisplayOnLastUpdate, savedNodes, contextOptions = {}, completeOnRender, needAsyncContext, renderOnEveryChange;
  4232. if (isWith) {
  4233. var as = allBindings.get('as'), noChildContext = allBindings.get('noChildContext');
  4234. renderOnEveryChange = !(as && noChildContext);
  4235. contextOptions = { 'as': as, 'noChildContext': noChildContext, 'exportDependencies': renderOnEveryChange };
  4236. }
  4237. completeOnRender = allBindings.get("completeOn") == "render";
  4238. needAsyncContext = completeOnRender || allBindings['has'](ko.bindingEvent.descendantsComplete);
  4239. ko.computed(function() {
  4240. var value = ko.utils.unwrapObservable(valueAccessor()),
  4241. shouldDisplay = !isNot !== !value, // equivalent to isNot ? !value : !!value,
  4242. isInitial = !savedNodes,
  4243. childContext;
  4244. if (!renderOnEveryChange && shouldDisplay === didDisplayOnLastUpdate) {
  4245. return;
  4246. }
  4247. if (needAsyncContext) {
  4248. bindingContext = ko.bindingEvent.startPossiblyAsyncContentBinding(element, bindingContext);
  4249. }
  4250. if (shouldDisplay) {
  4251. if (!isWith || renderOnEveryChange) {
  4252. contextOptions['dataDependency'] = ko.computedContext.computed();
  4253. }
  4254. if (isWith) {
  4255. childContext = bindingContext['createChildContext'](typeof value == "function" ? value : valueAccessor, contextOptions);
  4256. } else if (ko.computedContext.getDependenciesCount()) {
  4257. childContext = bindingContext['extend'](null, contextOptions);
  4258. } else {
  4259. childContext = bindingContext;
  4260. }
  4261. }
  4262. // Save a copy of the inner nodes on the initial update, but only if we have dependencies.
  4263. if (isInitial && ko.computedContext.getDependenciesCount()) {
  4264. savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
  4265. }
  4266. if (shouldDisplay) {
  4267. if (!isInitial) {
  4268. ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes));
  4269. }
  4270. ko.applyBindingsToDescendants(childContext, element);
  4271. } else {
  4272. ko.virtualElements.emptyNode(element);
  4273. if (!completeOnRender) {
  4274. ko.bindingEvent.notify(element, ko.bindingEvent.childrenComplete);
  4275. }
  4276. }
  4277. didDisplayOnLastUpdate = shouldDisplay;
  4278. }, null, { disposeWhenNodeIsRemoved: element });
  4279. return { 'controlsDescendantBindings': true };
  4280. }
  4281. };
  4282. ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
  4283. ko.virtualElements.allowedBindings[bindingKey] = true;
  4284. }
  4285. // Construct the actual binding handlers
  4286. makeWithIfBinding('if');
  4287. makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
  4288. makeWithIfBinding('with', true /* isWith */);
  4289. })();ko.bindingHandlers['let'] = {
  4290. 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  4291. // Make a modified binding context, with extra properties, and apply it to descendant elements
  4292. var innerContext = bindingContext['extend'](valueAccessor);
  4293. ko.applyBindingsToDescendants(innerContext, element);
  4294. return { 'controlsDescendantBindings': true };
  4295. }
  4296. };
  4297. ko.virtualElements.allowedBindings['let'] = true;
  4298. var captionPlaceholder = {};
  4299. ko.bindingHandlers['options'] = {
  4300. 'init': function(element) {
  4301. if (ko.utils.tagNameLower(element) !== "select")
  4302. throw new Error("options binding applies only to SELECT elements");
  4303. // Remove all existing <option>s.
  4304. while (element.length > 0) {
  4305. element.remove(0);
  4306. }
  4307. // Ensures that the binding processor doesn't try to bind the options
  4308. return { 'controlsDescendantBindings': true };
  4309. },
  4310. 'update': function (element, valueAccessor, allBindings) {
  4311. function selectedOptions() {
  4312. return ko.utils.arrayFilter(element.options, function (node) { return node.selected; });
  4313. }
  4314. var selectWasPreviouslyEmpty = element.length == 0,
  4315. multiple = element.multiple,
  4316. previousScrollTop = (!selectWasPreviouslyEmpty && multiple) ? element.scrollTop : null,
  4317. unwrappedArray = ko.utils.unwrapObservable(valueAccessor()),
  4318. valueAllowUnset = allBindings.get('valueAllowUnset') && allBindings['has']('value'),
  4319. includeDestroyed = allBindings.get('optionsIncludeDestroyed'),
  4320. arrayToDomNodeChildrenOptions = {},
  4321. captionValue,
  4322. filteredArray,
  4323. previousSelectedValues = [];
  4324. if (!valueAllowUnset) {
  4325. if (multiple) {
  4326. previousSelectedValues = ko.utils.arrayMap(selectedOptions(), ko.selectExtensions.readValue);
  4327. } else if (element.selectedIndex >= 0) {
  4328. previousSelectedValues.push(ko.selectExtensions.readValue(element.options[element.selectedIndex]));
  4329. }
  4330. }
  4331. if (unwrappedArray) {
  4332. if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
  4333. unwrappedArray = [unwrappedArray];
  4334. // Filter out any entries marked as destroyed
  4335. filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
  4336. return includeDestroyed || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
  4337. });
  4338. // If caption is included, add it to the array
  4339. if (allBindings['has']('optionsCaption')) {
  4340. captionValue = ko.utils.unwrapObservable(allBindings.get('optionsCaption'));
  4341. // If caption value is null or undefined, don't show a caption
  4342. if (captionValue !== null && captionValue !== undefined) {
  4343. filteredArray.unshift(captionPlaceholder);
  4344. }
  4345. }
  4346. } else {
  4347. // If a falsy value is provided (e.g. null), we'll simply empty the select element
  4348. }
  4349. function applyToObject(object, predicate, defaultValue) {
  4350. var predicateType = typeof predicate;
  4351. if (predicateType == "function") // Given a function; run it against the data value
  4352. return predicate(object);
  4353. else if (predicateType == "string") // Given a string; treat it as a property name on the data value
  4354. return object[predicate];
  4355. else // Given no optionsText arg; use the data value itself
  4356. return defaultValue;
  4357. }
  4358. // The following functions can run at two different times:
  4359. // The first is when the whole array is being updated directly from this binding handler.
  4360. // The second is when an observable value for a specific array entry is updated.
  4361. // oldOptions will be empty in the first case, but will be filled with the previously generated option in the second.
  4362. var itemUpdate = false;
  4363. function optionForArrayItem(arrayEntry, index, oldOptions) {
  4364. if (oldOptions.length) {
  4365. previousSelectedValues = !valueAllowUnset && oldOptions[0].selected ? [ ko.selectExtensions.readValue(oldOptions[0]) ] : [];
  4366. itemUpdate = true;
  4367. }
  4368. var option = element.ownerDocument.createElement("option");
  4369. if (arrayEntry === captionPlaceholder) {
  4370. ko.utils.setTextContent(option, allBindings.get('optionsCaption'));
  4371. ko.selectExtensions.writeValue(option, undefined);
  4372. } else {
  4373. // Apply a value to the option element
  4374. var optionValue = applyToObject(arrayEntry, allBindings.get('optionsValue'), arrayEntry);
  4375. ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
  4376. // Apply some text to the option element
  4377. var optionText = applyToObject(arrayEntry, allBindings.get('optionsText'), optionValue);
  4378. ko.utils.setTextContent(option, optionText);
  4379. }
  4380. return [option];
  4381. }
  4382. // By using a beforeRemove callback, we delay the removal until after new items are added. This fixes a selection
  4383. // problem in IE<=8 and Firefox. See https://github.com/knockout/knockout/issues/1208
  4384. arrayToDomNodeChildrenOptions['beforeRemove'] =
  4385. function (option) {
  4386. element.removeChild(option);
  4387. };
  4388. function setSelectionCallback(arrayEntry, newOptions) {
  4389. if (itemUpdate && valueAllowUnset) {
  4390. // The model value is authoritative, so make sure its value is the one selected
  4391. ko.bindingEvent.notify(element, ko.bindingEvent.childrenComplete);
  4392. } else if (previousSelectedValues.length) {
  4393. // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
  4394. // That's why we first added them without selection. Now it's time to set the selection.
  4395. var isSelected = ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[0])) >= 0;
  4396. ko.utils.setOptionNodeSelectionState(newOptions[0], isSelected);
  4397. // If this option was changed from being selected during a single-item update, notify the change
  4398. if (itemUpdate && !isSelected) {
  4399. ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
  4400. }
  4401. }
  4402. }
  4403. var callback = setSelectionCallback;
  4404. if (allBindings['has']('optionsAfterRender') && typeof allBindings.get('optionsAfterRender') == "function") {
  4405. callback = function(arrayEntry, newOptions) {
  4406. setSelectionCallback(arrayEntry, newOptions);
  4407. ko.dependencyDetection.ignore(allBindings.get('optionsAfterRender'), null, [newOptions[0], arrayEntry !== captionPlaceholder ? arrayEntry : undefined]);
  4408. }
  4409. }
  4410. ko.utils.setDomNodeChildrenFromArrayMapping(element, filteredArray, optionForArrayItem, arrayToDomNodeChildrenOptions, callback);
  4411. if (!valueAllowUnset) {
  4412. // Determine if the selection has changed as a result of updating the options list
  4413. var selectionChanged;
  4414. if (multiple) {
  4415. // For a multiple-select box, compare the new selection count to the previous one
  4416. // But if nothing was selected before, the selection can't have changed
  4417. selectionChanged = previousSelectedValues.length && selectedOptions().length < previousSelectedValues.length;
  4418. } else {
  4419. // For a single-select box, compare the current value to the previous value
  4420. // But if nothing was selected before or nothing is selected now, just look for a change in selection
  4421. selectionChanged = (previousSelectedValues.length && element.selectedIndex >= 0)
  4422. ? (ko.selectExtensions.readValue(element.options[element.selectedIndex]) !== previousSelectedValues[0])
  4423. : (previousSelectedValues.length || element.selectedIndex >= 0);
  4424. }
  4425. // Ensure consistency between model value and selected option.
  4426. // If the dropdown was changed so that selection is no longer the same,
  4427. // notify the value or selectedOptions binding.
  4428. if (selectionChanged) {
  4429. ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
  4430. }
  4431. }
  4432. if (valueAllowUnset || ko.computedContext.isInitial()) {
  4433. ko.bindingEvent.notify(element, ko.bindingEvent.childrenComplete);
  4434. }
  4435. // Workaround for IE bug
  4436. ko.utils.ensureSelectElementIsRenderedCorrectly(element);
  4437. if (previousScrollTop && Math.abs(previousScrollTop - element.scrollTop) > 20)
  4438. element.scrollTop = previousScrollTop;
  4439. }
  4440. };
  4441. ko.bindingHandlers['options'].optionValueDomDataKey = ko.utils.domData.nextKey();
  4442. ko.bindingHandlers['selectedOptions'] = {
  4443. 'init': function (element, valueAccessor, allBindings) {
  4444. function updateFromView() {
  4445. var value = valueAccessor(), valueToWrite = [];
  4446. ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
  4447. if (node.selected)
  4448. valueToWrite.push(ko.selectExtensions.readValue(node));
  4449. });
  4450. ko.expressionRewriting.writeValueToProperty(value, allBindings, 'selectedOptions', valueToWrite);
  4451. }
  4452. function updateFromModel() {
  4453. var newValue = ko.utils.unwrapObservable(valueAccessor()),
  4454. previousScrollTop = element.scrollTop;
  4455. if (newValue && typeof newValue.length == "number") {
  4456. ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
  4457. var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
  4458. if (node.selected != isSelected) { // This check prevents flashing of the select element in IE
  4459. ko.utils.setOptionNodeSelectionState(node, isSelected);
  4460. }
  4461. });
  4462. }
  4463. element.scrollTop = previousScrollTop;
  4464. }
  4465. if (ko.utils.tagNameLower(element) != "select") {
  4466. throw new Error("selectedOptions binding applies only to SELECT elements");
  4467. }
  4468. var updateFromModelComputed;
  4469. ko.bindingEvent.subscribe(element, ko.bindingEvent.childrenComplete, function () {
  4470. if (!updateFromModelComputed) {
  4471. ko.utils.registerEventHandler(element, "change", updateFromView);
  4472. updateFromModelComputed = ko.computed(updateFromModel, null, { disposeWhenNodeIsRemoved: element });
  4473. } else {
  4474. updateFromView();
  4475. }
  4476. }, null, { 'notifyImmediately': true });
  4477. },
  4478. 'update': function() {} // Keep for backwards compatibility with code that may have wrapped binding
  4479. };
  4480. ko.expressionRewriting.twoWayBindings['selectedOptions'] = true;
  4481. ko.bindingHandlers['style'] = {
  4482. 'update': function (element, valueAccessor) {
  4483. var value = ko.utils.unwrapObservable(valueAccessor() || {});
  4484. ko.utils.objectForEach(value, function(styleName, styleValue) {
  4485. styleValue = ko.utils.unwrapObservable(styleValue);
  4486. if (styleValue === null || styleValue === undefined || styleValue === false) {
  4487. // Empty string removes the value, whereas null/undefined have no effect
  4488. styleValue = "";
  4489. }
  4490. if (jQueryInstance) {
  4491. jQueryInstance(element)['css'](styleName, styleValue);
  4492. } else if (/^--/.test(styleName)) {
  4493. // Is styleName a custom CSS property?
  4494. element.style.setProperty(styleName, styleValue);
  4495. } else {
  4496. styleName = styleName.replace(/-(\w)/g, function (all, letter) {
  4497. return letter.toUpperCase();
  4498. });
  4499. var previousStyle = element.style[styleName];
  4500. element.style[styleName] = styleValue;
  4501. if (styleValue !== previousStyle && element.style[styleName] == previousStyle && !isNaN(styleValue)) {
  4502. element.style[styleName] = styleValue + "px";
  4503. }
  4504. }
  4505. });
  4506. }
  4507. };
  4508. ko.bindingHandlers['submit'] = {
  4509. 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
  4510. if (typeof valueAccessor() != "function")
  4511. throw new Error("The value for a submit binding must be a function");
  4512. ko.utils.registerEventHandler(element, "submit", function (event) {
  4513. var handlerReturnValue;
  4514. var value = valueAccessor();
  4515. try { handlerReturnValue = value.call(bindingContext['$data'], element); }
  4516. finally {
  4517. if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
  4518. if (event.preventDefault)
  4519. event.preventDefault();
  4520. else
  4521. event.returnValue = false;
  4522. }
  4523. }
  4524. });
  4525. }
  4526. };
  4527. ko.bindingHandlers['text'] = {
  4528. 'init': function() {
  4529. // Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications).
  4530. // It should also make things faster, as we no longer have to consider whether the text node might be bindable.
  4531. return { 'controlsDescendantBindings': true };
  4532. },
  4533. 'update': function (element, valueAccessor) {
  4534. ko.utils.setTextContent(element, valueAccessor());
  4535. }
  4536. };
  4537. ko.virtualElements.allowedBindings['text'] = true;
  4538. (function () {
  4539. if (window && window.navigator) {
  4540. var parseVersion = function (matches) {
  4541. if (matches) {
  4542. return parseFloat(matches[1]);
  4543. }
  4544. };
  4545. // Detect various browser versions because some old versions don't fully support the 'input' event
  4546. var userAgent = window.navigator.userAgent,
  4547. operaVersion, chromeVersion, safariVersion, firefoxVersion, ieVersion, edgeVersion;
  4548. (operaVersion = window.opera && window.opera.version && parseInt(window.opera.version()))
  4549. || (edgeVersion = parseVersion(userAgent.match(/Edge\/([^ ]+)$/)))
  4550. || (chromeVersion = parseVersion(userAgent.match(/Chrome\/([^ ]+)/)))
  4551. || (safariVersion = parseVersion(userAgent.match(/Version\/([^ ]+) Safari/)))
  4552. || (firefoxVersion = parseVersion(userAgent.match(/Firefox\/([^ ]+)/)))
  4553. || (ieVersion = ko.utils.ieVersion || parseVersion(userAgent.match(/MSIE ([^ ]+)/))) // Detects up to IE 10
  4554. || (ieVersion = parseVersion(userAgent.match(/rv:([^ )]+)/))); // Detects IE 11
  4555. }
  4556. // IE 8 and 9 have bugs that prevent the normal events from firing when the value changes.
  4557. // But it does fire the 'selectionchange' event on many of those, presumably because the
  4558. // cursor is moving and that counts as the selection changing. The 'selectionchange' event is
  4559. // fired at the document level only and doesn't directly indicate which element changed. We
  4560. // set up just one event handler for the document and use 'activeElement' to determine which
  4561. // element was changed.
  4562. if (ieVersion >= 8 && ieVersion < 10) {
  4563. var selectionChangeRegisteredName = ko.utils.domData.nextKey(),
  4564. selectionChangeHandlerName = ko.utils.domData.nextKey();
  4565. var selectionChangeHandler = function(event) {
  4566. var target = this.activeElement,
  4567. handler = target && ko.utils.domData.get(target, selectionChangeHandlerName);
  4568. if (handler) {
  4569. handler(event);
  4570. }
  4571. };
  4572. var registerForSelectionChangeEvent = function (element, handler) {
  4573. var ownerDoc = element.ownerDocument;
  4574. if (!ko.utils.domData.get(ownerDoc, selectionChangeRegisteredName)) {
  4575. ko.utils.domData.set(ownerDoc, selectionChangeRegisteredName, true);
  4576. ko.utils.registerEventHandler(ownerDoc, 'selectionchange', selectionChangeHandler);
  4577. }
  4578. ko.utils.domData.set(element, selectionChangeHandlerName, handler);
  4579. };
  4580. }
  4581. ko.bindingHandlers['textInput'] = {
  4582. 'init': function (element, valueAccessor, allBindings) {
  4583. var previousElementValue = element.value,
  4584. timeoutHandle,
  4585. elementValueBeforeEvent;
  4586. var updateModel = function (event) {
  4587. clearTimeout(timeoutHandle);
  4588. elementValueBeforeEvent = timeoutHandle = undefined;
  4589. var elementValue = element.value;
  4590. if (previousElementValue !== elementValue) {
  4591. // Provide a way for tests to know exactly which event was processed
  4592. if (DEBUG && event) element['_ko_textInputProcessedEvent'] = event.type;
  4593. previousElementValue = elementValue;
  4594. ko.expressionRewriting.writeValueToProperty(valueAccessor(), allBindings, 'textInput', elementValue);
  4595. }
  4596. };
  4597. var deferUpdateModel = function (event) {
  4598. if (!timeoutHandle) {
  4599. // The elementValueBeforeEvent variable is set *only* during the brief gap between an
  4600. // event firing and the updateModel function running. This allows us to ignore model
  4601. // updates that are from the previous state of the element, usually due to techniques
  4602. // such as rateLimit. Such updates, if not ignored, can cause keystrokes to be lost.
  4603. elementValueBeforeEvent = element.value;
  4604. var handler = DEBUG ? updateModel.bind(element, {type: event.type}) : updateModel;
  4605. timeoutHandle = ko.utils.setTimeout(handler, 4);
  4606. }
  4607. };
  4608. // IE9 will mess up the DOM if you handle events synchronously which results in DOM changes (such as other bindings);
  4609. // so we'll make sure all updates are asynchronous
  4610. var ieUpdateModel = ko.utils.ieVersion == 9 ? deferUpdateModel : updateModel,
  4611. ourUpdate = false;
  4612. var updateView = function () {
  4613. var modelValue = ko.utils.unwrapObservable(valueAccessor());
  4614. if (modelValue === null || modelValue === undefined) {
  4615. modelValue = '';
  4616. }
  4617. if (elementValueBeforeEvent !== undefined && modelValue === elementValueBeforeEvent) {
  4618. ko.utils.setTimeout(updateView, 4);
  4619. return;
  4620. }
  4621. // Update the element only if the element and model are different. On some browsers, updating the value
  4622. // will move the cursor to the end of the input, which would be bad while the user is typing.
  4623. if (element.value !== modelValue) {
  4624. ourUpdate = true; // Make sure we ignore events (propertychange) that result from updating the value
  4625. element.value = modelValue;
  4626. ourUpdate = false;
  4627. previousElementValue = element.value; // In case the browser changes the value (see #2281)
  4628. }
  4629. };
  4630. var onEvent = function (event, handler) {
  4631. ko.utils.registerEventHandler(element, event, handler);
  4632. };
  4633. if (DEBUG && ko.bindingHandlers['textInput']['_forceUpdateOn']) {
  4634. // Provide a way for tests to specify exactly which events are bound
  4635. ko.utils.arrayForEach(ko.bindingHandlers['textInput']['_forceUpdateOn'], function(eventName) {
  4636. if (eventName.slice(0,5) == 'after') {
  4637. onEvent(eventName.slice(5), deferUpdateModel);
  4638. } else {
  4639. onEvent(eventName, updateModel);
  4640. }
  4641. });
  4642. } else {
  4643. if (ieVersion) {
  4644. // All versions (including 11) of Internet Explorer have a bug that they don't generate an input or propertychange event when ESC is pressed
  4645. onEvent('keypress', updateModel);
  4646. }
  4647. if (ieVersion < 11) {
  4648. // Internet Explorer <= 8 doesn't support the 'input' event, but does include 'propertychange' that fires whenever
  4649. // any property of an element changes. Unlike 'input', it also fires if a property is changed from JavaScript code,
  4650. // but that's an acceptable compromise for this binding. IE 9 and 10 support 'input', but since they don't always
  4651. // fire it when using autocomplete, we'll use 'propertychange' for them also.
  4652. onEvent('propertychange', function(event) {
  4653. if (!ourUpdate && event.propertyName === 'value') {
  4654. ieUpdateModel(event);
  4655. }
  4656. });
  4657. }
  4658. if (ieVersion == 8) {
  4659. // IE 8 has a bug where it fails to fire 'propertychange' on the first update following a value change from
  4660. // JavaScript code. It also doesn't fire if you clear the entire value. To fix this, we bind to the following
  4661. // events too.
  4662. onEvent('keyup', updateModel); // A single keystoke
  4663. onEvent('keydown', updateModel); // The first character when a key is held down
  4664. }
  4665. if (registerForSelectionChangeEvent) {
  4666. // Internet Explorer 9 doesn't fire the 'input' event when deleting text, including using
  4667. // the backspace, delete, or ctrl-x keys, clicking the 'x' to clear the input, dragging text
  4668. // out of the field, and cutting or deleting text using the context menu. 'selectionchange'
  4669. // can detect all of those except dragging text out of the field, for which we use 'dragend'.
  4670. // These are also needed in IE8 because of the bug described above.
  4671. registerForSelectionChangeEvent(element, ieUpdateModel); // 'selectionchange' covers cut, paste, drop, delete, etc.
  4672. onEvent('dragend', deferUpdateModel);
  4673. }
  4674. if (!ieVersion || ieVersion >= 9) {
  4675. // All other supported browsers support the 'input' event, which fires whenever the content of the element is changed
  4676. // through the user interface.
  4677. onEvent('input', ieUpdateModel);
  4678. }
  4679. if (safariVersion < 5 && ko.utils.tagNameLower(element) === "textarea") {
  4680. // Safari <5 doesn't fire the 'input' event for <textarea> elements (it does fire 'textInput'
  4681. // but only when typing). So we'll just catch as much as we can with keydown, cut, and paste.
  4682. onEvent('keydown', deferUpdateModel);
  4683. onEvent('paste', deferUpdateModel);
  4684. onEvent('cut', deferUpdateModel);
  4685. } else if (operaVersion < 11) {
  4686. // Opera 10 doesn't always fire the 'input' event for cut, paste, undo & drop operations.
  4687. // We can try to catch some of those using 'keydown'.
  4688. onEvent('keydown', deferUpdateModel);
  4689. } else if (firefoxVersion < 4.0) {
  4690. // Firefox <= 3.6 doesn't fire the 'input' event when text is filled in through autocomplete
  4691. onEvent('DOMAutoComplete', updateModel);
  4692. // Firefox <=3.5 doesn't fire the 'input' event when text is dropped into the input.
  4693. onEvent('dragdrop', updateModel); // <3.5
  4694. onEvent('drop', updateModel); // 3.5
  4695. } else if (edgeVersion && element.type === "number") {
  4696. // Microsoft Edge doesn't fire 'input' or 'change' events for number inputs when
  4697. // the value is changed via the up / down arrow keys
  4698. onEvent('keydown', deferUpdateModel);
  4699. }
  4700. }
  4701. // Bind to the change event so that we can catch programmatic updates of the value that fire this event.
  4702. onEvent('change', updateModel);
  4703. // To deal with browsers that don't notify any kind of event for some changes (IE, Safari, etc.)
  4704. onEvent('blur', updateModel);
  4705. ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
  4706. }
  4707. };
  4708. ko.expressionRewriting.twoWayBindings['textInput'] = true;
  4709. // textinput is an alias for textInput
  4710. ko.bindingHandlers['textinput'] = {
  4711. // preprocess is the only way to set up a full alias
  4712. 'preprocess': function (value, name, addBinding) {
  4713. addBinding('textInput', value);
  4714. }
  4715. };
  4716. })();ko.bindingHandlers['uniqueName'] = {
  4717. 'init': function (element, valueAccessor) {
  4718. if (valueAccessor()) {
  4719. var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
  4720. ko.utils.setElementName(element, name);
  4721. }
  4722. }
  4723. };
  4724. ko.bindingHandlers['uniqueName'].currentIndex = 0;
  4725. ko.bindingHandlers['using'] = {
  4726. 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  4727. var options;
  4728. if (allBindings['has']('as')) {
  4729. options = { 'as': allBindings.get('as'), 'noChildContext': allBindings.get('noChildContext') };
  4730. }
  4731. var innerContext = bindingContext['createChildContext'](valueAccessor, options);
  4732. ko.applyBindingsToDescendants(innerContext, element);
  4733. return { 'controlsDescendantBindings': true };
  4734. }
  4735. };
  4736. ko.virtualElements.allowedBindings['using'] = true;
  4737. ko.bindingHandlers['value'] = {
  4738. 'init': function (element, valueAccessor, allBindings) {
  4739. var tagName = ko.utils.tagNameLower(element),
  4740. isInputElement = tagName == "input";
  4741. // If the value binding is placed on a radio/checkbox, then just pass through to checkedValue and quit
  4742. if (isInputElement && (element.type == "checkbox" || element.type == "radio")) {
  4743. ko.applyBindingAccessorsToNode(element, { 'checkedValue': valueAccessor });
  4744. return;
  4745. }
  4746. var eventsToCatch = [];
  4747. var requestedEventsToCatch = allBindings.get("valueUpdate");
  4748. var propertyChangedFired = false;
  4749. var elementValueBeforeEvent = null;
  4750. if (requestedEventsToCatch) {
  4751. // Allow both individual event names, and arrays of event names
  4752. if (typeof requestedEventsToCatch == "string") {
  4753. eventsToCatch = [requestedEventsToCatch];
  4754. } else {
  4755. eventsToCatch = ko.utils.arrayGetDistinctValues(requestedEventsToCatch);
  4756. }
  4757. ko.utils.arrayRemoveItem(eventsToCatch, "change"); // We'll subscribe to "change" events later
  4758. }
  4759. var valueUpdateHandler = function() {
  4760. elementValueBeforeEvent = null;
  4761. propertyChangedFired = false;
  4762. var modelValue = valueAccessor();
  4763. var elementValue = ko.selectExtensions.readValue(element);
  4764. ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'value', elementValue);
  4765. }
  4766. // Workaround for https://github.com/SteveSanderson/knockout/issues/122
  4767. // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
  4768. var ieAutoCompleteHackNeeded = ko.utils.ieVersion && isInputElement && element.type == "text"
  4769. && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
  4770. if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
  4771. ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
  4772. ko.utils.registerEventHandler(element, "focus", function () { propertyChangedFired = false });
  4773. ko.utils.registerEventHandler(element, "blur", function() {
  4774. if (propertyChangedFired) {
  4775. valueUpdateHandler();
  4776. }
  4777. });
  4778. }
  4779. ko.utils.arrayForEach(eventsToCatch, function(eventName) {
  4780. // The syntax "after<eventname>" means "run the handler asynchronously after the event"
  4781. // This is useful, for example, to catch "keydown" events after the browser has updated the control
  4782. // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
  4783. var handler = valueUpdateHandler;
  4784. if (ko.utils.stringStartsWith(eventName, "after")) {
  4785. handler = function() {
  4786. // The elementValueBeforeEvent variable is non-null *only* during the brief gap between
  4787. // a keyX event firing and the valueUpdateHandler running, which is scheduled to happen
  4788. // at the earliest asynchronous opportunity. We store this temporary information so that
  4789. // if, between keyX and valueUpdateHandler, the underlying model value changes separately,
  4790. // we can overwrite that model value change with the value the user just typed. Otherwise,
  4791. // techniques like rateLimit can trigger model changes at critical moments that will
  4792. // override the user's inputs, causing keystrokes to be lost.
  4793. elementValueBeforeEvent = ko.selectExtensions.readValue(element);
  4794. ko.utils.setTimeout(valueUpdateHandler, 0);
  4795. };
  4796. eventName = eventName.substring("after".length);
  4797. }
  4798. ko.utils.registerEventHandler(element, eventName, handler);
  4799. });
  4800. var updateFromModel;
  4801. if (isInputElement && element.type == "file") {
  4802. // For file input elements, can only write the empty string
  4803. updateFromModel = function () {
  4804. var newValue = ko.utils.unwrapObservable(valueAccessor());
  4805. if (newValue === null || newValue === undefined || newValue === "") {
  4806. element.value = "";
  4807. } else {
  4808. ko.dependencyDetection.ignore(valueUpdateHandler); // reset the model to match the element
  4809. }
  4810. }
  4811. } else {
  4812. updateFromModel = function () {
  4813. var newValue = ko.utils.unwrapObservable(valueAccessor());
  4814. var elementValue = ko.selectExtensions.readValue(element);
  4815. if (elementValueBeforeEvent !== null && newValue === elementValueBeforeEvent) {
  4816. ko.utils.setTimeout(updateFromModel, 0);
  4817. return;
  4818. }
  4819. var valueHasChanged = newValue !== elementValue;
  4820. if (valueHasChanged || elementValue === undefined) {
  4821. if (tagName === "select") {
  4822. var allowUnset = allBindings.get('valueAllowUnset');
  4823. ko.selectExtensions.writeValue(element, newValue, allowUnset);
  4824. if (!allowUnset && newValue !== ko.selectExtensions.readValue(element)) {
  4825. // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
  4826. // because you're not allowed to have a model value that disagrees with a visible UI selection.
  4827. ko.dependencyDetection.ignore(valueUpdateHandler);
  4828. }
  4829. } else {
  4830. ko.selectExtensions.writeValue(element, newValue);
  4831. }
  4832. }
  4833. };
  4834. }
  4835. if (tagName === "select") {
  4836. var updateFromModelComputed;
  4837. ko.bindingEvent.subscribe(element, ko.bindingEvent.childrenComplete, function () {
  4838. if (!updateFromModelComputed) {
  4839. ko.utils.registerEventHandler(element, "change", valueUpdateHandler);
  4840. updateFromModelComputed = ko.computed(updateFromModel, null, { disposeWhenNodeIsRemoved: element });
  4841. } else if (allBindings.get('valueAllowUnset')) {
  4842. updateFromModel();
  4843. } else {
  4844. valueUpdateHandler();
  4845. }
  4846. }, null, { 'notifyImmediately': true });
  4847. } else {
  4848. ko.utils.registerEventHandler(element, "change", valueUpdateHandler);
  4849. ko.computed(updateFromModel, null, { disposeWhenNodeIsRemoved: element });
  4850. }
  4851. },
  4852. 'update': function() {} // Keep for backwards compatibility with code that may have wrapped value binding
  4853. };
  4854. ko.expressionRewriting.twoWayBindings['value'] = true;
  4855. ko.bindingHandlers['visible'] = {
  4856. 'update': function (element, valueAccessor) {
  4857. var value = ko.utils.unwrapObservable(valueAccessor());
  4858. var isCurrentlyVisible = !(element.style.display == "none");
  4859. if (value && !isCurrentlyVisible)
  4860. element.style.display = "";
  4861. else if ((!value) && isCurrentlyVisible)
  4862. element.style.display = "none";
  4863. }
  4864. };
  4865. ko.bindingHandlers['hidden'] = {
  4866. 'update': function (element, valueAccessor) {
  4867. ko.bindingHandlers['visible']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
  4868. }
  4869. };
  4870. // 'click' is just a shorthand for the usual full-length event:{click:handler}
  4871. makeEventHandlerShortcut('click');
  4872. // If you want to make a custom template engine,
  4873. //
  4874. // [1] Inherit from this class (like ko.nativeTemplateEngine does)
  4875. // [2] Override 'renderTemplateSource', supplying a function with this signature:
  4876. //
  4877. // function (templateSource, bindingContext, options) {
  4878. // // - templateSource.text() is the text of the template you should render
  4879. // // - bindingContext.$data is the data you should pass into the template
  4880. // // - you might also want to make bindingContext.$parent, bindingContext.$parents,
  4881. // // and bindingContext.$root available in the template too
  4882. // // - options gives you access to any other properties set on "data-bind: { template: options }"
  4883. // // - templateDocument is the document object of the template
  4884. // //
  4885. // // Return value: an array of DOM nodes
  4886. // }
  4887. //
  4888. // [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
  4889. //
  4890. // function (script) {
  4891. // // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
  4892. // // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
  4893. // }
  4894. //
  4895. // This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
  4896. // If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
  4897. // and then you don't need to override 'createJavaScriptEvaluatorBlock'.
  4898. ko.templateEngine = function () { };
  4899. ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options, templateDocument) {
  4900. throw new Error("Override renderTemplateSource");
  4901. };
  4902. ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
  4903. throw new Error("Override createJavaScriptEvaluatorBlock");
  4904. };
  4905. ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
  4906. // Named template
  4907. if (typeof template == "string") {
  4908. templateDocument = templateDocument || document;
  4909. var elem = templateDocument.getElementById(template);
  4910. if (!elem)
  4911. throw new Error("Cannot find template with ID " + template);
  4912. return new ko.templateSources.domElement(elem);
  4913. } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
  4914. // Anonymous template
  4915. return new ko.templateSources.anonymousTemplate(template);
  4916. } else
  4917. throw new Error("Unknown template type: " + template);
  4918. };
  4919. ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
  4920. var templateSource = this['makeTemplateSource'](template, templateDocument);
  4921. return this['renderTemplateSource'](templateSource, bindingContext, options, templateDocument);
  4922. };
  4923. ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
  4924. // Skip rewriting if requested
  4925. if (this['allowTemplateRewriting'] === false)
  4926. return true;
  4927. return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
  4928. };
  4929. ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
  4930. var templateSource = this['makeTemplateSource'](template, templateDocument);
  4931. var rewritten = rewriterCallback(templateSource['text']());
  4932. templateSource['text'](rewritten);
  4933. templateSource['data']("isRewritten", true);
  4934. };
  4935. ko.exportSymbol('templateEngine', ko.templateEngine);
  4936. ko.templateRewriting = (function () {
  4937. var memoizeDataBindingAttributeSyntaxRegex = /(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'|[^>]*))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi;
  4938. var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
  4939. function validateDataBindValuesForRewriting(keyValueArray) {
  4940. var allValidators = ko.expressionRewriting.bindingRewriteValidators;
  4941. for (var i = 0; i < keyValueArray.length; i++) {
  4942. var key = keyValueArray[i]['key'];
  4943. if (Object.prototype.hasOwnProperty.call(allValidators, key)) {
  4944. var validator = allValidators[key];
  4945. if (typeof validator === "function") {
  4946. var possibleErrorMessage = validator(keyValueArray[i]['value']);
  4947. if (possibleErrorMessage)
  4948. throw new Error(possibleErrorMessage);
  4949. } else if (!validator) {
  4950. throw new Error("This template engine does not support the '" + key + "' binding within its templates");
  4951. }
  4952. }
  4953. }
  4954. }
  4955. function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, nodeName, templateEngine) {
  4956. var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
  4957. validateDataBindValuesForRewriting(dataBindKeyValueArray);
  4958. var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray, {'valueAccessors':true});
  4959. // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
  4960. // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
  4961. // extra indirection.
  4962. var applyBindingsToNextSiblingScript =
  4963. "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()},'" + nodeName.toLowerCase() + "')";
  4964. return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
  4965. }
  4966. return {
  4967. ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
  4968. if (!templateEngine['isTemplateRewritten'](template, templateDocument))
  4969. templateEngine['rewriteTemplate'](template, function (htmlString) {
  4970. return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
  4971. }, templateDocument);
  4972. },
  4973. memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
  4974. return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
  4975. return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[4], /* tagToRetain: */ arguments[1], /* nodeName: */ arguments[2], templateEngine);
  4976. }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
  4977. return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", /* nodeName: */ "#comment", templateEngine);
  4978. });
  4979. },
  4980. applyMemoizedBindingsToNextSibling: function (bindings, nodeName) {
  4981. return ko.memoization.memoize(function (domNode, bindingContext) {
  4982. var nodeToBind = domNode.nextSibling;
  4983. if (nodeToBind && nodeToBind.nodeName.toLowerCase() === nodeName) {
  4984. ko.applyBindingAccessorsToNode(nodeToBind, bindings, bindingContext);
  4985. }
  4986. });
  4987. }
  4988. }
  4989. })();
  4990. // Exported only because it has to be referenced by string lookup from within rewritten template
  4991. ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
  4992. (function() {
  4993. // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
  4994. // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
  4995. //
  4996. // Two are provided by default:
  4997. // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
  4998. // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
  4999. // without reading/writing the actual element text content, since it will be overwritten
  5000. // with the rendered template output.
  5001. // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
  5002. // Template sources need to have the following functions:
  5003. // text() - returns the template text from your storage location
  5004. // text(value) - writes the supplied template text to your storage location
  5005. // data(key) - reads values stored using data(key, value) - see below
  5006. // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
  5007. //
  5008. // Optionally, template sources can also have the following functions:
  5009. // nodes() - returns a DOM element containing the nodes of this template, where available
  5010. // nodes(value) - writes the given DOM element to your storage location
  5011. // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
  5012. // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
  5013. //
  5014. // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
  5015. // using and overriding "makeTemplateSource" to return an instance of your custom template source.
  5016. ko.templateSources = {};
  5017. // ---- ko.templateSources.domElement -----
  5018. // template types
  5019. var templateScript = 1,
  5020. templateTextArea = 2,
  5021. templateTemplate = 3,
  5022. templateElement = 4;
  5023. ko.templateSources.domElement = function(element) {
  5024. this.domElement = element;
  5025. if (element) {
  5026. var tagNameLower = ko.utils.tagNameLower(element);
  5027. this.templateType =
  5028. tagNameLower === "script" ? templateScript :
  5029. tagNameLower === "textarea" ? templateTextArea :
  5030. // For browsers with proper <template> element support, where the .content property gives a document fragment
  5031. tagNameLower == "template" && element.content && element.content.nodeType === 11 ? templateTemplate :
  5032. templateElement;
  5033. }
  5034. }
  5035. ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
  5036. var elemContentsProperty = this.templateType === templateScript ? "text"
  5037. : this.templateType === templateTextArea ? "value"
  5038. : "innerHTML";
  5039. if (arguments.length == 0) {
  5040. return this.domElement[elemContentsProperty];
  5041. } else {
  5042. var valueToWrite = arguments[0];
  5043. if (elemContentsProperty === "innerHTML")
  5044. ko.utils.setHtml(this.domElement, valueToWrite);
  5045. else
  5046. this.domElement[elemContentsProperty] = valueToWrite;
  5047. }
  5048. };
  5049. var dataDomDataPrefix = ko.utils.domData.nextKey() + "_";
  5050. ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
  5051. if (arguments.length === 1) {
  5052. return ko.utils.domData.get(this.domElement, dataDomDataPrefix + key);
  5053. } else {
  5054. ko.utils.domData.set(this.domElement, dataDomDataPrefix + key, arguments[1]);
  5055. }
  5056. };
  5057. var templatesDomDataKey = ko.utils.domData.nextKey();
  5058. function getTemplateDomData(element) {
  5059. return ko.utils.domData.get(element, templatesDomDataKey) || {};
  5060. }
  5061. function setTemplateDomData(element, data) {
  5062. ko.utils.domData.set(element, templatesDomDataKey, data);
  5063. }
  5064. ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
  5065. var element = this.domElement;
  5066. if (arguments.length == 0) {
  5067. var templateData = getTemplateDomData(element),
  5068. nodes = templateData.containerData || (
  5069. this.templateType === templateTemplate ? element.content :
  5070. this.templateType === templateElement ? element :
  5071. undefined);
  5072. if (!nodes || templateData.alwaysCheckText) {
  5073. // If the template is associated with an element that stores the template as text,
  5074. // parse and cache the nodes whenever there's new text content available. This allows
  5075. // the user to update the template content by updating the text of template node.
  5076. var text = this['text']();
  5077. if (text && text !== templateData.textData) {
  5078. nodes = ko.utils.parseHtmlForTemplateNodes(text, element.ownerDocument);
  5079. setTemplateDomData(element, {containerData: nodes, textData: text, alwaysCheckText: true});
  5080. }
  5081. }
  5082. return nodes;
  5083. } else {
  5084. var valueToWrite = arguments[0];
  5085. if (this.templateType !== undefined) {
  5086. this['text'](""); // clear the text from the node
  5087. }
  5088. setTemplateDomData(element, {containerData: valueToWrite});
  5089. }
  5090. };
  5091. // ---- ko.templateSources.anonymousTemplate -----
  5092. // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
  5093. // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
  5094. // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
  5095. ko.templateSources.anonymousTemplate = function(element) {
  5096. this.domElement = element;
  5097. }
  5098. ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
  5099. ko.templateSources.anonymousTemplate.prototype.constructor = ko.templateSources.anonymousTemplate;
  5100. ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
  5101. if (arguments.length == 0) {
  5102. var templateData = getTemplateDomData(this.domElement);
  5103. if (templateData.textData === undefined && templateData.containerData)
  5104. templateData.textData = templateData.containerData.innerHTML;
  5105. return templateData.textData;
  5106. } else {
  5107. var valueToWrite = arguments[0];
  5108. setTemplateDomData(this.domElement, {textData: valueToWrite});
  5109. }
  5110. };
  5111. ko.exportSymbol('templateSources', ko.templateSources);
  5112. ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
  5113. ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
  5114. })();
  5115. (function () {
  5116. var _templateEngine;
  5117. ko.setTemplateEngine = function (templateEngine) {
  5118. if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
  5119. throw new Error("templateEngine must inherit from ko.templateEngine");
  5120. _templateEngine = templateEngine;
  5121. }
  5122. function invokeForEachNodeInContinuousRange(firstNode, lastNode, action) {
  5123. var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
  5124. while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
  5125. nextInQueue = ko.virtualElements.nextSibling(node);
  5126. action(node, nextInQueue);
  5127. }
  5128. }
  5129. function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
  5130. // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
  5131. // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
  5132. // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
  5133. // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
  5134. // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
  5135. if (continuousNodeArray.length) {
  5136. var firstNode = continuousNodeArray[0],
  5137. lastNode = continuousNodeArray[continuousNodeArray.length - 1],
  5138. parentNode = firstNode.parentNode,
  5139. provider = ko.bindingProvider['instance'],
  5140. preprocessNode = provider['preprocessNode'];
  5141. if (preprocessNode) {
  5142. invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node, nextNodeInRange) {
  5143. var nodePreviousSibling = node.previousSibling;
  5144. var newNodes = preprocessNode.call(provider, node);
  5145. if (newNodes) {
  5146. if (node === firstNode)
  5147. firstNode = newNodes[0] || nextNodeInRange;
  5148. if (node === lastNode)
  5149. lastNode = newNodes[newNodes.length - 1] || nodePreviousSibling;
  5150. }
  5151. });
  5152. // Because preprocessNode can change the nodes, including the first and last nodes, update continuousNodeArray to match.
  5153. // We need the full set, including inner nodes, because the unmemoize step might remove the first node (and so the real
  5154. // first node needs to be in the array).
  5155. continuousNodeArray.length = 0;
  5156. if (!firstNode) { // preprocessNode might have removed all the nodes, in which case there's nothing left to do
  5157. return;
  5158. }
  5159. if (firstNode === lastNode) {
  5160. continuousNodeArray.push(firstNode);
  5161. } else {
  5162. continuousNodeArray.push(firstNode, lastNode);
  5163. ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
  5164. }
  5165. }
  5166. // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
  5167. // whereas a regular applyBindings won't introduce new memoized nodes
  5168. invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
  5169. if (node.nodeType === 1 || node.nodeType === 8)
  5170. ko.applyBindings(bindingContext, node);
  5171. });
  5172. invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
  5173. if (node.nodeType === 1 || node.nodeType === 8)
  5174. ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
  5175. });
  5176. // Make sure any changes done by applyBindings or unmemoize are reflected in the array
  5177. ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
  5178. }
  5179. }
  5180. function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
  5181. return nodeOrNodeArray.nodeType ? nodeOrNodeArray
  5182. : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
  5183. : null;
  5184. }
  5185. function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
  5186. options = options || {};
  5187. var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  5188. var templateDocument = (firstTargetNode || template || {}).ownerDocument;
  5189. var templateEngineToUse = (options['templateEngine'] || _templateEngine);
  5190. ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
  5191. var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
  5192. // Loosely check result is an array of DOM nodes
  5193. if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
  5194. throw new Error("Template engine must return an array of DOM nodes");
  5195. var haveAddedNodesToParent = false;
  5196. switch (renderMode) {
  5197. case "replaceChildren":
  5198. ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
  5199. haveAddedNodesToParent = true;
  5200. break;
  5201. case "replaceNode":
  5202. ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
  5203. haveAddedNodesToParent = true;
  5204. break;
  5205. case "ignoreTargetNode": break;
  5206. default:
  5207. throw new Error("Unknown renderMode: " + renderMode);
  5208. }
  5209. if (haveAddedNodesToParent) {
  5210. activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
  5211. if (options['afterRender']) {
  5212. ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext[options['as'] || '$data']]);
  5213. }
  5214. if (renderMode == "replaceChildren") {
  5215. ko.bindingEvent.notify(targetNodeOrNodeArray, ko.bindingEvent.childrenComplete);
  5216. }
  5217. }
  5218. return renderedNodesArray;
  5219. }
  5220. function resolveTemplateName(template, data, context) {
  5221. // The template can be specified as:
  5222. if (ko.isObservable(template)) {
  5223. // 1. An observable, with string value
  5224. return template();
  5225. } else if (typeof template === 'function') {
  5226. // 2. A function of (data, context) returning a string
  5227. return template(data, context);
  5228. } else {
  5229. // 3. A string
  5230. return template;
  5231. }
  5232. }
  5233. ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
  5234. options = options || {};
  5235. if ((options['templateEngine'] || _templateEngine) == undefined)
  5236. throw new Error("Set a template engine before calling renderTemplate");
  5237. renderMode = renderMode || "replaceChildren";
  5238. if (targetNodeOrNodeArray) {
  5239. var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  5240. var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
  5241. var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
  5242. return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
  5243. function () {
  5244. // Ensure we've got a proper binding context to work with
  5245. var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
  5246. ? dataOrBindingContext
  5247. : new ko.bindingContext(dataOrBindingContext, null, null, null, { "exportDependencies": true });
  5248. var templateName = resolveTemplateName(template, bindingContext['$data'], bindingContext),
  5249. renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
  5250. if (renderMode == "replaceNode") {
  5251. targetNodeOrNodeArray = renderedNodesArray;
  5252. firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  5253. }
  5254. },
  5255. null,
  5256. { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
  5257. );
  5258. } else {
  5259. // 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
  5260. return ko.memoization.memoize(function (domNode) {
  5261. ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
  5262. });
  5263. }
  5264. };
  5265. ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
  5266. // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
  5267. // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
  5268. var arrayItemContext, asName = options['as'];
  5269. // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
  5270. var executeTemplateForArrayItem = function (arrayValue, index) {
  5271. // Support selecting template as a function of the data being rendered
  5272. arrayItemContext = parentBindingContext['createChildContext'](arrayValue, {
  5273. 'as': asName,
  5274. 'noChildContext': options['noChildContext'],
  5275. 'extend': function(context) {
  5276. context['$index'] = index;
  5277. if (asName) {
  5278. context[asName + "Index"] = index;
  5279. }
  5280. }
  5281. });
  5282. var templateName = resolveTemplateName(template, arrayValue, arrayItemContext);
  5283. return executeTemplate(targetNode, "ignoreTargetNode", templateName, arrayItemContext, options);
  5284. };
  5285. // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
  5286. var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
  5287. activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
  5288. if (options['afterRender'])
  5289. options['afterRender'](addedNodesArray, arrayValue);
  5290. // release the "cache" variable, so that it can be collected by
  5291. // the GC when its value isn't used from within the bindings anymore.
  5292. arrayItemContext = null;
  5293. };
  5294. var setDomNodeChildrenFromArrayMapping = function (newArray, changeList) {
  5295. // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
  5296. // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
  5297. ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, newArray, executeTemplateForArrayItem, options, activateBindingsCallback, changeList]);
  5298. ko.bindingEvent.notify(targetNode, ko.bindingEvent.childrenComplete);
  5299. };
  5300. var shouldHideDestroyed = (options['includeDestroyed'] === false) || (ko.options['foreachHidesDestroyed'] && !options['includeDestroyed']);
  5301. if (!shouldHideDestroyed && !options['beforeRemove'] && ko.isObservableArray(arrayOrObservableArray)) {
  5302. setDomNodeChildrenFromArrayMapping(arrayOrObservableArray.peek());
  5303. var subscription = arrayOrObservableArray.subscribe(function (changeList) {
  5304. setDomNodeChildrenFromArrayMapping(arrayOrObservableArray(), changeList);
  5305. }, null, "arrayChange");
  5306. subscription.disposeWhenNodeIsRemoved(targetNode);
  5307. return subscription;
  5308. } else {
  5309. return ko.dependentObservable(function () {
  5310. var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
  5311. if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
  5312. unwrappedArray = [unwrappedArray];
  5313. if (shouldHideDestroyed) {
  5314. // Filter out any entries marked as destroyed
  5315. unwrappedArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
  5316. return item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
  5317. });
  5318. }
  5319. setDomNodeChildrenFromArrayMapping(unwrappedArray);
  5320. }, null, { disposeWhenNodeIsRemoved: targetNode });
  5321. }
  5322. };
  5323. var templateComputedDomDataKey = ko.utils.domData.nextKey();
  5324. function disposeOldComputedAndStoreNewOne(element, newComputed) {
  5325. var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
  5326. if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
  5327. oldComputed.dispose();
  5328. ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && (!newComputed.isActive || newComputed.isActive())) ? newComputed : undefined);
  5329. }
  5330. var cleanContainerDomDataKey = ko.utils.domData.nextKey();
  5331. ko.bindingHandlers['template'] = {
  5332. 'init': function(element, valueAccessor) {
  5333. // Support anonymous templates
  5334. var bindingValue = ko.utils.unwrapObservable(valueAccessor());
  5335. if (typeof bindingValue == "string" || 'name' in bindingValue) {
  5336. // It's a named template - clear the element
  5337. ko.virtualElements.emptyNode(element);
  5338. } else if ('nodes' in bindingValue) {
  5339. // We've been given an array of DOM nodes. Save them as the template source.
  5340. // There is no known use case for the node array being an observable array (if the output
  5341. // varies, put that behavior *into* your template - that's what templates are for), and
  5342. // the implementation would be a mess, so assert that it's not observable.
  5343. var nodes = bindingValue['nodes'] || [];
  5344. if (ko.isObservable(nodes)) {
  5345. throw new Error('The "nodes" option must be a plain, non-observable array.');
  5346. }
  5347. // If the nodes are already attached to a KO-generated container, we reuse that container without moving the
  5348. // elements to a new one (we check only the first node, as the nodes are always moved together)
  5349. var container = nodes[0] && nodes[0].parentNode;
  5350. if (!container || !ko.utils.domData.get(container, cleanContainerDomDataKey)) {
  5351. container = ko.utils.moveCleanedNodesToContainerElement(nodes);
  5352. ko.utils.domData.set(container, cleanContainerDomDataKey, true);
  5353. }
  5354. new ko.templateSources.anonymousTemplate(element)['nodes'](container);
  5355. } else {
  5356. // It's an anonymous template - store the element contents, then clear the element
  5357. var templateNodes = ko.virtualElements.childNodes(element);
  5358. if (templateNodes.length > 0) {
  5359. var container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
  5360. new ko.templateSources.anonymousTemplate(element)['nodes'](container);
  5361. } else {
  5362. throw new Error("Anonymous template defined, but no template content was provided");
  5363. }
  5364. }
  5365. return { 'controlsDescendantBindings': true };
  5366. },
  5367. 'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
  5368. var value = valueAccessor(),
  5369. options = ko.utils.unwrapObservable(value),
  5370. shouldDisplay = true,
  5371. templateComputed = null,
  5372. template;
  5373. if (typeof options == "string") {
  5374. template = value;
  5375. options = {};
  5376. } else {
  5377. template = 'name' in options ? options['name'] : element;
  5378. // Support "if"/"ifnot" conditions
  5379. if ('if' in options)
  5380. shouldDisplay = ko.utils.unwrapObservable(options['if']);
  5381. if (shouldDisplay && 'ifnot' in options)
  5382. shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
  5383. // Don't show anything if an empty name is given (see #2446)
  5384. if (shouldDisplay && !template) {
  5385. shouldDisplay = false;
  5386. }
  5387. }
  5388. if ('foreach' in options) {
  5389. // Render once for each data point (treating data set as empty if shouldDisplay==false)
  5390. var dataArray = (shouldDisplay && options['foreach']) || [];
  5391. templateComputed = ko.renderTemplateForEach(template, dataArray, options, element, bindingContext);
  5392. } else if (!shouldDisplay) {
  5393. ko.virtualElements.emptyNode(element);
  5394. } else {
  5395. // Render once for this single data point (or use the viewModel if no data was provided)
  5396. var innerBindingContext = bindingContext;
  5397. if ('data' in options) {
  5398. innerBindingContext = bindingContext['createChildContext'](options['data'], {
  5399. 'as': options['as'],
  5400. 'noChildContext': options['noChildContext'],
  5401. 'exportDependencies': true
  5402. });
  5403. }
  5404. templateComputed = ko.renderTemplate(template, innerBindingContext, options, element);
  5405. }
  5406. // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
  5407. disposeOldComputedAndStoreNewOne(element, templateComputed);
  5408. }
  5409. };
  5410. // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
  5411. ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
  5412. var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
  5413. if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
  5414. return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
  5415. if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
  5416. return null; // Named templates can be rewritten, so return "no error"
  5417. return "This template engine does not support anonymous templates nested within its templates";
  5418. };
  5419. ko.virtualElements.allowedBindings['template'] = true;
  5420. })();
  5421. ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
  5422. ko.exportSymbol('renderTemplate', ko.renderTemplate);
  5423. // Go through the items that have been added and deleted and try to find matches between them.
  5424. ko.utils.findMovesInArrayComparison = function (left, right, limitFailedCompares) {
  5425. if (left.length && right.length) {
  5426. var failedCompares, l, r, leftItem, rightItem;
  5427. for (failedCompares = l = 0; (!limitFailedCompares || failedCompares < limitFailedCompares) && (leftItem = left[l]); ++l) {
  5428. for (r = 0; rightItem = right[r]; ++r) {
  5429. if (leftItem['value'] === rightItem['value']) {
  5430. leftItem['moved'] = rightItem['index'];
  5431. rightItem['moved'] = leftItem['index'];
  5432. right.splice(r, 1); // This item is marked as moved; so remove it from right list
  5433. failedCompares = r = 0; // Reset failed compares count because we're checking for consecutive failures
  5434. break;
  5435. }
  5436. }
  5437. failedCompares += r;
  5438. }
  5439. }
  5440. };
  5441. ko.utils.compareArrays = (function () {
  5442. var statusNotInOld = 'added', statusNotInNew = 'deleted';
  5443. // Simple calculation based on Levenshtein distance.
  5444. function compareArrays(oldArray, newArray, options) {
  5445. // For backward compatibility, if the third arg is actually a bool, interpret
  5446. // it as the old parameter 'dontLimitMoves'. Newer code should use { dontLimitMoves: true }.
  5447. options = (typeof options === 'boolean') ? { 'dontLimitMoves': options } : (options || {});
  5448. oldArray = oldArray || [];
  5449. newArray = newArray || [];
  5450. if (oldArray.length < newArray.length)
  5451. return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, options);
  5452. else
  5453. return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, options);
  5454. }
  5455. function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, options) {
  5456. var myMin = Math.min,
  5457. myMax = Math.max,
  5458. editDistanceMatrix = [],
  5459. smlIndex, smlIndexMax = smlArray.length,
  5460. bigIndex, bigIndexMax = bigArray.length,
  5461. compareRange = (bigIndexMax - smlIndexMax) || 1,
  5462. maxDistance = smlIndexMax + bigIndexMax + 1,
  5463. thisRow, lastRow,
  5464. bigIndexMaxForRow, bigIndexMinForRow;
  5465. for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
  5466. lastRow = thisRow;
  5467. editDistanceMatrix.push(thisRow = []);
  5468. bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
  5469. bigIndexMinForRow = myMax(0, smlIndex - 1);
  5470. for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
  5471. if (!bigIndex)
  5472. thisRow[bigIndex] = smlIndex + 1;
  5473. else if (!smlIndex) // Top row - transform empty array into new array via additions
  5474. thisRow[bigIndex] = bigIndex + 1;
  5475. else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
  5476. thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
  5477. else {
  5478. var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
  5479. var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
  5480. thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
  5481. }
  5482. }
  5483. }
  5484. var editScript = [], meMinusOne, notInSml = [], notInBig = [];
  5485. for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
  5486. meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
  5487. if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
  5488. notInSml.push(editScript[editScript.length] = { // added
  5489. 'status': statusNotInSml,
  5490. 'value': bigArray[--bigIndex],
  5491. 'index': bigIndex });
  5492. } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
  5493. notInBig.push(editScript[editScript.length] = { // deleted
  5494. 'status': statusNotInBig,
  5495. 'value': smlArray[--smlIndex],
  5496. 'index': smlIndex });
  5497. } else {
  5498. --bigIndex;
  5499. --smlIndex;
  5500. if (!options['sparse']) {
  5501. editScript.push({
  5502. 'status': "retained",
  5503. 'value': bigArray[bigIndex] });
  5504. }
  5505. }
  5506. }
  5507. // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
  5508. // smlIndexMax keeps the time complexity of this algorithm linear.
  5509. ko.utils.findMovesInArrayComparison(notInBig, notInSml, !options['dontLimitMoves'] && smlIndexMax * 10);
  5510. return editScript.reverse();
  5511. }
  5512. return compareArrays;
  5513. })();
  5514. ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
  5515. (function () {
  5516. // Objective:
  5517. // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
  5518. // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
  5519. // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
  5520. // 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
  5521. // previously mapped - retain those nodes, and just insert/delete other ones
  5522. // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
  5523. // You can use this, for example, to activate bindings on those nodes.
  5524. function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
  5525. // Map this array value inside a dependentObservable so we re-map when any dependency changes
  5526. var mappedNodes = [];
  5527. var dependentObservable = ko.dependentObservable(function() {
  5528. var newMappedNodes = mapping(valueToMap, index, ko.utils.fixUpContinuousNodeArray(mappedNodes, containerNode)) || [];
  5529. // On subsequent evaluations, just replace the previously-inserted DOM nodes
  5530. if (mappedNodes.length > 0) {
  5531. ko.utils.replaceDomNodes(mappedNodes, newMappedNodes);
  5532. if (callbackAfterAddingNodes)
  5533. ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
  5534. }
  5535. // Replace the contents of the mappedNodes array, thereby updating the record
  5536. // of which nodes would be deleted if valueToMap was itself later removed
  5537. mappedNodes.length = 0;
  5538. ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
  5539. }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return !ko.utils.anyDomNodeIsAttachedToDocument(mappedNodes); } });
  5540. return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
  5541. }
  5542. var lastMappingResultDomDataKey = ko.utils.domData.nextKey(),
  5543. deletedItemDummyValue = ko.utils.domData.nextKey();
  5544. ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes, editScript) {
  5545. array = array || [];
  5546. if (typeof array.length == "undefined") // Coerce single value into array
  5547. array = [array];
  5548. options = options || {};
  5549. var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey);
  5550. var isFirstExecution = !lastMappingResult;
  5551. // Build the new mapping result
  5552. var newMappingResult = [];
  5553. var lastMappingResultIndex = 0;
  5554. var currentArrayIndex = 0;
  5555. var nodesToDelete = [];
  5556. var itemsToMoveFirstIndexes = [];
  5557. var itemsForBeforeRemoveCallbacks = [];
  5558. var itemsForMoveCallbacks = [];
  5559. var itemsForAfterAddCallbacks = [];
  5560. var mapData;
  5561. var countWaitingForRemove = 0;
  5562. function itemAdded(value) {
  5563. mapData = { arrayEntry: value, indexObservable: ko.observable(currentArrayIndex++) };
  5564. newMappingResult.push(mapData);
  5565. if (!isFirstExecution) {
  5566. itemsForAfterAddCallbacks.push(mapData);
  5567. }
  5568. }
  5569. function itemMovedOrRetained(oldPosition) {
  5570. mapData = lastMappingResult[oldPosition];
  5571. if (currentArrayIndex !== mapData.indexObservable.peek())
  5572. itemsForMoveCallbacks.push(mapData);
  5573. // Since updating the index might change the nodes, do so before calling fixUpContinuousNodeArray
  5574. mapData.indexObservable(currentArrayIndex++);
  5575. ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode);
  5576. newMappingResult.push(mapData);
  5577. }
  5578. function callCallback(callback, items) {
  5579. if (callback) {
  5580. for (var i = 0, n = items.length; i < n; i++) {
  5581. ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
  5582. callback(node, i, items[i].arrayEntry);
  5583. });
  5584. }
  5585. }
  5586. }
  5587. if (isFirstExecution) {
  5588. ko.utils.arrayForEach(array, itemAdded);
  5589. } else {
  5590. if (!editScript || (lastMappingResult && lastMappingResult['_countWaitingForRemove'])) {
  5591. // Compare the provided array against the previous one
  5592. var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; }),
  5593. compareOptions = {
  5594. 'dontLimitMoves': options['dontLimitMoves'],
  5595. 'sparse': true
  5596. };
  5597. editScript = ko.utils.compareArrays(lastArray, array, compareOptions);
  5598. }
  5599. for (var i = 0, editScriptItem, movedIndex, itemIndex; editScriptItem = editScript[i]; i++) {
  5600. movedIndex = editScriptItem['moved'];
  5601. itemIndex = editScriptItem['index'];
  5602. switch (editScriptItem['status']) {
  5603. case "deleted":
  5604. while (lastMappingResultIndex < itemIndex) {
  5605. itemMovedOrRetained(lastMappingResultIndex++);
  5606. }
  5607. if (movedIndex === undefined) {
  5608. mapData = lastMappingResult[lastMappingResultIndex];
  5609. // Stop tracking changes to the mapping for these nodes
  5610. if (mapData.dependentObservable) {
  5611. mapData.dependentObservable.dispose();
  5612. mapData.dependentObservable = undefined;
  5613. }
  5614. // Queue these nodes for later removal
  5615. if (ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode).length) {
  5616. if (options['beforeRemove']) {
  5617. newMappingResult.push(mapData);
  5618. countWaitingForRemove++;
  5619. if (mapData.arrayEntry === deletedItemDummyValue) {
  5620. mapData = null;
  5621. } else {
  5622. itemsForBeforeRemoveCallbacks.push(mapData);
  5623. }
  5624. }
  5625. if (mapData) {
  5626. nodesToDelete.push.apply(nodesToDelete, mapData.mappedNodes);
  5627. }
  5628. }
  5629. }
  5630. lastMappingResultIndex++;
  5631. break;
  5632. case "added":
  5633. while (currentArrayIndex < itemIndex) {
  5634. itemMovedOrRetained(lastMappingResultIndex++);
  5635. }
  5636. if (movedIndex !== undefined) {
  5637. itemsToMoveFirstIndexes.push(newMappingResult.length);
  5638. itemMovedOrRetained(movedIndex);
  5639. } else {
  5640. itemAdded(editScriptItem['value']);
  5641. }
  5642. break;
  5643. }
  5644. }
  5645. while (currentArrayIndex < array.length) {
  5646. itemMovedOrRetained(lastMappingResultIndex++);
  5647. }
  5648. // Record that the current view may still contain deleted items
  5649. // because it means we won't be able to use a provided editScript.
  5650. newMappingResult['_countWaitingForRemove'] = countWaitingForRemove;
  5651. }
  5652. // Store a copy of the array items we just considered so we can difference it next time
  5653. ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
  5654. // Call beforeMove first before any changes have been made to the DOM
  5655. callCallback(options['beforeMove'], itemsForMoveCallbacks);
  5656. // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
  5657. ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
  5658. var i, j, lastNode, nodeToInsert, mappedNodes, activeElement;
  5659. // Since most browsers remove the focus from an element when it's moved to another location,
  5660. // save the focused element and try to restore it later.
  5661. try {
  5662. activeElement = domNode.ownerDocument.activeElement;
  5663. } catch(e) {
  5664. // IE9 throws if you access activeElement during page load (see issue #703)
  5665. }
  5666. // Try to reduce overall moved nodes by first moving the ones that were marked as moved by the edit script
  5667. if (itemsToMoveFirstIndexes.length) {
  5668. while ((i = itemsToMoveFirstIndexes.shift()) != undefined) {
  5669. mapData = newMappingResult[i];
  5670. for (lastNode = undefined; i; ) {
  5671. if ((mappedNodes = newMappingResult[--i].mappedNodes) && mappedNodes.length) {
  5672. lastNode = mappedNodes[mappedNodes.length-1];
  5673. break;
  5674. }
  5675. }
  5676. for (j = 0; nodeToInsert = mapData.mappedNodes[j]; lastNode = nodeToInsert, j++) {
  5677. ko.virtualElements.insertAfter(domNode, nodeToInsert, lastNode);
  5678. }
  5679. }
  5680. }
  5681. // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
  5682. for (i = 0; mapData = newMappingResult[i]; i++) {
  5683. // Get nodes for newly added items
  5684. if (!mapData.mappedNodes)
  5685. ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
  5686. // Put nodes in the right place if they aren't there already
  5687. for (j = 0; nodeToInsert = mapData.mappedNodes[j]; lastNode = nodeToInsert, j++) {
  5688. ko.virtualElements.insertAfter(domNode, nodeToInsert, lastNode);
  5689. }
  5690. // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
  5691. if (!mapData.initialized && callbackAfterAddingNodes) {
  5692. callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
  5693. mapData.initialized = true;
  5694. lastNode = mapData.mappedNodes[mapData.mappedNodes.length - 1]; // get the last node again since it may have been changed by a preprocessor
  5695. }
  5696. }
  5697. // Restore the focused element if it had lost focus
  5698. if (activeElement && domNode.ownerDocument.activeElement != activeElement) {
  5699. activeElement.focus();
  5700. }
  5701. // If there's a beforeRemove callback, call it after reordering.
  5702. // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
  5703. // some sort of animation, which is why we first reorder the nodes that will be removed. If the
  5704. // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
  5705. // Perhaps we'll make that change in the future if this scenario becomes more common.
  5706. callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
  5707. // Replace the stored values of deleted items with a dummy value. This provides two benefits: it marks this item
  5708. // as already "removed" so we won't call beforeRemove for it again, and it ensures that the item won't match up
  5709. // with an actual item in the array and appear as "retained" or "moved".
  5710. for (i = 0; i < itemsForBeforeRemoveCallbacks.length; ++i) {
  5711. itemsForBeforeRemoveCallbacks[i].arrayEntry = deletedItemDummyValue;
  5712. }
  5713. // Finally call afterMove and afterAdd callbacks
  5714. callCallback(options['afterMove'], itemsForMoveCallbacks);
  5715. callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
  5716. }
  5717. })();
  5718. ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
  5719. ko.nativeTemplateEngine = function () {
  5720. this['allowTemplateRewriting'] = false;
  5721. }
  5722. ko.nativeTemplateEngine.prototype = new ko.templateEngine();
  5723. ko.nativeTemplateEngine.prototype.constructor = ko.nativeTemplateEngine;
  5724. ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options, templateDocument) {
  5725. var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
  5726. templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
  5727. templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
  5728. if (templateNodes) {
  5729. return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
  5730. } else {
  5731. var templateText = templateSource['text']();
  5732. return ko.utils.parseHtmlFragment(templateText, templateDocument);
  5733. }
  5734. };
  5735. ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
  5736. ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
  5737. ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
  5738. (function() {
  5739. ko.jqueryTmplTemplateEngine = function () {
  5740. // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
  5741. // doesn't expose a version number, so we have to infer it.
  5742. // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
  5743. // which KO internally refers to as version "2", so older versions are no longer detected.
  5744. var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
  5745. if (!jQueryInstance || !(jQueryInstance['tmpl']))
  5746. return 0;
  5747. // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
  5748. try {
  5749. if (jQueryInstance['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
  5750. // Since 1.0.0pre, custom tags should append markup to an array called "__"
  5751. return 2; // Final version of jquery.tmpl
  5752. }
  5753. } catch(ex) { /* Apparently not the version we were looking for */ }
  5754. return 1; // Any older version that we don't support
  5755. })();
  5756. function ensureHasReferencedJQueryTemplates() {
  5757. if (jQueryTmplVersion < 2)
  5758. throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
  5759. }
  5760. function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
  5761. return jQueryInstance['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
  5762. }
  5763. this['renderTemplateSource'] = function(templateSource, bindingContext, options, templateDocument) {
  5764. templateDocument = templateDocument || document;
  5765. options = options || {};
  5766. ensureHasReferencedJQueryTemplates();
  5767. // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
  5768. var precompiled = templateSource['data']('precompiled');
  5769. if (!precompiled) {
  5770. var templateText = templateSource['text']() || "";
  5771. // Wrap in "with($whatever.koBindingContext) { ... }"
  5772. templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
  5773. precompiled = jQueryInstance['template'](null, templateText);
  5774. templateSource['data']('precompiled', precompiled);
  5775. }
  5776. var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
  5777. var jQueryTemplateOptions = jQueryInstance['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
  5778. var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
  5779. resultNodes['appendTo'](templateDocument.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
  5780. jQueryInstance['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
  5781. return resultNodes;
  5782. };
  5783. this['createJavaScriptEvaluatorBlock'] = function(script) {
  5784. return "{{ko_code ((function() { return " + script + " })()) }}";
  5785. };
  5786. this['addTemplate'] = function(templateName, templateMarkup) {
  5787. document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "<" + "/script>");
  5788. };
  5789. if (jQueryTmplVersion > 0) {
  5790. jQueryInstance['tmpl']['tag']['ko_code'] = {
  5791. open: "__.push($1 || '');"
  5792. };
  5793. jQueryInstance['tmpl']['tag']['ko_with'] = {
  5794. open: "with($1) {",
  5795. close: "} "
  5796. };
  5797. }
  5798. };
  5799. ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
  5800. ko.jqueryTmplTemplateEngine.prototype.constructor = ko.jqueryTmplTemplateEngine;
  5801. // Use this one by default *only if jquery.tmpl is referenced*
  5802. var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
  5803. if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
  5804. ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
  5805. ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
  5806. })();
  5807. }));
  5808. }());
  5809. })();