/assets/vendor/ko/knockout.js

https://bitbucket.org/grid13/yii-knockout-jsplum · JavaScript · 3564 lines · 2969 code · 303 blank · 292 comment · 608 complexity · 366ab33cc62e55a46125a00436919756 MD5 · raw file

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