Advertisement
Guest User

Untitled

a guest
Jan 18th, 2019
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*!
  2.  * Knockout JavaScript library v3.4.2
  3.  * (c) The Knockout.js team - http://knockoutjs.com/
  4.  * License: MIT (http://www.opensource.org/licenses/mit-license.php)
  5.  */
  6.  
  7. (function(){
  8. var DEBUG=true;
  9. (function(undefined){
  10.     // (0, eval)('this') is a robust way of getting a reference to the global object
  11.     // For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023
  12.     var window = this || (0, eval)('this'),
  13.         document = window['document'],
  14.         navigator = window['navigator'],
  15.         jQueryInstance = window["jQuery"],
  16.         JSON = window["JSON"];
  17. (function(factory) {
  18.     // Support three module loading scenarios
  19.     if (typeof define === 'function' && define['amd']) {
  20.         // [1] AMD anonymous module
  21.         define(['exports', 'require'], factory);
  22.     } else if (typeof exports === 'object' && typeof module === 'object') {
  23.         // [2] CommonJS/Node.js
  24.         factory(module['exports'] || exports);  // module.exports is for Node.js
  25.     } else {
  26.         // [3] No module loader (plain <script> tag) - put directly in global namespace
  27.         factory(window['ko'] = {});
  28.     }
  29. }(function(koExports, amdRequire){
  30. // Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
  31. // In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
  32. var ko = typeof koExports !== 'undefined' ? koExports : {};
  33. // Google Closure Compiler helpers (used only to make the minified file smaller)
  34. ko.exportSymbol = function(koPath, object) {
  35.     var tokens = koPath.split(".");
  36.  
  37.     // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
  38.     // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
  39.     var target = ko;
  40.  
  41.     for (var i = 0; i < tokens.length - 1; i++)
  42.         target = target[tokens[i]];
  43.     target[tokens[tokens.length - 1]] = object;
  44. };
  45. ko.exportProperty = function(owner, publicName, object) {
  46.     owner[publicName] = object;
  47. };
  48. ko.version = "3.4.2";
  49.  
  50. ko.exportSymbol('version', ko.version);
  51. // For any options that may affect various areas of Knockout and aren't directly associated with data binding.
  52. ko.options = {
  53.     'deferUpdates': false,
  54.     'useOnlyNativeEvents': false
  55. };
  56.  
  57. //ko.exportSymbol('options', ko.options);   // 'options' isn't minified
  58. ko.utils = (function () {
  59.     function objectForEach(obj, action) {
  60.         for (var prop in obj) {
  61.             if (obj.hasOwnProperty(prop)) {
  62.                 action(prop, obj[prop]);
  63.             }
  64.         }
  65.     }
  66.  
  67.     function extend(target, source) {
  68.         if (source) {
  69.             for(var prop in source) {
  70.                 if(source.hasOwnProperty(prop)) {
  71.                     target[prop] = source[prop];
  72.                 }
  73.             }
  74.         }
  75.         return target;
  76.     }
  77.  
  78.     function setPrototypeOf(obj, proto) {
  79.         obj.__proto__ = proto;
  80.         return obj;
  81.     }
  82.  
  83.     var canSetPrototype = ({ __proto__: [] } instanceof Array);
  84.     var canUseSymbols = !DEBUG && typeof Symbol === 'function';
  85.  
  86.     // 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)
  87.     var knownEvents = {}, knownEventTypesByEventName = {};
  88.     var keyEventTypeName = (navigator && /Firefox\/2/i.test(navigator.userAgent)) ? 'KeyboardEvent' : 'UIEvents';
  89.     knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
  90.     knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
  91.     objectForEach(knownEvents, function(eventType, knownEventsForType) {
  92.         if (knownEventsForType.length) {
  93.             for (var i = 0, j = knownEventsForType.length; i < j; i++)
  94.                 knownEventTypesByEventName[knownEventsForType[i]] = eventType;
  95.         }
  96.     });
  97.     var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
  98.  
  99.     // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
  100.     // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
  101.     // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
  102.     // If there is a future need to detect specific versions of IE10+, we will amend this.
  103.     var ieVersion = document && (function() {
  104.         var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
  105.  
  106.         // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
  107.         while (
  108.             div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
  109.             iElems[0]
  110.         ) {}
  111.         return version > 4 ? version : undefined;
  112.     }());
  113.     var isIe6 = ieVersion === 6,
  114.         isIe7 = ieVersion === 7;
  115.  
  116.     function isClickOnCheckableElement(element, eventType) {
  117.         if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
  118.         if (eventType.toLowerCase() != "click") return false;
  119.         var inputType = element.type;
  120.         return (inputType == "checkbox") || (inputType == "radio");
  121.     }
  122.  
  123.     // For details on the pattern for changing node classes
  124.     // see: https://github.com/knockout/knockout/issues/1597
  125.     var cssClassNameRegex = /\S+/g;
  126.  
  127.     function toggleDomNodeCssClass(node, classNames, shouldHaveClass) {
  128.         var addOrRemoveFn;
  129.         if (classNames) {
  130.             if (typeof node.classList === 'object') {
  131.                 addOrRemoveFn = node.classList[shouldHaveClass ? 'add' : 'remove'];
  132.                 ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
  133.                     addOrRemoveFn.call(node.classList, className);
  134.                 });
  135.             } else if (typeof node.className['baseVal'] === 'string') {
  136.                 // SVG tag .classNames is an SVGAnimatedString instance
  137.                 toggleObjectClassPropertyString(node.className, 'baseVal', classNames, shouldHaveClass);
  138.             } else {
  139.                 // node.className ought to be a string.
  140.                 toggleObjectClassPropertyString(node, 'className', classNames, shouldHaveClass);
  141.             }
  142.         }
  143.     }
  144.  
  145.     function toggleObjectClassPropertyString(obj, prop, classNames, shouldHaveClass) {
  146.         // obj/prop is either a node/'className' or a SVGAnimatedString/'baseVal'.
  147.         var currentClassNames = obj[prop].match(cssClassNameRegex) || [];
  148.         ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
  149.             ko.utils.addOrRemoveItem(currentClassNames, className, shouldHaveClass);
  150.         });
  151.         obj[prop] = currentClassNames.join(" ");
  152.     }
  153.  
  154.     return {
  155.         fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
  156.  
  157.         arrayForEach: function (array, action) {
  158.             for (var i = 0, j = array.length; i < j; i++)
  159.                 action(array[i], i);
  160.         },
  161.  
  162.         arrayIndexOf: function (array, item) {
  163.             if (typeof Array.prototype.indexOf == "function")
  164.                 return Array.prototype.indexOf.call(array, item);
  165.             for (var i = 0, j = array.length; i < j; i++)
  166.                 if (array[i] === item)
  167.                     return i;
  168.             return -1;
  169.         },
  170.  
  171.         arrayFirst: function (array, predicate, predicateOwner) {
  172.             for (var i = 0, j = array.length; i < j; i++)
  173.                 if (predicate.call(predicateOwner, array[i], i))
  174.                     return array[i];
  175.             return null;
  176.         },
  177.  
  178.         arrayRemoveItem: function (array, itemToRemove) {
  179.             var index = ko.utils.arrayIndexOf(array, itemToRemove);
  180.             if (index > 0) {
  181.                 array.splice(index, 1);
  182.             }
  183.             else if (index === 0) {
  184.                 array.shift();
  185.             }
  186.         },
  187.  
  188.         arrayGetDistinctValues: function (array) {
  189.             array = array || [];
  190.             var result = [];
  191.             for (var i = 0, j = array.length; i < j; i++) {
  192.                 if (ko.utils.arrayIndexOf(result, array[i]) < 0)
  193.                     result.push(array[i]);
  194.             }
  195.             return result;
  196.         },
  197.  
  198.         arrayMap: function (array, mapping) {
  199.             array = array || [];
  200.             var result = [];
  201.             for (var i = 0, j = array.length; i < j; i++)
  202.                 result.push(mapping(array[i], i));
  203.             return result;
  204.         },
  205.  
  206.         arrayFilter: function (array, predicate) {
  207.             array = array || [];
  208.             var result = [];
  209.             for (var i = 0, j = array.length; i < j; i++)
  210.                 if (predicate(array[i], i))
  211.                     result.push(array[i]);
  212.             return result;
  213.         },
  214.  
  215.         arrayPushAll: function (array, valuesToPush) {
  216.             if (valuesToPush instanceof Array)
  217.                 array.push.apply(array, valuesToPush);
  218.             else
  219.                 for (var i = 0, j = valuesToPush.length; i < j; i++)
  220.                     array.push(valuesToPush[i]);
  221.             return array;
  222.         },
  223.  
  224.         addOrRemoveItem: function(array, value, included) {
  225.             var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.peekObservable(array), value);
  226.             if (existingEntryIndex < 0) {
  227.                 if (included)
  228.                     array.push(value);
  229.             } else {
  230.                 if (!included)
  231.                     array.splice(existingEntryIndex, 1);
  232.             }
  233.         },
  234.  
  235.         canSetPrototype: canSetPrototype,
  236.  
  237.         extend: extend,
  238.  
  239.         setPrototypeOf: setPrototypeOf,
  240.  
  241.         setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : extend,
  242.  
  243.         objectForEach: objectForEach,
  244.  
  245.         objectMap: function(source, mapping) {
  246.             if (!source)
  247.                 return source;
  248.             var target = {};
  249.             for (var prop in source) {
  250.                 if (source.hasOwnProperty(prop)) {
  251.                     target[prop] = mapping(source[prop], prop, source);
  252.                 }
  253.             }
  254.             return target;
  255.         },
  256.  
  257.         emptyDomNode: function (domNode) {
  258.             while (domNode.firstChild) {
  259.                 ko.removeNode(domNode.firstChild);
  260.             }
  261.         },
  262.  
  263.         moveCleanedNodesToContainerElement: function(nodes) {
  264.             // Ensure it's a real array, as we're about to reparent the nodes and
  265.             // we don't want the underlying collection to change while we're doing that.
  266.             var nodesArray = ko.utils.makeArray(nodes);
  267.             var templateDocument = (nodesArray[0] && nodesArray[0].ownerDocument) || document;
  268.  
  269.             var container = templateDocument.createElement('div');
  270.             for (var i = 0, j = nodesArray.length; i < j; i++) {
  271.                 container.appendChild(ko.cleanNode(nodesArray[i]));
  272.             }
  273.             return container;
  274.         },
  275.  
  276.         cloneNodes: function (nodesArray, shouldCleanNodes) {
  277.             for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
  278.                 var clonedNode = nodesArray[i].cloneNode(true);
  279.                 newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
  280.             }
  281.             return newNodesArray;
  282.         },
  283.  
  284.         setDomNodeChildren: function (domNode, childNodes) {
  285.             ko.utils.emptyDomNode(domNode);
  286.             if (childNodes) {
  287.                 for (var i = 0, j = childNodes.length; i < j; i++)
  288.                     domNode.appendChild(childNodes[i]);
  289.             }
  290.         },
  291.  
  292.         replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
  293.             var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
  294.             if (nodesToReplaceArray.length > 0) {
  295.                 var insertionPoint = nodesToReplaceArray[0];
  296.                 var parent = insertionPoint.parentNode;
  297.                 for (var i = 0, j = newNodesArray.length; i < j; i++)
  298.                     parent.insertBefore(newNodesArray[i], insertionPoint);
  299.                 for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
  300.                     ko.removeNode(nodesToReplaceArray[i]);
  301.                 }
  302.             }
  303.         },
  304.  
  305.         fixUpContinuousNodeArray: function(continuousNodeArray, parentNode) {
  306.             // Before acting on a set of nodes that were previously outputted by a template function, we have to reconcile
  307.             // them against what is in the DOM right now. It may be that some of the nodes have already been removed, or that
  308.             // new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
  309.             // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
  310.             // So, this function translates the old "map" output array into its best guess of the set of current DOM nodes.
  311.             //
  312.             // Rules:
  313.             //   [A] Any leading nodes that have been removed should be ignored
  314.             //       These most likely correspond to memoization nodes that were already removed during binding
  315.             //       See https://github.com/knockout/knockout/pull/440
  316.             //   [B] Any trailing nodes that have been remove should be ignored
  317.             //       This prevents the code here from adding unrelated nodes to the array while processing rule [C]
  318.             //       See https://github.com/knockout/knockout/pull/1903
  319.             //   [C] We want to output a continuous series of nodes. So, ignore any nodes that have already been removed,
  320.             //       and include any nodes that have been inserted among the previous collection
  321.  
  322.             if (continuousNodeArray.length) {
  323.                 // The parent node can be a virtual element; so get the real parent node
  324.                 parentNode = (parentNode.nodeType === 8 && parentNode.parentNode) || parentNode;
  325.  
  326.                 // Rule [A]
  327.                 while (continuousNodeArray.length && continuousNodeArray[0].parentNode !== parentNode)
  328.                     continuousNodeArray.splice(0, 1);
  329.  
  330.                 // Rule [B]
  331.                 while (continuousNodeArray.length > 1 && continuousNodeArray[continuousNodeArray.length - 1].parentNode !== parentNode)
  332.                     continuousNodeArray.length--;
  333.  
  334.                 // Rule [C]
  335.                 if (continuousNodeArray.length > 1) {
  336.                     var current = continuousNodeArray[0], last = continuousNodeArray[continuousNodeArray.length - 1];
  337.                     // Replace with the actual new continuous node set
  338.                     continuousNodeArray.length = 0;
  339.                     while (current !== last) {
  340.                         continuousNodeArray.push(current);
  341.                         current = current.nextSibling;
  342.                     }
  343.                     continuousNodeArray.push(last);
  344.                 }
  345.             }
  346.             return continuousNodeArray;
  347.         },
  348.  
  349.         setOptionNodeSelectionState: function (optionNode, isSelected) {
  350.             // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
  351.             if (ieVersion < 7)
  352.                 optionNode.setAttribute("selected", isSelected);
  353.             else
  354.                 optionNode.selected = isSelected;
  355.         },
  356.  
  357.         stringTrim: function (string) {
  358.             return string === null || string === undefined ? '' :
  359.                 string.trim ?
  360.                     string.trim() :
  361.                     string.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
  362.         },
  363.  
  364.         stringStartsWith: function (string, startsWith) {
  365.             string = string || "";
  366.             if (startsWith.length > string.length)
  367.                 return false;
  368.             return string.substring(0, startsWith.length) === startsWith;
  369.         },
  370.  
  371.         domNodeIsContainedBy: function (node, containedByNode) {
  372.             if (node === containedByNode)
  373.                 return true;
  374.             if (node.nodeType === 11)
  375.                 return false; // Fixes issue #1162 - can't use node.contains for document fragments on IE8
  376.             if (containedByNode.contains)
  377.                 return containedByNode.contains(node.nodeType === 3 ? node.parentNode : node);
  378.             if (containedByNode.compareDocumentPosition)
  379.                 return (containedByNode.compareDocumentPosition(node) & 16) == 16;
  380.             while (node && node != containedByNode) {
  381.                 node = node.parentNode;
  382.             }
  383.             return !!node;
  384.         },
  385.  
  386.         domNodeIsAttachedToDocument: function (node) {
  387.             return ko.utils.domNodeIsContainedBy(node, node.ownerDocument.documentElement);
  388.         },
  389.  
  390.         anyDomNodeIsAttachedToDocument: function(nodes) {
  391.             return !!ko.utils.arrayFirst(nodes, ko.utils.domNodeIsAttachedToDocument);
  392.         },
  393.  
  394.         tagNameLower: function(element) {
  395.             // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
  396.             // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
  397.             // we don't need to do the .toLowerCase() as it will always be lower case anyway.
  398.             return element && element.tagName && element.tagName.toLowerCase();
  399.         },
  400.  
  401.         catchFunctionErrors: function (delegate) {
  402.             return ko['onError'] ? function () {
  403.                 try {
  404.                     return delegate.apply(this, arguments);
  405.                 } catch (e) {
  406.                     ko['onError'] && ko['onError'](e);
  407.                     throw e;
  408.                 }
  409.             } : delegate;
  410.         },
  411.  
  412.         setTimeout: function (handler, timeout) {
  413.             return setTimeout(ko.utils.catchFunctionErrors(handler), timeout);
  414.         },
  415.  
  416.         deferError: function (error) {
  417.             setTimeout(function () {
  418.                 ko['onError'] && ko['onError'](error);
  419.                 throw error;
  420.             }, 0);
  421.         },
  422.  
  423.         registerEventHandler: function (element, eventType, handler) {
  424.             var wrappedHandler = ko.utils.catchFunctionErrors(handler);
  425.  
  426.             var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
  427.             if (!ko.options['useOnlyNativeEvents'] && !mustUseAttachEvent && jQueryInstance) {
  428.                 jQueryInstance(element)['bind'](eventType, wrappedHandler);
  429.             } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
  430.                 element.addEventListener(eventType, wrappedHandler, false);
  431.             else if (typeof element.attachEvent != "undefined") {
  432.                 var attachEventHandler = function (event) { wrappedHandler.call(element, event); },
  433.                     attachEventName = "on" + eventType;
  434.                 element.attachEvent(attachEventName, attachEventHandler);
  435.  
  436.                 // IE does not dispose attachEvent handlers automatically (unlike with addEventListener)
  437.                 // so to avoid leaks, we have to remove them manually. See bug #856
  438.                 ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
  439.                     element.detachEvent(attachEventName, attachEventHandler);
  440.                 });
  441.             } else
  442.                 throw new Error("Browser doesn't support addEventListener or attachEvent");
  443.         },
  444.  
  445.         triggerEvent: function (element, eventType) {
  446.             if (!(element && element.nodeType))
  447.                 throw new Error("element must be a DOM node when calling triggerEvent");
  448.  
  449.             // For click events on checkboxes and radio buttons, jQuery toggles the element checked state *after* the
  450.             // event handler runs instead of *before*. (This was fixed in 1.9 for checkboxes but not for radio buttons.)
  451.             // IE doesn't change the checked state when you trigger the click event using "fireEvent".
  452.             // In both cases, we'll use the click method instead.
  453.             var useClickWorkaround = isClickOnCheckableElement(element, eventType);
  454.  
  455.             if (!ko.options['useOnlyNativeEvents'] && jQueryInstance && !useClickWorkaround) {
  456.                 jQueryInstance(element)['trigger'](eventType);
  457.             } else if (typeof document.createEvent == "function") {
  458.                 if (typeof element.dispatchEvent == "function") {
  459.                     var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
  460.                     var event = document.createEvent(eventCategory);
  461.                     event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
  462.                     element.dispatchEvent(event);
  463.                 }
  464.                 else
  465.                     throw new Error("The supplied element doesn't support dispatchEvent");
  466.             } else if (useClickWorkaround && element.click) {
  467.                 element.click();
  468.             } else if (typeof element.fireEvent != "undefined") {
  469.                 element.fireEvent("on" + eventType);
  470.             } else {
  471.                 throw new Error("Browser doesn't support triggering events");
  472.             }
  473.         },
  474.  
  475.         unwrapObservable: function (value) {
  476.             return ko.isObservable(value) ? value() : value;
  477.         },
  478.  
  479.         peekObservable: function (value) {
  480.             return ko.isObservable(value) ? value.peek() : value;
  481.         },
  482.  
  483.         toggleDomNodeCssClass: toggleDomNodeCssClass,
  484.  
  485.         setTextContent: function(element, textContent) {
  486.             var value = ko.utils.unwrapObservable(textContent);
  487.             if ((value === null) || (value === undefined))
  488.                 value = "";
  489.  
  490.             // We need there to be exactly one child: a text node.
  491.             // If there are no children, more than one, or if it's not a text node,
  492.             // we'll clear everything and create a single text node.
  493.             var innerTextNode = ko.virtualElements.firstChild(element);
  494.             if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
  495.                 ko.virtualElements.setDomNodeChildren(element, [element.ownerDocument.createTextNode(value)]);
  496.             } else {
  497.                 innerTextNode.data = value;
  498.             }
  499.  
  500.             ko.utils.forceRefresh(element);
  501.         },
  502.  
  503.         setElementName: function(element, name) {
  504.             element.name = name;
  505.  
  506.             // Workaround IE 6/7 issue
  507.             // - https://github.com/SteveSanderson/knockout/issues/197
  508.             // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
  509.             if (ieVersion <= 7) {
  510.                 try {
  511.                     element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
  512.                 }
  513.                 catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
  514.             }
  515.         },
  516.  
  517.         forceRefresh: function(node) {
  518.             // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
  519.             if (ieVersion >= 9) {
  520.                 // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
  521.                 var elem = node.nodeType == 1 ? node : node.parentNode;
  522.                 if (elem.style)
  523.                     elem.style.zoom = elem.style.zoom;
  524.             }
  525.         },
  526.  
  527.         ensureSelectElementIsRenderedCorrectly: function(selectElement) {
  528.             // 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.
  529.             // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
  530.             // Also fixes IE7 and IE8 bug that causes selects to be zero width if enclosed by 'if' or 'with'. (See issue #839)
  531.             if (ieVersion) {
  532.                 var originalWidth = selectElement.style.width;
  533.                 selectElement.style.width = 0;
  534.                 selectElement.style.width = originalWidth;
  535.             }
  536.         },
  537.  
  538.         range: function (min, max) {
  539.             min = ko.utils.unwrapObservable(min);
  540.             max = ko.utils.unwrapObservable(max);
  541.             var result = [];
  542.             for (var i = min; i <= max; i++)
  543.                 result.push(i);
  544.             return result;
  545.         },
  546.  
  547.         makeArray: function(arrayLikeObject) {
  548.             var result = [];
  549.             for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
  550.                 result.push(arrayLikeObject[i]);
  551.             };
  552.             return result;
  553.         },
  554.  
  555.         createSymbolOrString: function(identifier) {
  556.             return canUseSymbols ? Symbol(identifier) : identifier;
  557.         },
  558.  
  559.         isIe6 : isIe6,
  560.         isIe7 : isIe7,
  561.         ieVersion : ieVersion,
  562.  
  563.         getFormFields: function(form, fieldName) {
  564.             var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
  565.             var isMatchingField = (typeof fieldName == 'string')
  566.                 ? function(field) { return field.name === fieldName }
  567.                 : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
  568.             var matches = [];
  569.             for (var i = fields.length - 1; i >= 0; i--) {
  570.                 if (isMatchingField(fields[i]))
  571.                     matches.push(fields[i]);
  572.             };
  573.             return matches;
  574.         },
  575.  
  576.         parseJson: function (jsonString) {
  577.             if (typeof jsonString == "string") {
  578.                 jsonString = ko.utils.stringTrim(jsonString);
  579.                 if (jsonString) {
  580.                     if (JSON && JSON.parse) // Use native parsing where available
  581.                         return JSON.parse(jsonString);
  582.                     return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
  583.                 }
  584.             }
  585.             return null;
  586.         },
  587.  
  588.         stringifyJson: function (data, replacer, space) {   // replacer and space are optional
  589.             if (!JSON || !JSON.stringify)
  590.                 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");
  591.             return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
  592.         },
  593.  
  594.         postJson: function (urlOrForm, data, options) {
  595.             options = options || {};
  596.             var params = options['params'] || {};
  597.             var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
  598.             var url = urlOrForm;
  599.  
  600.             // If we were given a form, use its 'action' URL and pick out any requested field values
  601.             if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
  602.                 var originalForm = urlOrForm;
  603.                 url = originalForm.action;
  604.                 for (var i = includeFields.length - 1; i >= 0; i--) {
  605.                     var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
  606.                     for (var j = fields.length - 1; j >= 0; j--)
  607.                         params[fields[j].name] = fields[j].value;
  608.                 }
  609.             }
  610.  
  611.             data = ko.utils.unwrapObservable(data);
  612.             var form = document.createElement("form");
  613.             form.style.display = "none";
  614.             form.action = url;
  615.             form.method = "post";
  616.             for (var key in data) {
  617.                 // Since 'data' this is a model object, we include all properties including those inherited from its prototype
  618.                 var input = document.createElement("input");
  619.                 input.type = "hidden";
  620.                 input.name = key;
  621.                 input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
  622.                 form.appendChild(input);
  623.             }
  624.             objectForEach(params, function(key, value) {
  625.                 var input = document.createElement("input");
  626.                 input.type = "hidden";
  627.                 input.name = key;
  628.                 input.value = value;
  629.                 form.appendChild(input);
  630.             });
  631.             document.body.appendChild(form);
  632.             options['submitter'] ? options['submitter'](form) : form.submit();
  633.             setTimeout(function () { form.parentNode.removeChild(form); }, 0);
  634.         }
  635.     }
  636. }());
  637.  
  638. ko.exportSymbol('utils', ko.utils);
  639. ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
  640. ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
  641. ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
  642. ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
  643. ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
  644. ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
  645. ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
  646. ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
  647. ko.exportSymbol('utils.extend', ko.utils.extend);
  648. ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
  649. ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
  650. ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
  651. ko.exportSymbol('utils.postJson', ko.utils.postJson);
  652. ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
  653. ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
  654. ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
  655. ko.exportSymbol('utils.range', ko.utils.range);
  656. ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
  657. ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
  658. ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
  659. ko.exportSymbol('utils.objectForEach', ko.utils.objectForEach);
  660. ko.exportSymbol('utils.addOrRemoveItem', ko.utils.addOrRemoveItem);
  661. ko.exportSymbol('utils.setTextContent', ko.utils.setTextContent);
  662. ko.exportSymbol('unwrap', ko.utils.unwrapObservable); // Convenient shorthand, because this is used so commonly
  663.  
  664. if (!Function.prototype['bind']) {
  665.     // 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)
  666.     // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
  667.     Function.prototype['bind'] = function (object) {
  668.         var originalFunction = this;
  669.         if (arguments.length === 1) {
  670.             return function () {
  671.                 return originalFunction.apply(object, arguments);
  672.             };
  673.         } else {
  674.             var partialArgs = Array.prototype.slice.call(arguments, 1);
  675.             return function () {
  676.                 var args = partialArgs.slice(0);
  677.                 args.push.apply(args, arguments);
  678.                 return originalFunction.apply(object, args);
  679.             };
  680.         }
  681.     };
  682. }
  683.  
  684. ko.utils.domData = new (function () {
  685.     var uniqueId = 0;
  686.     var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
  687.     var dataStore = {};
  688.  
  689.     function getAll(node, createIfNotFound) {
  690.         var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
  691.         var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
  692.         if (!hasExistingDataStore) {
  693.             if (!createIfNotFound)
  694.                 return undefined;
  695.             dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
  696.             dataStore[dataStoreKey] = {};
  697.         }
  698.         return dataStore[dataStoreKey];
  699.     }
  700.  
  701.     return {
  702.         get: function (node, key) {
  703.             var allDataForNode = getAll(node, false);
  704.             return allDataForNode === undefined ? undefined : allDataForNode[key];
  705.         },
  706.         set: function (node, key, value) {
  707.             if (value === undefined) {
  708.                 // Make sure we don't actually create a new domData key if we are actually deleting a value
  709.                 if (getAll(node, false) === undefined)
  710.                     return;
  711.             }
  712.             var allDataForNode = getAll(node, true);
  713.             allDataForNode[key] = value;
  714.         },
  715.         clear: function (node) {
  716.             var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
  717.             if (dataStoreKey) {
  718.                 delete dataStore[dataStoreKey];
  719.                 node[dataStoreKeyExpandoPropertyName] = null;
  720.                 return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
  721.             }
  722.             return false;
  723.         },
  724.  
  725.         nextKey: function () {
  726.             return (uniqueId++) + dataStoreKeyExpandoPropertyName;
  727.         }
  728.     };
  729. })();
  730.  
  731. ko.exportSymbol('utils.domData', ko.utils.domData);
  732. ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
  733.  
  734. ko.utils.domNodeDisposal = new (function () {
  735.     var domDataKey = ko.utils.domData.nextKey();
  736.     var cleanableNodeTypes = { 1: true, 8: true, 9: true };       // Element, Comment, Document
  737.     var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
  738.  
  739.     function getDisposeCallbacksCollection(node, createIfNotFound) {
  740.         var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
  741.         if ((allDisposeCallbacks === undefined) && createIfNotFound) {
  742.             allDisposeCallbacks = [];
  743.             ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
  744.         }
  745.         return allDisposeCallbacks;
  746.     }
  747.     function destroyCallbacksCollection(node) {
  748.         ko.utils.domData.set(node, domDataKey, undefined);
  749.     }
  750.  
  751.     function cleanSingleNode(node) {
  752.         // Run all the dispose callbacks
  753.         var callbacks = getDisposeCallbacksCollection(node, false);
  754.         if (callbacks) {
  755.             callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
  756.             for (var i = 0; i < callbacks.length; i++)
  757.                 callbacks[i](node);
  758.         }
  759.  
  760.         // Erase the DOM data
  761.         ko.utils.domData.clear(node);
  762.  
  763.         // Perform cleanup needed by external libraries (currently only jQuery, but can be extended)
  764.         ko.utils.domNodeDisposal["cleanExternalData"](node);
  765.  
  766.         // Clear any immediate-child comment nodes, as these wouldn't have been found by
  767.         // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
  768.         if (cleanableNodeTypesWithDescendants[node.nodeType])
  769.             cleanImmediateCommentTypeChildren(node);
  770.     }
  771.  
  772.     function cleanImmediateCommentTypeChildren(nodeWithChildren) {
  773.         var child, nextChild = nodeWithChildren.firstChild;
  774.         while (child = nextChild) {
  775.             nextChild = child.nextSibling;
  776.             if (child.nodeType === 8)
  777.                 cleanSingleNode(child);
  778.         }
  779.     }
  780.  
  781.     return {
  782.         addDisposeCallback : function(node, callback) {
  783.             if (typeof callback != "function")
  784.                 throw new Error("Callback must be a function");
  785.             getDisposeCallbacksCollection(node, true).push(callback);
  786.         },
  787.  
  788.         removeDisposeCallback : function(node, callback) {
  789.             var callbacksCollection = getDisposeCallbacksCollection(node, false);
  790.             if (callbacksCollection) {
  791.                 ko.utils.arrayRemoveItem(callbacksCollection, callback);
  792.                 if (callbacksCollection.length == 0)
  793.                     destroyCallbacksCollection(node);
  794.             }
  795.         },
  796.  
  797.         cleanNode : function(node) {
  798.             // First clean this node, where applicable
  799.             if (cleanableNodeTypes[node.nodeType]) {
  800.                 cleanSingleNode(node);
  801.  
  802.                 // ... then its descendants, where applicable
  803.                 if (cleanableNodeTypesWithDescendants[node.nodeType]) {
  804.                     // Clone the descendants list in case it changes during iteration
  805.                     var descendants = [];
  806.                     ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
  807.                     for (var i = 0, j = descendants.length; i < j; i++)
  808.                         cleanSingleNode(descendants[i]);
  809.                 }
  810.             }
  811.             return node;
  812.         },
  813.  
  814.         removeNode : function(node) {
  815.             ko.cleanNode(node);
  816.             if (node.parentNode)
  817.                 node.parentNode.removeChild(node);
  818.         },
  819.  
  820.         "cleanExternalData" : function (node) {
  821.             // Special support for jQuery here because it's so commonly used.
  822.             // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
  823.             // so notify it to tear down any resources associated with the node & descendants here.
  824.             if (jQueryInstance && (typeof jQueryInstance['cleanData'] == "function"))
  825.                 jQueryInstance['cleanData']([node]);
  826.         }
  827.     };
  828. })();
  829. ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
  830. ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
  831. ko.exportSymbol('cleanNode', ko.cleanNode);
  832. ko.exportSymbol('removeNode', ko.removeNode);
  833. ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
  834. ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
  835. ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
  836. (function () {
  837.     var none = [0, "", ""],
  838.         table = [1, "<table>", "</table>"],
  839.         tbody = [2, "<table><tbody>", "</tbody></table>"],
  840.         tr = [3, "<table><tbody><tr>", "</tr></tbody></table>"],
  841.         select = [1, "<select multiple='multiple'>", "</select>"],
  842.         lookup = {
  843.             'thead': table,
  844.             'tbody': table,
  845.             'tfoot': table,
  846.             'tr': tbody,
  847.             'td': tr,
  848.             'th': tr,
  849.             'option': select,
  850.             'optgroup': select
  851.         },
  852.  
  853.         // This is needed for old IE if you're *not* using either jQuery or innerShiv. Doesn't affect other cases.
  854.         mayRequireCreateElementHack = ko.utils.ieVersion <= 8;
  855.  
  856.     function getWrap(tags) {
  857.         var m = tags.match(/^<([a-z]+)[ >]/);
  858.         return (m && lookup[m[1]]) || none;
  859.     }
  860.  
  861.     function simpleHtmlParse(html, documentContext) {
  862.         documentContext || (documentContext = document);
  863.         var windowContext = documentContext['parentWindow'] || documentContext['defaultView'] || window;
  864.  
  865.         // Based on jQuery's "clean" function, but only accounting for table-related elements.
  866.         // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
  867.  
  868.         // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
  869.         // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
  870.         // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
  871.         // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
  872.  
  873.         // Trim whitespace, otherwise indexOf won't work as expected
  874.         var tags = ko.utils.stringTrim(html).toLowerCase(), div = documentContext.createElement("div"),
  875.             wrap = getWrap(tags),
  876.             depth = wrap[0];
  877.  
  878.         // Go to html and back, then peel off extra wrappers
  879.         // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
  880.         var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
  881.         if (typeof windowContext['innerShiv'] == "function") {
  882.             // Note that innerShiv is deprecated in favour of html5shiv. We should consider adding
  883.             // support for html5shiv (except if no explicit support is needed, e.g., if html5shiv
  884.             // somehow shims the native APIs so it just works anyway)
  885.             div.appendChild(windowContext['innerShiv'](markup));
  886.         } else {
  887.             if (mayRequireCreateElementHack) {
  888.                 // The document.createElement('my-element') trick to enable custom elements in IE6-8
  889.                 // only works if we assign innerHTML on an element associated with that document.
  890.                 documentContext.appendChild(div);
  891.             }
  892.  
  893.             div.innerHTML = markup;
  894.  
  895.             if (mayRequireCreateElementHack) {
  896.                 div.parentNode.removeChild(div);
  897.             }
  898.         }
  899.  
  900.         // Move to the right depth
  901.         while (depth--)
  902.             div = div.lastChild;
  903.  
  904.         return ko.utils.makeArray(div.lastChild.childNodes);
  905.     }
  906.  
  907.     function jQueryHtmlParse(html, documentContext) {
  908.         // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
  909.         if (jQueryInstance['parseHTML']) {
  910.             return jQueryInstance['parseHTML'](html, documentContext) || []; // Ensure we always return an array and never null
  911.         } else {
  912.             // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
  913.             var elems = jQueryInstance['clean']([html], documentContext);
  914.  
  915.             // 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.
  916.             // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
  917.             // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
  918.             if (elems && elems[0]) {
  919.                 // Find the top-most parent element that's a direct child of a document fragment
  920.                 var elem = elems[0];
  921.                 while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
  922.                     elem = elem.parentNode;
  923.                 // ... then detach it
  924.                 if (elem.parentNode)
  925.                     elem.parentNode.removeChild(elem);
  926.             }
  927.  
  928.             return elems;
  929.         }
  930.     }
  931.  
  932.     ko.utils.parseHtmlFragment = function(html, documentContext) {
  933.         return jQueryInstance ?
  934.             jQueryHtmlParse(html, documentContext) :   // As below, benefit from jQuery's optimisations where possible
  935.             simpleHtmlParse(html, documentContext);  // ... otherwise, this simple logic will do in most common cases.
  936.     };
  937.  
  938.     ko.utils.setHtml = function(node, html) {
  939.         ko.utils.emptyDomNode(node);
  940.  
  941.         // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
  942.         html = ko.utils.unwrapObservable(html);
  943.  
  944.         if ((html !== null) && (html !== undefined)) {
  945.             if (typeof html != 'string')
  946.                 html = html.toString();
  947.  
  948.             // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
  949.             // for example <tr> elements which are not normally allowed to exist on their own.
  950.             // If you've referenced jQuery we'll use that rather than duplicating its code.
  951.             if (jQueryInstance) {
  952.                 jQueryInstance(node)['html'](html);
  953.             } else {
  954.                 // ... otherwise, use KO's own parsing logic.
  955.                 var parsedNodes = ko.utils.parseHtmlFragment(html, node.ownerDocument);
  956.                 for (var i = 0; i < parsedNodes.length; i++)
  957.                     node.appendChild(parsedNodes[i]);
  958.             }
  959.         }
  960.     };
  961. })();
  962.  
  963. ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
  964. ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
  965.  
  966. ko.memoization = (function () {
  967.     var memos = {};
  968.  
  969.     function randomMax8HexChars() {
  970.         return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
  971.     }
  972.     function generateRandomId() {
  973.         return randomMax8HexChars() + randomMax8HexChars();
  974.     }
  975.     function findMemoNodes(rootNode, appendToArray) {
  976.         if (!rootNode)
  977.             return;
  978.         if (rootNode.nodeType == 8) {
  979.             var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
  980.             if (memoId != null)
  981.                 appendToArray.push({ domNode: rootNode, memoId: memoId });
  982.         } else if (rootNode.nodeType == 1) {
  983.             for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
  984.                 findMemoNodes(childNodes[i], appendToArray);
  985.         }
  986.     }
  987.  
  988.     return {
  989.         memoize: function (callback) {
  990.             if (typeof callback != "function")
  991.                 throw new Error("You can only pass a function to ko.memoization.memoize()");
  992.             var memoId = generateRandomId();
  993.             memos[memoId] = callback;
  994.             return "<!--[ko_memo:" + memoId + "]-->";
  995.         },
  996.  
  997.         unmemoize: function (memoId, callbackParams) {
  998.             var callback = memos[memoId];
  999.             if (callback === undefined)
  1000.                 throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
  1001.             try {
  1002.                 callback.apply(null, callbackParams || []);
  1003.                 return true;
  1004.             }
  1005.             finally { delete memos[memoId]; }
  1006.         },
  1007.  
  1008.         unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
  1009.             var memos = [];
  1010.             findMemoNodes(domNode, memos);
  1011.             for (var i = 0, j = memos.length; i < j; i++) {
  1012.                 var node = memos[i].domNode;
  1013.                 var combinedParams = [node];
  1014.                 if (extraCallbackParamsArray)
  1015.                     ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
  1016.                 ko.memoization.unmemoize(memos[i].memoId, combinedParams);
  1017.                 node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
  1018.                 if (node.parentNode)
  1019.                     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)
  1020.             }
  1021.         },
  1022.  
  1023.         parseMemoText: function (memoText) {
  1024.             var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
  1025.             return match ? match[1] : null;
  1026.         }
  1027.     };
  1028. })();
  1029.  
  1030. ko.exportSymbol('memoization', ko.memoization);
  1031. ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
  1032. ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
  1033. ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
  1034. ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
  1035. ko.tasks = (function () {
  1036.     var scheduler,
  1037.         taskQueue = [],
  1038.         taskQueueLength = 0,
  1039.         nextHandle = 1,
  1040.         nextIndexToProcess = 0;
  1041.  
  1042.     if (window['MutationObserver']) {
  1043.         // Chrome 27+, Firefox 14+, IE 11+, Opera 15+, Safari 6.1+
  1044.         // From https://github.com/petkaantonov/bluebird * Copyright (c) 2014 Petka Antonov * License: MIT
  1045.         scheduler = (function (callback) {
  1046.             var div = document.createElement("div");
  1047.             new MutationObserver(callback).observe(div, {attributes: true});
  1048.             return function () { div.classList.toggle("foo"); };
  1049.         })(scheduledProcess);
  1050.     } else if (document && "onreadystatechange" in document.createElement("script")) {
  1051.         // IE 6-10
  1052.         // From https://github.com/YuzuJS/setImmediate * Copyright (c) 2012 Barnesandnoble.com, llc, Donavon West, and Domenic Denicola * License: MIT
  1053.         scheduler = function (callback) {
  1054.             var script = document.createElement("script");
  1055.             script.onreadystatechange = function () {
  1056.                 script.onreadystatechange = null;
  1057.                 document.documentElement.removeChild(script);
  1058.                 script = null;
  1059.                 callback();
  1060.             };
  1061.             document.documentElement.appendChild(script);
  1062.         };
  1063.     } else {
  1064.         scheduler = function (callback) {
  1065.             setTimeout(callback, 0);
  1066.         };
  1067.     }
  1068.  
  1069.     function processTasks() {
  1070.         if (taskQueueLength) {
  1071.             // Each mark represents the end of a logical group of tasks and the number of these groups is
  1072.             // limited to prevent unchecked recursion.
  1073.             var mark = taskQueueLength, countMarks = 0;
  1074.  
  1075.             // nextIndexToProcess keeps track of where we are in the queue; processTasks can be called recursively without issue
  1076.             for (var task; nextIndexToProcess < taskQueueLength; ) {
  1077.                 if (task = taskQueue[nextIndexToProcess++]) {
  1078.                     if (nextIndexToProcess > mark) {
  1079.                         if (++countMarks >= 5000) {
  1080.                             nextIndexToProcess = taskQueueLength;   // skip all tasks remaining in the queue since any of them could be causing the recursion
  1081.                             ko.utils.deferError(Error("'Too much recursion' after processing " + countMarks + " task groups."));
  1082.                             break;
  1083.                         }
  1084.                         mark = taskQueueLength;
  1085.                     }
  1086.                     try {
  1087.                         task();
  1088.                     } catch (ex) {
  1089.                         ko.utils.deferError(ex);
  1090.                     }
  1091.                 }
  1092.             }
  1093.         }
  1094.     }
  1095.  
  1096.     function scheduledProcess() {
  1097.         processTasks();
  1098.  
  1099.         // Reset the queue
  1100.         nextIndexToProcess = taskQueueLength = taskQueue.length = 0;
  1101.     }
  1102.  
  1103.     function scheduleTaskProcessing() {
  1104.         ko.tasks['scheduler'](scheduledProcess);
  1105.     }
  1106.  
  1107.     var tasks = {
  1108.         'scheduler': scheduler,     // Allow overriding the scheduler
  1109.  
  1110.         schedule: function (func) {
  1111.             if (!taskQueueLength) {
  1112.                 scheduleTaskProcessing();
  1113.             }
  1114.  
  1115.             taskQueue[taskQueueLength++] = func;
  1116.             return nextHandle++;
  1117.         },
  1118.  
  1119.         cancel: function (handle) {
  1120.             var index = handle - (nextHandle - taskQueueLength);
  1121.             if (index >= nextIndexToProcess && index < taskQueueLength) {
  1122.                 taskQueue[index] = null;
  1123.             }
  1124.         },
  1125.  
  1126.         // For testing only: reset the queue and return the previous queue length
  1127.         'resetForTesting': function () {
  1128.             var length = taskQueueLength - nextIndexToProcess;
  1129.             nextIndexToProcess = taskQueueLength = taskQueue.length = 0;
  1130.             return length;
  1131.         },
  1132.  
  1133.         runEarly: processTasks
  1134.     };
  1135.  
  1136.     return tasks;
  1137. })();
  1138.  
  1139. ko.exportSymbol('tasks', ko.tasks);
  1140. ko.exportSymbol('tasks.schedule', ko.tasks.schedule);
  1141. //ko.exportSymbol('tasks.cancel', ko.tasks.cancel);  "cancel" isn't minified
  1142. ko.exportSymbol('tasks.runEarly', ko.tasks.runEarly);
  1143. ko.extenders = {
  1144.     'throttle': function(target, timeout) {
  1145.         // Throttling means two things:
  1146.  
  1147.         // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
  1148.         //     notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
  1149.         target['throttleEvaluation'] = timeout;
  1150.  
  1151.         // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
  1152.         //     so the target cannot change value synchronously or faster than a certain rate
  1153.         var writeTimeoutInstance = null;
  1154.         return ko.dependentObservable({
  1155.             'read': target,
  1156.             'write': function(value) {
  1157.                 clearTimeout(writeTimeoutInstance);
  1158.                 writeTimeoutInstance = ko.utils.setTimeout(function() {
  1159.                     target(value);
  1160.                 }, timeout);
  1161.             }
  1162.         });
  1163.     },
  1164.  
  1165.     'rateLimit': function(target, options) {
  1166.         var timeout, method, limitFunction;
  1167.  
  1168.         if (typeof options == 'number') {
  1169.             timeout = options;
  1170.         } else {
  1171.             timeout = options['timeout'];
  1172.             method = options['method'];
  1173.         }
  1174.  
  1175.         // rateLimit supersedes deferred updates
  1176.         target._deferUpdates = false;
  1177.  
  1178.         limitFunction = method == 'notifyWhenChangesStop' ?  debounce : throttle;
  1179.         target.limit(function(callback) {
  1180.             return limitFunction(callback, timeout);
  1181.         });
  1182.     },
  1183.  
  1184.     'deferred': function(target, options) {
  1185.         if (options !== true) {
  1186.             throw new Error('The \'deferred\' extender only accepts the value \'true\', because it is not supported to turn deferral off once enabled.')
  1187.         }
  1188.  
  1189.         if (!target._deferUpdates) {
  1190.             target._deferUpdates = true;
  1191.             target.limit(function (callback) {
  1192.                 var handle,
  1193.                     ignoreUpdates = false;
  1194.                 return function () {
  1195.                     if (!ignoreUpdates) {
  1196.                         ko.tasks.cancel(handle);
  1197.                         handle = ko.tasks.schedule(callback);
  1198.  
  1199.                         try {
  1200.                             ignoreUpdates = true;
  1201.                             target['notifySubscribers'](undefined, 'dirty');
  1202.                         } finally {
  1203.                             ignoreUpdates = false;
  1204.                         }
  1205.                     }
  1206.                 };
  1207.             });
  1208.         }
  1209.     },
  1210.  
  1211.     'notify': function(target, notifyWhen) {
  1212.         target["equalityComparer"] = notifyWhen == "always" ?
  1213.             null :  // null equalityComparer means to always notify
  1214.             valuesArePrimitiveAndEqual;
  1215.     }
  1216. };
  1217.  
  1218. var primitiveTypes = { 'undefined':1, 'boolean':1, 'number':1, 'string':1 };
  1219. function valuesArePrimitiveAndEqual(a, b) {
  1220.     var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
  1221.     return oldValueIsPrimitive ? (a === b) : false;
  1222. }
  1223.  
  1224. function throttle(callback, timeout) {
  1225.     var timeoutInstance;
  1226.     return function () {
  1227.         if (!timeoutInstance) {
  1228.             timeoutInstance = ko.utils.setTimeout(function () {
  1229.                 timeoutInstance = undefined;
  1230.                 callback();
  1231.             }, timeout);
  1232.         }
  1233.     };
  1234. }
  1235.  
  1236. function debounce(callback, timeout) {
  1237.     var timeoutInstance;
  1238.     return function () {
  1239.         clearTimeout(timeoutInstance);
  1240.         timeoutInstance = ko.utils.setTimeout(callback, timeout);
  1241.     };
  1242. }
  1243.  
  1244. function applyExtenders(requestedExtenders) {
  1245.     var target = this;
  1246.     if (requestedExtenders) {
  1247.         ko.utils.objectForEach(requestedExtenders, function(key, value) {
  1248.             var extenderHandler = ko.extenders[key];
  1249.             if (typeof extenderHandler == 'function') {
  1250.                 target = extenderHandler(target, value) || target;
  1251.             }
  1252.         });
  1253.     }
  1254.     return target;
  1255. }
  1256.  
  1257. ko.exportSymbol('extenders', ko.extenders);
  1258.  
  1259. ko.subscription = function (target, callback, disposeCallback) {
  1260.     this._target = target;
  1261.     this.callback = callback;
  1262.     this.disposeCallback = disposeCallback;
  1263.     this.isDisposed = false;
  1264.     ko.exportProperty(this, 'dispose', this.dispose);
  1265. };
  1266. ko.subscription.prototype.dispose = function () {
  1267.     this.isDisposed = true;
  1268.     this.disposeCallback();
  1269. };
  1270.  
  1271. ko.subscribable = function () {
  1272.     ko.utils.setPrototypeOfOrExtend(this, ko_subscribable_fn);
  1273.     ko_subscribable_fn.init(this);
  1274. }
  1275.  
  1276. var defaultEvent = "change";
  1277.  
  1278. // Moved out of "limit" to avoid the extra closure
  1279. function limitNotifySubscribers(value, event) {
  1280.     if (!event || event === defaultEvent) {
  1281.         this._limitChange(value);
  1282.     } else if (event === 'beforeChange') {
  1283.         this._limitBeforeChange(value);
  1284.     } else {
  1285.         this._origNotifySubscribers(value, event);
  1286.     }
  1287. }
  1288.  
  1289. var ko_subscribable_fn = {
  1290.     init: function(instance) {
  1291.         instance._subscriptions = { "change": [] };
  1292.         instance._versionNumber = 1;
  1293.     },
  1294.  
  1295.     subscribe: function (callback, callbackTarget, event) {
  1296.         var self = this;
  1297.  
  1298.         event = event || defaultEvent;
  1299.         var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
  1300.  
  1301.         var subscription = new ko.subscription(self, boundCallback, function () {
  1302.             ko.utils.arrayRemoveItem(self._subscriptions[event], subscription);
  1303.             if (self.afterSubscriptionRemove)
  1304.                 self.afterSubscriptionRemove(event);
  1305.         });
  1306.  
  1307.         if (self.beforeSubscriptionAdd)
  1308.             self.beforeSubscriptionAdd(event);
  1309.  
  1310.         if (!self._subscriptions[event])
  1311.             self._subscriptions[event] = [];
  1312.         self._subscriptions[event].push(subscription);
  1313.  
  1314.         return subscription;
  1315.     },
  1316.  
  1317.     "notifySubscribers": function (valueToNotify, event) {
  1318.         event = event || defaultEvent;
  1319.         if (event === defaultEvent) {
  1320.             this.updateVersion();
  1321.         }
  1322.         if (this.hasSubscriptionsForEvent(event)) {
  1323.             var subs = event === defaultEvent && this._changeSubscriptions || this._subscriptions[event].slice(0);
  1324.             try {
  1325.                 ko.dependencyDetection.begin(); // Begin suppressing dependency detection (by setting the top frame to undefined)
  1326.                 for (var i = 0, subscription; subscription = subs[i]; ++i) {
  1327.                     // In case a subscription was disposed during the arrayForEach cycle, check
  1328.                     // for isDisposed on each subscription before invoking its callback
  1329.                     if (!subscription.isDisposed)
  1330.                         subscription.callback(valueToNotify);
  1331.                 }
  1332.             } finally {
  1333.                 ko.dependencyDetection.end(); // End suppressing dependency detection
  1334.             }
  1335.         }
  1336.     },
  1337.  
  1338.     getVersion: function () {
  1339.         return this._versionNumber;
  1340.     },
  1341.  
  1342.     hasChanged: function (versionToCheck) {
  1343.         return this.getVersion() !== versionToCheck;
  1344.     },
  1345.  
  1346.     updateVersion: function () {
  1347.         ++this._versionNumber;
  1348.     },
  1349.  
  1350.     limit: function(limitFunction) {
  1351.         var self = this, selfIsObservable = ko.isObservable(self),
  1352.             ignoreBeforeChange, notifyNextChange, previousValue, pendingValue, beforeChange = 'beforeChange';
  1353.  
  1354.         if (!self._origNotifySubscribers) {
  1355.             self._origNotifySubscribers = self["notifySubscribers"];
  1356.             self["notifySubscribers"] = limitNotifySubscribers;
  1357.         }
  1358.  
  1359.         var finish = limitFunction(function() {
  1360.             self._notificationIsPending = false;
  1361.  
  1362.             // If an observable provided a reference to itself, access it to get the latest value.
  1363.             // This allows computed observables to delay calculating their value until needed.
  1364.             if (selfIsObservable && pendingValue === self) {
  1365.                 pendingValue = self._evalIfChanged ? self._evalIfChanged() : self();
  1366.             }
  1367.             var shouldNotify = notifyNextChange || self.isDifferent(previousValue, pendingValue);
  1368.  
  1369.             notifyNextChange = ignoreBeforeChange = false;
  1370.  
  1371.             if (shouldNotify) {
  1372.                 self._origNotifySubscribers(previousValue = pendingValue);
  1373.             }
  1374.         });
  1375.  
  1376.         self._limitChange = function(value) {
  1377.             self._changeSubscriptions = self._subscriptions[defaultEvent].slice(0);
  1378.             self._notificationIsPending = ignoreBeforeChange = true;
  1379.             pendingValue = value;
  1380.             finish();
  1381.         };
  1382.         self._limitBeforeChange = function(value) {
  1383.             if (!ignoreBeforeChange) {
  1384.                 previousValue = value;
  1385.                 self._origNotifySubscribers(value, beforeChange);
  1386.             }
  1387.         };
  1388.         self._notifyNextChangeIfValueIsDifferent = function() {
  1389.             if (self.isDifferent(previousValue, self.peek(true /*evaluate*/))) {
  1390.                 notifyNextChange = true;
  1391.             }
  1392.         };
  1393.     },
  1394.  
  1395.     hasSubscriptionsForEvent: function(event) {
  1396.         return this._subscriptions[event] && this._subscriptions[event].length;
  1397.     },
  1398.  
  1399.     getSubscriptionsCount: function (event) {
  1400.         if (event) {
  1401.             return this._subscriptions[event] && this._subscriptions[event].length || 0;
  1402.         } else {
  1403.             var total = 0;
  1404.             ko.utils.objectForEach(this._subscriptions, function(eventName, subscriptions) {
  1405.                 if (eventName !== 'dirty')
  1406.                     total += subscriptions.length;
  1407.             });
  1408.             return total;
  1409.         }
  1410.     },
  1411.  
  1412.     isDifferent: function(oldValue, newValue) {
  1413.         return !this['equalityComparer'] || !this['equalityComparer'](oldValue, newValue);
  1414.     },
  1415.  
  1416.     extend: applyExtenders
  1417. };
  1418.  
  1419. ko.exportProperty(ko_subscribable_fn, 'subscribe', ko_subscribable_fn.subscribe);
  1420. ko.exportProperty(ko_subscribable_fn, 'extend', ko_subscribable_fn.extend);
  1421. ko.exportProperty(ko_subscribable_fn, 'getSubscriptionsCount', ko_subscribable_fn.getSubscriptionsCount);
  1422.  
  1423. // For browsers that support proto assignment, we overwrite the prototype of each
  1424. // observable instance. Since observables are functions, we need Function.prototype
  1425. // to still be in the prototype chain.
  1426. if (ko.utils.canSetPrototype) {
  1427.     ko.utils.setPrototypeOf(ko_subscribable_fn, Function.prototype);
  1428. }
  1429.  
  1430. ko.subscribable['fn'] = ko_subscribable_fn;
  1431.  
  1432.  
  1433. ko.isSubscribable = function (instance) {
  1434.     return instance != null && typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
  1435. };
  1436.  
  1437. ko.exportSymbol('subscribable', ko.subscribable);
  1438. ko.exportSymbol('isSubscribable', ko.isSubscribable);
  1439.  
  1440. ko.computedContext = ko.dependencyDetection = (function () {
  1441.     var outerFrames = [],
  1442.         currentFrame,
  1443.         lastId = 0;
  1444.  
  1445.     // Return a unique ID that can be assigned to an observable for dependency tracking.
  1446.     // Theoretically, you could eventually overflow the number storage size, resulting
  1447.     // in duplicate IDs. But in JavaScript, the largest exact integral value is 2^53
  1448.     // or 9,007,199,254,740,992. If you created 1,000,000 IDs per second, it would
  1449.     // take over 285 years to reach that number.
  1450.     // Reference http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html
  1451.     function getId() {
  1452.         return ++lastId;
  1453.     }
  1454.  
  1455.     function begin(options) {
  1456.         outerFrames.push(currentFrame);
  1457.         currentFrame = options;
  1458.     }
  1459.  
  1460.     function end() {
  1461.         currentFrame = outerFrames.pop();
  1462.     }
  1463.  
  1464.     return {
  1465.         begin: begin,
  1466.  
  1467.         end: end,
  1468.  
  1469.         registerDependency: function (subscribable) {
  1470.             if (currentFrame) {
  1471.                 if (!ko.isSubscribable(subscribable))
  1472.                     throw new Error("Only subscribable things can act as dependencies");
  1473.                 currentFrame.callback.call(currentFrame.callbackTarget, subscribable, subscribable._id || (subscribable._id = getId()));
  1474.             }
  1475.         },
  1476.  
  1477.         ignore: function (callback, callbackTarget, callbackArgs) {
  1478.             try {
  1479.                 begin();
  1480.                 return callback.apply(callbackTarget, callbackArgs || []);
  1481.             } finally {
  1482.                 end();
  1483.             }
  1484.         },
  1485.  
  1486.         getDependenciesCount: function () {
  1487.             if (currentFrame)
  1488.                 return currentFrame.computed.getDependenciesCount();
  1489.         },
  1490.  
  1491.         isInitial: function() {
  1492.             if (currentFrame)
  1493.                 return currentFrame.isInitial;
  1494.         }
  1495.     };
  1496. })();
  1497.  
  1498. ko.exportSymbol('computedContext', ko.computedContext);
  1499. ko.exportSymbol('computedContext.getDependenciesCount', ko.computedContext.getDependenciesCount);
  1500. ko.exportSymbol('computedContext.isInitial', ko.computedContext.isInitial);
  1501.  
  1502. ko.exportSymbol('ignoreDependencies', ko.ignoreDependencies = ko.dependencyDetection.ignore);
  1503. var observableLatestValue = ko.utils.createSymbolOrString('_latestValue');
  1504.  
  1505. ko.observable = function (initialValue) {
  1506.     function observable() {
  1507.         if (arguments.length > 0) {
  1508.             // Write
  1509.  
  1510.             // Ignore writes if the value hasn't changed
  1511.             if (observable.isDifferent(observable[observableLatestValue], arguments[0])) {
  1512.                 observable.valueWillMutate();
  1513.                 observable[observableLatestValue] = arguments[0];
  1514.                 observable.valueHasMutated();
  1515.             }
  1516.             return this; // Permits chained assignments
  1517.         }
  1518.         else {
  1519.             // Read
  1520.             ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
  1521.             return observable[observableLatestValue];
  1522.         }
  1523.     }
  1524.  
  1525.     observable[observableLatestValue] = initialValue;
  1526.  
  1527.     // Inherit from 'subscribable'
  1528.     if (!ko.utils.canSetPrototype) {
  1529.         // 'subscribable' won't be on the prototype chain unless we put it there directly
  1530.         ko.utils.extend(observable, ko.subscribable['fn']);
  1531.     }
  1532.     ko.subscribable['fn'].init(observable);
  1533.  
  1534.     // Inherit from 'observable'
  1535.     ko.utils.setPrototypeOfOrExtend(observable, observableFn);
  1536.  
  1537.     if (ko.options['deferUpdates']) {
  1538.         ko.extenders['deferred'](observable, true);
  1539.     }
  1540.  
  1541.     return observable;
  1542. }
  1543.  
  1544. // Define prototype for observables
  1545. var observableFn = {
  1546.     'equalityComparer': valuesArePrimitiveAndEqual,
  1547.     peek: function() { return this[observableLatestValue]; },
  1548.     valueHasMutated: function () { this['notifySubscribers'](this[observableLatestValue]); },
  1549.     valueWillMutate: function () { this['notifySubscribers'](this[observableLatestValue], 'beforeChange'); }
  1550. };
  1551.  
  1552. // Note that for browsers that don't support proto assignment, the
  1553. // inheritance chain is created manually in the ko.observable constructor
  1554. if (ko.utils.canSetPrototype) {
  1555.     ko.utils.setPrototypeOf(observableFn, ko.subscribable['fn']);
  1556. }
  1557.  
  1558. var protoProperty = ko.observable.protoProperty = '__ko_proto__';
  1559. observableFn[protoProperty] = ko.observable;
  1560.  
  1561. ko.hasPrototype = function(instance, prototype) {
  1562.     if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
  1563.     if (instance[protoProperty] === prototype) return true;
  1564.     return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
  1565. };
  1566.  
  1567. ko.isObservable = function (instance) {
  1568.     return ko.hasPrototype(instance, ko.observable);
  1569. }
  1570. ko.isWriteableObservable = function (instance) {
  1571.     // Observable
  1572.     if ((typeof instance == 'function') && instance[protoProperty] === ko.observable)
  1573.         return true;
  1574.     // Writeable dependent observable
  1575.     if ((typeof instance == 'function') && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
  1576.         return true;
  1577.     // Anything else
  1578.     return false;
  1579. }
  1580.  
  1581. ko.exportSymbol('observable', ko.observable);
  1582. ko.exportSymbol('isObservable', ko.isObservable);
  1583. ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
  1584. ko.exportSymbol('isWritableObservable', ko.isWriteableObservable);
  1585. ko.exportSymbol('observable.fn', observableFn);
  1586. ko.exportProperty(observableFn, 'peek', observableFn.peek);
  1587. ko.exportProperty(observableFn, 'valueHasMutated', observableFn.valueHasMutated);
  1588. ko.exportProperty(observableFn, 'valueWillMutate', observableFn.valueWillMutate);
  1589. ko.observableArray = function (initialValues) {
  1590.     initialValues = initialValues || [];
  1591.  
  1592.     if (typeof initialValues != 'object' || !('length' in initialValues))
  1593.         throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
  1594.  
  1595.     var result = ko.observable(initialValues);
  1596.     ko.utils.setPrototypeOfOrExtend(result, ko.observableArray['fn']);
  1597.     return result.extend({'trackArrayChanges':true});
  1598. };
  1599.  
  1600. ko.observableArray['fn'] = {
  1601.     'remove': function (valueOrPredicate) {
  1602.         var underlyingArray = this.peek();
  1603.         var removedValues = [];
  1604.         var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
  1605.         for (var i = 0; i < underlyingArray.length; i++) {
  1606.             var value = underlyingArray[i];
  1607.             if (predicate(value)) {
  1608.                 if (removedValues.length === 0) {
  1609.                     this.valueWillMutate();
  1610.                 }
  1611.                 removedValues.push(value);
  1612.                 underlyingArray.splice(i, 1);
  1613.                 i--;
  1614.             }
  1615.         }
  1616.         if (removedValues.length) {
  1617.             this.valueHasMutated();
  1618.         }
  1619.         return removedValues;
  1620.     },
  1621.  
  1622.     'removeAll': function (arrayOfValues) {
  1623.         // If you passed zero args, we remove everything
  1624.         if (arrayOfValues === undefined) {
  1625.             var underlyingArray = this.peek();
  1626.             var allValues = underlyingArray.slice(0);
  1627.             this.valueWillMutate();
  1628.             underlyingArray.splice(0, underlyingArray.length);
  1629.             this.valueHasMutated();
  1630.             return allValues;
  1631.         }
  1632.         // If you passed an arg, we interpret it as an array of entries to remove
  1633.         if (!arrayOfValues)
  1634.             return [];
  1635.         return this['remove'](function (value) {
  1636.             return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
  1637.         });
  1638.     },
  1639.  
  1640.     'destroy': function (valueOrPredicate) {
  1641.         var underlyingArray = this.peek();
  1642.         var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
  1643.         this.valueWillMutate();
  1644.         for (var i = underlyingArray.length - 1; i >= 0; i--) {
  1645.             var value = underlyingArray[i];
  1646.             if (predicate(value))
  1647.                 underlyingArray[i]["_destroy"] = true;
  1648.         }
  1649.         this.valueHasMutated();
  1650.     },
  1651.  
  1652.     'destroyAll': function (arrayOfValues) {
  1653.         // If you passed zero args, we destroy everything
  1654.         if (arrayOfValues === undefined)
  1655.             return this['destroy'](function() { return true });
  1656.  
  1657.         // If you passed an arg, we interpret it as an array of entries to destroy
  1658.         if (!arrayOfValues)
  1659.             return [];
  1660.         return this['destroy'](function (value) {
  1661.             return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
  1662.         });
  1663.     },
  1664.  
  1665.     'indexOf': function (item) {
  1666.         var underlyingArray = this();
  1667.         return ko.utils.arrayIndexOf(underlyingArray, item);
  1668.     },
  1669.  
  1670.     'replace': function(oldItem, newItem) {
  1671.         var index = this['indexOf'](oldItem);
  1672.         if (index >= 0) {
  1673.             this.valueWillMutate();
  1674.             this.peek()[index] = newItem;
  1675.             this.valueHasMutated();
  1676.         }
  1677.     }
  1678. };
  1679.  
  1680. // Note that for browsers that don't support proto assignment, the
  1681. // inheritance chain is created manually in the ko.observableArray constructor
  1682. if (ko.utils.canSetPrototype) {
  1683.     ko.utils.setPrototypeOf(ko.observableArray['fn'], ko.observable['fn']);
  1684. }
  1685.  
  1686. // Populate ko.observableArray.fn with read/write functions from native arrays
  1687. // Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
  1688. // because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
  1689. ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
  1690.     ko.observableArray['fn'][methodName] = function () {
  1691.         // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
  1692.         // (for consistency with mutating regular observables)
  1693.         var underlyingArray = this.peek();
  1694.         this.valueWillMutate();
  1695.         this.cacheDiffForKnownOperation(underlyingArray, methodName, arguments);
  1696.         var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
  1697.         this.valueHasMutated();
  1698.         // The native sort and reverse methods return a reference to the array, but it makes more sense to return the observable array instead.
  1699.         return methodCallResult === underlyingArray ? this : methodCallResult;
  1700.     };
  1701. });
  1702.  
  1703. // Populate ko.observableArray.fn with read-only functions from native arrays
  1704. ko.utils.arrayForEach(["slice"], function (methodName) {
  1705.     ko.observableArray['fn'][methodName] = function () {
  1706.         var underlyingArray = this();
  1707.         return underlyingArray[methodName].apply(underlyingArray, arguments);
  1708.     };
  1709. });
  1710.  
  1711. ko.exportSymbol('observableArray', ko.observableArray);
  1712. var arrayChangeEventName = 'arrayChange';
  1713. ko.extenders['trackArrayChanges'] = function(target, options) {
  1714.     // Use the provided options--each call to trackArrayChanges overwrites the previously set options
  1715.     target.compareArrayOptions = {};
  1716.     if (options && typeof options == "object") {
  1717.         ko.utils.extend(target.compareArrayOptions, options);
  1718.     }
  1719.     target.compareArrayOptions['sparse'] = true;
  1720.  
  1721.     // Only modify the target observable once
  1722.     if (target.cacheDiffForKnownOperation) {
  1723.         return;
  1724.     }
  1725.     var trackingChanges = false,
  1726.         cachedDiff = null,
  1727.         arrayChangeSubscription,
  1728.         pendingNotifications = 0,
  1729.         underlyingNotifySubscribersFunction,
  1730.         underlyingBeforeSubscriptionAddFunction = target.beforeSubscriptionAdd,
  1731.         underlyingAfterSubscriptionRemoveFunction = target.afterSubscriptionRemove;
  1732.  
  1733.     // Watch "subscribe" calls, and for array change events, ensure change tracking is enabled
  1734.     target.beforeSubscriptionAdd = function (event) {
  1735.         if (underlyingBeforeSubscriptionAddFunction)
  1736.             underlyingBeforeSubscriptionAddFunction.call(target, event);
  1737.         if (event === arrayChangeEventName) {
  1738.             trackChanges();
  1739.         }
  1740.     };
  1741.     // Watch "dispose" calls, and for array change events, ensure change tracking is disabled when all are disposed
  1742.     target.afterSubscriptionRemove = function (event) {
  1743.         if (underlyingAfterSubscriptionRemoveFunction)
  1744.             underlyingAfterSubscriptionRemoveFunction.call(target, event);
  1745.         if (event === arrayChangeEventName && !target.hasSubscriptionsForEvent(arrayChangeEventName)) {
  1746.             if (underlyingNotifySubscribersFunction) {
  1747.                 target['notifySubscribers'] = underlyingNotifySubscribersFunction;
  1748.                 underlyingNotifySubscribersFunction = undefined;
  1749.             }
  1750.             arrayChangeSubscription.dispose();
  1751.             trackingChanges = false;
  1752.         }
  1753.     };
  1754.  
  1755.     function trackChanges() {
  1756.         // Calling 'trackChanges' multiple times is the same as calling it once
  1757.         if (trackingChanges) {
  1758.             return;
  1759.         }
  1760.  
  1761.         trackingChanges = true;
  1762.  
  1763.         // Intercept "notifySubscribers" to track how many times it was called.
  1764.         underlyingNotifySubscribersFunction = target['notifySubscribers'];
  1765.         target['notifySubscribers'] = function(valueToNotify, event) {
  1766.             if (!event || event === defaultEvent) {
  1767.                 ++pendingNotifications;
  1768.             }
  1769.             return underlyingNotifySubscribersFunction.apply(this, arguments);
  1770.         };
  1771.  
  1772.         // Each time the array changes value, capture a clone so that on the next
  1773.         // change it's possible to produce a diff
  1774.         var previousContents = [].concat(target.peek() || []);
  1775.         cachedDiff = null;
  1776.         arrayChangeSubscription = target.subscribe(function(currentContents) {
  1777.             // Make a copy of the current contents and ensure it's an array
  1778.             currentContents = [].concat(currentContents || []);
  1779.  
  1780.             // Compute the diff and issue notifications, but only if someone is listening
  1781.             if (target.hasSubscriptionsForEvent(arrayChangeEventName)) {
  1782.                 var changes = getChanges(previousContents, currentContents);
  1783.             }
  1784.  
  1785.             // Eliminate references to the old, removed items, so they can be GCed
  1786.             previousContents = currentContents;
  1787.             cachedDiff = null;
  1788.             pendingNotifications = 0;
  1789.  
  1790.             if (changes && changes.length) {
  1791.                 target['notifySubscribers'](changes, arrayChangeEventName);
  1792.             }
  1793.         });
  1794.     }
  1795.  
  1796.     function getChanges(previousContents, currentContents) {
  1797.         // We try to re-use cached diffs.
  1798.         // The scenarios where pendingNotifications > 1 are when using rate-limiting or the Deferred Updates
  1799.         // plugin, which without this check would not be compatible with arrayChange notifications. Normally,
  1800.         // notifications are issued immediately so we wouldn't be queueing up more than one.
  1801.         if (!cachedDiff || pendingNotifications > 1) {
  1802.             cachedDiff = ko.utils.compareArrays(previousContents, currentContents, target.compareArrayOptions);
  1803.         }
  1804.  
  1805.         return cachedDiff;
  1806.     }
  1807.  
  1808.     target.cacheDiffForKnownOperation = function(rawArray, operationName, args) {
  1809.         // Only run if we're currently tracking changes for this observable array
  1810.         // and there aren't any pending deferred notifications.
  1811.         if (!trackingChanges || pendingNotifications) {
  1812.             return;
  1813.         }
  1814.         var diff = [],
  1815.             arrayLength = rawArray.length,
  1816.             argsLength = args.length,
  1817.             offset = 0;
  1818.  
  1819.         function pushDiff(status, value, index) {
  1820.             return diff[diff.length] = { 'status': status, 'value': value, 'index': index };
  1821.         }
  1822.         switch (operationName) {
  1823.             case 'push':
  1824.                 offset = arrayLength;
  1825.             case 'unshift':
  1826.                 for (var index = 0; index < argsLength; index++) {
  1827.                     pushDiff('added', args[index], offset + index);
  1828.                 }
  1829.                 break;
  1830.  
  1831.             case 'pop':
  1832.                 offset = arrayLength - 1;
  1833.             case 'shift':
  1834.                 if (arrayLength) {
  1835.                     pushDiff('deleted', rawArray[offset], offset);
  1836.                 }
  1837.                 break;
  1838.  
  1839.             case 'splice':
  1840.                 // Negative start index means 'from end of array'. After that we clamp to [0...arrayLength].
  1841.                 // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
  1842.                 var startIndex = Math.min(Math.max(0, args[0] < 0 ? arrayLength + args[0] : args[0]), arrayLength),
  1843.                     endDeleteIndex = argsLength === 1 ? arrayLength : Math.min(startIndex + (args[1] || 0), arrayLength),
  1844.                     endAddIndex = startIndex + argsLength - 2,
  1845.                     endIndex = Math.max(endDeleteIndex, endAddIndex),
  1846.                     additions = [], deletions = [];
  1847.                 for (var index = startIndex, argsIndex = 2; index < endIndex; ++index, ++argsIndex) {
  1848.                     if (index < endDeleteIndex)
  1849.                         deletions.push(pushDiff('deleted', rawArray[index], index));
  1850.                     if (index < endAddIndex)
  1851.                         additions.push(pushDiff('added', args[argsIndex], index));
  1852.                 }
  1853.                 ko.utils.findMovesInArrayComparison(deletions, additions);
  1854.                 break;
  1855.  
  1856.             default:
  1857.                 return;
  1858.         }
  1859.         cachedDiff = diff;
  1860.     };
  1861. };
  1862. var computedState = ko.utils.createSymbolOrString('_state');
  1863.  
  1864. ko.computed = ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
  1865.     if (typeof evaluatorFunctionOrOptions === "object") {
  1866.         // Single-parameter syntax - everything is on this "options" param
  1867.         options = evaluatorFunctionOrOptions;
  1868.     } else {
  1869.         // Multi-parameter syntax - construct the options according to the params passed
  1870.         options = options || {};
  1871.         if (evaluatorFunctionOrOptions) {
  1872.             options["read"] = evaluatorFunctionOrOptions;
  1873.         }
  1874.     }
  1875.     if (typeof options["read"] != "function")
  1876.         throw Error("Pass a function that returns the value of the ko.computed");
  1877.  
  1878.     var writeFunction = options["write"];
  1879.     var state = {
  1880.         latestValue: undefined,
  1881.         isStale: true,
  1882.         isDirty: true,
  1883.         isBeingEvaluated: false,
  1884.         suppressDisposalUntilDisposeWhenReturnsFalse: false,
  1885.         isDisposed: false,
  1886.         pure: false,
  1887.         isSleeping: false,
  1888.         readFunction: options["read"],
  1889.         evaluatorFunctionTarget: evaluatorFunctionTarget || options["owner"],
  1890.         disposeWhenNodeIsRemoved: options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
  1891.         disposeWhen: options["disposeWhen"] || options.disposeWhen,
  1892.         domNodeDisposalCallback: null,
  1893.         dependencyTracking: {},
  1894.         dependenciesCount: 0,
  1895.         evaluationTimeoutInstance: null
  1896.     };
  1897.  
  1898.     function computedObservable() {
  1899.         if (arguments.length > 0) {
  1900.             if (typeof writeFunction === "function") {
  1901.                 // Writing a value
  1902.                 writeFunction.apply(state.evaluatorFunctionTarget, arguments);
  1903.             } else {
  1904.                 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.");
  1905.             }
  1906.             return this; // Permits chained assignments
  1907.         } else {
  1908.             // Reading the value
  1909.             ko.dependencyDetection.registerDependency(computedObservable);
  1910.             if (state.isDirty || (state.isSleeping && computedObservable.haveDependenciesChanged())) {
  1911.                 computedObservable.evaluateImmediate();
  1912.             }
  1913.             return state.latestValue;
  1914.         }
  1915.     }
  1916.  
  1917.     computedObservable[computedState] = state;
  1918.     computedObservable.hasWriteFunction = typeof writeFunction === "function";
  1919.  
  1920.     // Inherit from 'subscribable'
  1921.     if (!ko.utils.canSetPrototype) {
  1922.         // 'subscribable' won't be on the prototype chain unless we put it there directly
  1923.         ko.utils.extend(computedObservable, ko.subscribable['fn']);
  1924.     }
  1925.     ko.subscribable['fn'].init(computedObservable);
  1926.  
  1927.     // Inherit from 'computed'
  1928.     ko.utils.setPrototypeOfOrExtend(computedObservable, computedFn);
  1929.  
  1930.     if (options['pure']) {
  1931.         state.pure = true;
  1932.         state.isSleeping = true;     // Starts off sleeping; will awake on the first subscription
  1933.         ko.utils.extend(computedObservable, pureComputedOverrides);
  1934.     } else if (options['deferEvaluation']) {
  1935.         ko.utils.extend(computedObservable, deferEvaluationOverrides);
  1936.     }
  1937.  
  1938.     if (ko.options['deferUpdates']) {
  1939.         ko.extenders['deferred'](computedObservable, true);
  1940.     }
  1941.  
  1942.     if (DEBUG) {
  1943.         // #1731 - Aid debugging by exposing the computed's options
  1944.         computedObservable["_options"] = options;
  1945.     }
  1946.  
  1947.     if (state.disposeWhenNodeIsRemoved) {
  1948.         // Since this computed is associated with a DOM node, and we don't want to dispose the computed
  1949.         // until the DOM node is *removed* from the document (as opposed to never having been in the document),
  1950.         // we'll prevent disposal until "disposeWhen" first returns false.
  1951.         state.suppressDisposalUntilDisposeWhenReturnsFalse = true;
  1952.  
  1953.         // disposeWhenNodeIsRemoved: true can be used to opt into the "only dispose after first false result"
  1954.         // behaviour even if there's no specific node to watch. In that case, clear the option so we don't try
  1955.         // to watch for a non-node's disposal. This technique is intended for KO's internal use only and shouldn't
  1956.         // be documented or used by application code, as it's likely to change in a future version of KO.
  1957.         if (!state.disposeWhenNodeIsRemoved.nodeType) {
  1958.             state.disposeWhenNodeIsRemoved = null;
  1959.         }
  1960.     }
  1961.  
  1962.     // Evaluate, unless sleeping or deferEvaluation is true
  1963.     if (!state.isSleeping && !options['deferEvaluation']) {
  1964.         computedObservable.evaluateImmediate();
  1965.     }
  1966.  
  1967.     // Attach a DOM node disposal callback so that the computed will be proactively disposed as soon as the node is
  1968.     // removed using ko.removeNode. But skip if isActive is false (there will never be any dependencies to dispose).
  1969.     if (state.disposeWhenNodeIsRemoved && computedObservable.isActive()) {
  1970.         ko.utils.domNodeDisposal.addDisposeCallback(state.disposeWhenNodeIsRemoved, state.domNodeDisposalCallback = function () {
  1971.             computedObservable.dispose();
  1972.         });
  1973.     }
  1974.  
  1975.     return computedObservable;
  1976. };
  1977.  
  1978. // Utility function that disposes a given dependencyTracking entry
  1979. function computedDisposeDependencyCallback(id, entryToDispose) {
  1980.     if (entryToDispose !== null && entryToDispose.dispose) {
  1981.         entryToDispose.dispose();
  1982.     }
  1983. }
  1984.  
  1985. // This function gets called each time a dependency is detected while evaluating a computed.
  1986. // It's factored out as a shared function to avoid creating unnecessary function instances during evaluation.
  1987. function computedBeginDependencyDetectionCallback(subscribable, id) {
  1988.     var computedObservable = this.computedObservable,
  1989.         state = computedObservable[computedState];
  1990.     if (!state.isDisposed) {
  1991.         if (this.disposalCount && this.disposalCandidates[id]) {
  1992.             // Don't want to dispose this subscription, as it's still being used
  1993.             computedObservable.addDependencyTracking(id, subscribable, this.disposalCandidates[id]);
  1994.             this.disposalCandidates[id] = null; // No need to actually delete the property - disposalCandidates is a transient object anyway
  1995.             --this.disposalCount;
  1996.         } else if (!state.dependencyTracking[id]) {
  1997.             // Brand new subscription - add it
  1998.             computedObservable.addDependencyTracking(id, subscribable, state.isSleeping ? { _target: subscribable } : computedObservable.subscribeToDependency(subscribable));
  1999.         }
  2000.         // If the observable we've accessed has a pending notification, ensure we get notified of the actual final value (bypass equality checks)
  2001.         if (subscribable._notificationIsPending) {
  2002.             subscribable._notifyNextChangeIfValueIsDifferent();
  2003.         }
  2004.     }
  2005. }
  2006.  
  2007. var computedFn = {
  2008.     "equalityComparer": valuesArePrimitiveAndEqual,
  2009.     getDependenciesCount: function () {
  2010.         return this[computedState].dependenciesCount;
  2011.     },
  2012.     addDependencyTracking: function (id, target, trackingObj) {
  2013.         if (this[computedState].pure && target === this) {
  2014.             throw Error("A 'pure' computed must not be called recursively");
  2015.         }
  2016.  
  2017.         this[computedState].dependencyTracking[id] = trackingObj;
  2018.         trackingObj._order = this[computedState].dependenciesCount++;
  2019.         trackingObj._version = target.getVersion();
  2020.     },
  2021.     haveDependenciesChanged: function () {
  2022.         var id, dependency, dependencyTracking = this[computedState].dependencyTracking;
  2023.         for (id in dependencyTracking) {
  2024.             if (dependencyTracking.hasOwnProperty(id)) {
  2025.                 dependency = dependencyTracking[id];
  2026.                 if ((this._evalDelayed && dependency._target._notificationIsPending) || dependency._target.hasChanged(dependency._version)) {
  2027.                     return true;
  2028.                 }
  2029.             }
  2030.         }
  2031.     },
  2032.     markDirty: function () {
  2033.         // Process "dirty" events if we can handle delayed notifications
  2034.         if (this._evalDelayed && !this[computedState].isBeingEvaluated) {
  2035.             this._evalDelayed(false /*isChange*/);
  2036.         }
  2037.     },
  2038.     isActive: function () {
  2039.         var state = this[computedState];
  2040.         return state.isDirty || state.dependenciesCount > 0;
  2041.     },
  2042.     respondToChange: function () {
  2043.         // Ignore "change" events if we've already scheduled a delayed notification
  2044.         if (!this._notificationIsPending) {
  2045.             this.evaluatePossiblyAsync();
  2046.         } else if (this[computedState].isDirty) {
  2047.             this[computedState].isStale = true;
  2048.         }
  2049.     },
  2050.     subscribeToDependency: function (target) {
  2051.         if (target._deferUpdates && !this[computedState].disposeWhenNodeIsRemoved) {
  2052.             var dirtySub = target.subscribe(this.markDirty, this, 'dirty'),
  2053.                 changeSub = target.subscribe(this.respondToChange, this);
  2054.             return {
  2055.                 _target: target,
  2056.                 dispose: function () {
  2057.                     dirtySub.dispose();
  2058.                     changeSub.dispose();
  2059.                 }
  2060.             };
  2061.         } else {
  2062.             return target.subscribe(this.evaluatePossiblyAsync, this);
  2063.         }
  2064.     },
  2065.     evaluatePossiblyAsync: function () {
  2066.         var computedObservable = this,
  2067.             throttleEvaluationTimeout = computedObservable['throttleEvaluation'];
  2068.         if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
  2069.             clearTimeout(this[computedState].evaluationTimeoutInstance);
  2070.             this[computedState].evaluationTimeoutInstance = ko.utils.setTimeout(function () {
  2071.                 computedObservable.evaluateImmediate(true /*notifyChange*/);
  2072.             }, throttleEvaluationTimeout);
  2073.         } else if (computedObservable._evalDelayed) {
  2074.             computedObservable._evalDelayed(true /*isChange*/);
  2075.         } else {
  2076.             computedObservable.evaluateImmediate(true /*notifyChange*/);
  2077.         }
  2078.     },
  2079.     evaluateImmediate: function (notifyChange) {
  2080.         var computedObservable = this,
  2081.             state = computedObservable[computedState],
  2082.             disposeWhen = state.disposeWhen,
  2083.             changed = false;
  2084.  
  2085.         if (state.isBeingEvaluated) {
  2086.             // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
  2087.             // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
  2088.             // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
  2089.             // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
  2090.             return;
  2091.         }
  2092.  
  2093.         // Do not evaluate (and possibly capture new dependencies) if disposed
  2094.         if (state.isDisposed) {
  2095.             return;
  2096.         }
  2097.  
  2098.         if (state.disposeWhenNodeIsRemoved && !ko.utils.domNodeIsAttachedToDocument(state.disposeWhenNodeIsRemoved) || disposeWhen && disposeWhen()) {
  2099.             // See comment above about suppressDisposalUntilDisposeWhenReturnsFalse
  2100.             if (!state.suppressDisposalUntilDisposeWhenReturnsFalse) {
  2101.                 computedObservable.dispose();
  2102.                 return;
  2103.             }
  2104.         } else {
  2105.             // It just did return false, so we can stop suppressing now
  2106.             state.suppressDisposalUntilDisposeWhenReturnsFalse = false;
  2107.         }
  2108.  
  2109.         state.isBeingEvaluated = true;
  2110.         try {
  2111.             changed = this.evaluateImmediate_CallReadWithDependencyDetection(notifyChange);
  2112.         } finally {
  2113.             state.isBeingEvaluated = false;
  2114.         }
  2115.  
  2116.         if (!state.dependenciesCount) {
  2117.             computedObservable.dispose();
  2118.         }
  2119.  
  2120.         return changed;
  2121.     },
  2122.     evaluateImmediate_CallReadWithDependencyDetection: function (notifyChange) {
  2123.         // This function is really just part of the evaluateImmediate logic. You would never call it from anywhere else.
  2124.         // Factoring it out into a separate function means it can be independent of the try/catch block in evaluateImmediate,
  2125.         // which contributes to saving about 40% off the CPU overhead of computed evaluation (on V8 at least).
  2126.  
  2127.         var computedObservable = this,
  2128.             state = computedObservable[computedState],
  2129.             changed = false;
  2130.  
  2131.         // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
  2132.         // Then, during evaluation, we cross off any that are in fact still being used.
  2133.         var isInitial = state.pure ? undefined : !state.dependenciesCount,   // If we're evaluating when there are no previous dependencies, it must be the first time
  2134.             dependencyDetectionContext = {
  2135.                 computedObservable: computedObservable,
  2136.                 disposalCandidates: state.dependencyTracking,
  2137.                 disposalCount: state.dependenciesCount
  2138.             };
  2139.  
  2140.         ko.dependencyDetection.begin({
  2141.             callbackTarget: dependencyDetectionContext,
  2142.             callback: computedBeginDependencyDetectionCallback,
  2143.             computed: computedObservable,
  2144.             isInitial: isInitial
  2145.         });
  2146.  
  2147.         state.dependencyTracking = {};
  2148.         state.dependenciesCount = 0;
  2149.  
  2150.         var newValue = this.evaluateImmediate_CallReadThenEndDependencyDetection(state, dependencyDetectionContext);
  2151.  
  2152.         if (computedObservable.isDifferent(state.latestValue, newValue)) {
  2153.             if (!state.isSleeping) {
  2154.                 computedObservable["notifySubscribers"](state.latestValue, "beforeChange");
  2155.             }
  2156.  
  2157.             state.latestValue = newValue;
  2158.             if (DEBUG) computedObservable._latestValue = newValue;
  2159.  
  2160.             if (state.isSleeping) {
  2161.                 computedObservable.updateVersion();
  2162.             } else if (notifyChange) {
  2163.                 computedObservable["notifySubscribers"](state.latestValue);
  2164.             }
  2165.  
  2166.             changed = true;
  2167.         }
  2168.  
  2169.         if (isInitial) {
  2170.             computedObservable["notifySubscribers"](state.latestValue, "awake");
  2171.         }
  2172.  
  2173.         return changed;
  2174.     },
  2175.     evaluateImmediate_CallReadThenEndDependencyDetection: function (state, dependencyDetectionContext) {
  2176.         // This function is really part of the evaluateImmediate_CallReadWithDependencyDetection logic.
  2177.         // You'd never call it from anywhere else. Factoring it out means that evaluateImmediate_CallReadWithDependencyDetection
  2178.         // can be independent of try/finally blocks, which contributes to saving about 40% off the CPU
  2179.         // overhead of computed evaluation (on V8 at least).
  2180.  
  2181.         try {
  2182.             var readFunction = state.readFunction;
  2183.             return state.evaluatorFunctionTarget ? readFunction.call(state.evaluatorFunctionTarget) : readFunction();
  2184.         } finally {
  2185.             ko.dependencyDetection.end();
  2186.  
  2187.             // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
  2188.             if (dependencyDetectionContext.disposalCount && !state.isSleeping) {
  2189.                 ko.utils.objectForEach(dependencyDetectionContext.disposalCandidates, computedDisposeDependencyCallback);
  2190.             }
  2191.  
  2192.             state.isStale = state.isDirty = false;
  2193.         }
  2194.     },
  2195.     peek: function (evaluate) {
  2196.         // By default, peek won't re-evaluate, except while the computed is sleeping or to get the initial value when "deferEvaluation" is set.
  2197.         // Pass in true to evaluate if needed.
  2198.         var state = this[computedState];
  2199.         if ((state.isDirty && (evaluate || !state.dependenciesCount)) || (state.isSleeping && this.haveDependenciesChanged())) {
  2200.             this.evaluateImmediate();
  2201.         }
  2202.         return state.latestValue;
  2203.     },
  2204.     limit: function (limitFunction) {
  2205.         // Override the limit function with one that delays evaluation as well
  2206.         ko.subscribable['fn'].limit.call(this, limitFunction);
  2207.         this._evalIfChanged = function () {
  2208.             if (this[computedState].isStale) {
  2209.                 this.evaluateImmediate();
  2210.             } else {
  2211.                 this[computedState].isDirty = false;
  2212.             }
  2213.             return this[computedState].latestValue;
  2214.         };
  2215.         this._evalDelayed = function (isChange) {
  2216.             this._limitBeforeChange(this[computedState].latestValue);
  2217.  
  2218.             // Mark as dirty
  2219.             this[computedState].isDirty = true;
  2220.             if (isChange) {
  2221.                 this[computedState].isStale = true;
  2222.             }
  2223.  
  2224.             // Pass the observable to the "limit" code, which will evaluate it when
  2225.             // it's time to do the notification.
  2226.             this._limitChange(this);
  2227.         };
  2228.     },
  2229.     dispose: function () {
  2230.         var state = this[computedState];
  2231.         if (!state.isSleeping && state.dependencyTracking) {
  2232.             ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) {
  2233.                 if (dependency.dispose)
  2234.                     dependency.dispose();
  2235.             });
  2236.         }
  2237.         if (state.disposeWhenNodeIsRemoved && state.domNodeDisposalCallback) {
  2238.             ko.utils.domNodeDisposal.removeDisposeCallback(state.disposeWhenNodeIsRemoved, state.domNodeDisposalCallback);
  2239.         }
  2240.         state.dependencyTracking = null;
  2241.         state.dependenciesCount = 0;
  2242.         state.isDisposed = true;
  2243.         state.isStale = false;
  2244.         state.isDirty = false;
  2245.         state.isSleeping = false;
  2246.         state.disposeWhenNodeIsRemoved = null;
  2247.     }
  2248. };
  2249.  
  2250. var pureComputedOverrides = {
  2251.     beforeSubscriptionAdd: function (event) {
  2252.         // If asleep, wake up the computed by subscribing to any dependencies.
  2253.         var computedObservable = this,
  2254.             state = computedObservable[computedState];
  2255.         if (!state.isDisposed && state.isSleeping && event == 'change') {
  2256.             state.isSleeping = false;
  2257.             if (state.isStale || computedObservable.haveDependenciesChanged()) {
  2258.                 state.dependencyTracking = null;
  2259.                 state.dependenciesCount = 0;
  2260.                 if (computedObservable.evaluateImmediate()) {
  2261.                     computedObservable.updateVersion();
  2262.                 }
  2263.             } else {
  2264.                 // First put the dependencies in order
  2265.                 var dependeciesOrder = [];
  2266.                 ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) {
  2267.                     dependeciesOrder[dependency._order] = id;
  2268.                 });
  2269.                 // Next, subscribe to each one
  2270.                 ko.utils.arrayForEach(dependeciesOrder, function (id, order) {
  2271.                     var dependency = state.dependencyTracking[id],
  2272.                         subscription = computedObservable.subscribeToDependency(dependency._target);
  2273.                     subscription._order = order;
  2274.                     subscription._version = dependency._version;
  2275.                     state.dependencyTracking[id] = subscription;
  2276.                 });
  2277.             }
  2278.             if (!state.isDisposed) {     // test since evaluating could trigger disposal
  2279.                 computedObservable["notifySubscribers"](state.latestValue, "awake");
  2280.             }
  2281.         }
  2282.     },
  2283.     afterSubscriptionRemove: function (event) {
  2284.         var state = this[computedState];
  2285.         if (!state.isDisposed && event == 'change' && !this.hasSubscriptionsForEvent('change')) {
  2286.             ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) {
  2287.                 if (dependency.dispose) {
  2288.                     state.dependencyTracking[id] = {
  2289.                         _target: dependency._target,
  2290.                         _order: dependency._order,
  2291.                         _version: dependency._version
  2292.                     };
  2293.                     dependency.dispose();
  2294.                 }
  2295.             });
  2296.             state.isSleeping = true;
  2297.             this["notifySubscribers"](undefined, "asleep");
  2298.         }
  2299.     },
  2300.     getVersion: function () {
  2301.         // Because a pure computed is not automatically updated while it is sleeping, we can't
  2302.         // simply return the version number. Instead, we check if any of the dependencies have
  2303.         // changed and conditionally re-evaluate the computed observable.
  2304.         var state = this[computedState];
  2305.         if (state.isSleeping && (state.isStale || this.haveDependenciesChanged())) {
  2306.             this.evaluateImmediate();
  2307.         }
  2308.         return ko.subscribable['fn'].getVersion.call(this);
  2309.     }
  2310. };
  2311.  
  2312. var deferEvaluationOverrides = {
  2313.     beforeSubscriptionAdd: function (event) {
  2314.         // This will force a computed with deferEvaluation to evaluate when the first subscription is registered.
  2315.         if (event == 'change' || event == 'beforeChange') {
  2316.             this.peek();
  2317.         }
  2318.     }
  2319. };
  2320.  
  2321. // Note that for browsers that don't support proto assignment, the
  2322. // inheritance chain is created manually in the ko.computed constructor
  2323. if (ko.utils.canSetPrototype) {
  2324.     ko.utils.setPrototypeOf(computedFn, ko.subscribable['fn']);
  2325. }
  2326.  
  2327. // Set the proto chain values for ko.hasPrototype
  2328. var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
  2329. ko.computed[protoProp] = ko.observable;
  2330. computedFn[protoProp] = ko.computed;
  2331.  
  2332. ko.isComputed = function (instance) {
  2333.     return ko.hasPrototype(instance, ko.computed);
  2334. };
  2335.  
  2336. ko.isPureComputed = function (instance) {
  2337.     return ko.hasPrototype(instance, ko.computed)
  2338.         && instance[computedState] && instance[computedState].pure;
  2339. };
  2340.  
  2341. ko.exportSymbol('computed', ko.computed);
  2342. ko.exportSymbol('dependentObservable', ko.computed);    // export ko.dependentObservable for backwards compatibility (1.x)
  2343. ko.exportSymbol('isComputed', ko.isComputed);
  2344. ko.exportSymbol('isPureComputed', ko.isPureComputed);
  2345. ko.exportSymbol('computed.fn', computedFn);
  2346. ko.exportProperty(computedFn, 'peek', computedFn.peek);
  2347. ko.exportProperty(computedFn, 'dispose', computedFn.dispose);
  2348. ko.exportProperty(computedFn, 'isActive', computedFn.isActive);
  2349. ko.exportProperty(computedFn, 'getDependenciesCount', computedFn.getDependenciesCount);
  2350.  
  2351. ko.pureComputed = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget) {
  2352.     if (typeof evaluatorFunctionOrOptions === 'function') {
  2353.         return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget, {'pure':true});
  2354.     } else {
  2355.         evaluatorFunctionOrOptions = ko.utils.extend({}, evaluatorFunctionOrOptions);   // make a copy of the parameter object
  2356.         evaluatorFunctionOrOptions['pure'] = true;
  2357.         return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget);
  2358.     }
  2359. }
  2360. ko.exportSymbol('pureComputed', ko.pureComputed);
  2361.  
  2362. (function() {
  2363.     var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
  2364.  
  2365.     ko.toJS = function(rootObject) {
  2366.         if (arguments.length == 0)
  2367.             throw new Error("When calling ko.toJS, pass the object you want to convert.");
  2368.  
  2369.         // We just unwrap everything at every level in the object graph
  2370.         return mapJsObjectGraph(rootObject, function(valueToMap) {
  2371.             // Loop because an observable's value might in turn be another observable wrapper
  2372.             for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
  2373.                 valueToMap = valueToMap();
  2374.             return valueToMap;
  2375.         });
  2376.     };
  2377.  
  2378.     ko.toJSON = function(rootObject, replacer, space) {     // replacer and space are optional
  2379.         var plainJavaScriptObject = ko.toJS(rootObject);
  2380.         return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
  2381.     };
  2382.  
  2383.     function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
  2384.         visitedObjects = visitedObjects || new objectLookup();
  2385.  
  2386.         rootObject = mapInputCallback(rootObject);
  2387.         var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof RegExp)) && (!(rootObject instanceof Date)) && (!(rootObject instanceof String)) && (!(rootObject instanceof Number)) && (!(rootObject instanceof Boolean));
  2388.         if (!canHaveProperties)
  2389.             return rootObject;
  2390.  
  2391.         var outputProperties = rootObject instanceof Array ? [] : {};
  2392.         visitedObjects.save(rootObject, outputProperties);
  2393.  
  2394.         visitPropertiesOrArrayEntries(rootObject, function(indexer) {
  2395.             var propertyValue = mapInputCallback(rootObject[indexer]);
  2396.  
  2397.             switch (typeof propertyValue) {
  2398.                 case "boolean":
  2399.                 case "number":
  2400.                 case "string":
  2401.                 case "function":
  2402.                     outputProperties[indexer] = propertyValue;
  2403.                     break;
  2404.                 case "object":
  2405.                 case "undefined":
  2406.                     var previouslyMappedValue = visitedObjects.get(propertyValue);
  2407.                     outputProperties[indexer] = (previouslyMappedValue !== undefined)
  2408.                         ? previouslyMappedValue
  2409.                         : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
  2410.                     break;
  2411.             }
  2412.         });
  2413.  
  2414.         return outputProperties;
  2415.     }
  2416.  
  2417.     function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
  2418.         if (rootObject instanceof Array) {
  2419.             for (var i = 0; i < rootObject.length; i++)
  2420.                 visitorCallback(i);
  2421.  
  2422.             // For arrays, also respect toJSON property for custom mappings (fixes #278)
  2423.             if (typeof rootObject['toJSON'] == 'function')
  2424.                 visitorCallback('toJSON');
  2425.         } else {
  2426.             for (var propertyName in rootObject) {
  2427.                 visitorCallback(propertyName);
  2428.             }
  2429.         }
  2430.     };
  2431.  
  2432.     function objectLookup() {
  2433.         this.keys = [];
  2434.         this.values = [];
  2435.     };
  2436.  
  2437.     objectLookup.prototype = {
  2438.         constructor: objectLookup,
  2439.         save: function(key, value) {
  2440.             var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
  2441.             if (existingIndex >= 0)
  2442.                 this.values[existingIndex] = value;
  2443.             else {
  2444.                 this.keys.push(key);
  2445.                 this.values.push(value);
  2446.             }
  2447.         },
  2448.         get: function(key) {
  2449.             var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
  2450.             return (existingIndex >= 0) ? this.values[existingIndex] : undefined;
  2451.         }
  2452.     };
  2453. })();
  2454.  
  2455. ko.exportSymbol('toJS', ko.toJS);
  2456. ko.exportSymbol('toJSON', ko.toJSON);
  2457. (function () {
  2458.     var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
  2459.  
  2460.     // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
  2461.     // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
  2462.     // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
  2463.     ko.selectExtensions = {
  2464.         readValue : function(element) {
  2465.             switch (ko.utils.tagNameLower(element)) {
  2466.                 case 'option':
  2467.                     if (element[hasDomDataExpandoProperty] === true)
  2468.                         return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
  2469.                     return ko.utils.ieVersion <= 7
  2470.                         ? (element.getAttributeNode('value') && element.getAttributeNode('value').specified ? element.value : element.text)
  2471.                         : element.value;
  2472.                 case 'select':
  2473.                     return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
  2474.                 default:
  2475.                     return element.value;
  2476.             }
  2477.         },
  2478.  
  2479.         writeValue: function(element, value, allowUnset) {
  2480.             switch (ko.utils.tagNameLower(element)) {
  2481.                 case 'option':
  2482.                     switch(typeof value) {
  2483.                         case "string":
  2484.                             ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
  2485.                             if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
  2486.                                 delete element[hasDomDataExpandoProperty];
  2487.                             }
  2488.                             element.value = value;
  2489.                             break;
  2490.                         default:
  2491.                             // Store arbitrary object using DomData
  2492.                             ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
  2493.                             element[hasDomDataExpandoProperty] = true;
  2494.  
  2495.                             // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
  2496.                             element.value = typeof value === "number" ? value : "";
  2497.                             break;
  2498.                     }
  2499.                     break;
  2500.                 case 'select':
  2501.                     if (value === "" || value === null)       // A blank string or null value will select the caption
  2502.                         value = undefined;
  2503.                     var selection = -1;
  2504.                     for (var i = 0, n = element.options.length, optionValue; i < n; ++i) {
  2505.                         optionValue = ko.selectExtensions.readValue(element.options[i]);
  2506.                         // Include special check to handle selecting a caption with a blank string value
  2507.                         if (optionValue == value || (optionValue == "" && value === undefined)) {
  2508.                             selection = i;
  2509.                             break;
  2510.                         }
  2511.                     }
  2512.                     if (allowUnset || selection >= 0 || (value === undefined && element.size > 1)) {
  2513.                         element.selectedIndex = selection;
  2514.                     }
  2515.                     break;
  2516.                 default:
  2517.                     if ((value === null) || (value === undefined))
  2518.                         value = "";
  2519.                     element.value = value;
  2520.                     break;
  2521.             }
  2522.         }
  2523.     };
  2524. })();
  2525.  
  2526. ko.exportSymbol('selectExtensions', ko.selectExtensions);
  2527. ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
  2528. ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
  2529. ko.expressionRewriting = (function () {
  2530.     var javaScriptReservedWords = ["true", "false", "null", "undefined"];
  2531.  
  2532.     // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
  2533.     // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
  2534.     // This also will not properly handle nested brackets (e.g., obj1[obj2['prop']]; see #911).
  2535.     var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
  2536.  
  2537.     function getWriteableValue(expression) {
  2538.         if (ko.utils.arrayIndexOf(javaScriptReservedWords, expression) >= 0)
  2539.             return false;
  2540.         var match = expression.match(javaScriptAssignmentTarget);
  2541.         return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
  2542.     }
  2543.  
  2544.     // The following regular expressions will be used to split an object-literal string into tokens
  2545.  
  2546.         // These two match strings, either with double quotes or single quotes
  2547.     var stringDouble = '"(?:[^"\\\\]|\\\\.)*"',
  2548.         stringSingle = "'(?:[^'\\\\]|\\\\.)*'",
  2549.         // Matches a regular expression (text enclosed by slashes), but will also match sets of divisions
  2550.         // as a regular expression (this is handled by the parsing loop below).
  2551.         stringRegexp = '/(?:[^/\\\\]|\\\\.)*/\w*',
  2552.         // These characters have special meaning to the parser and must not appear in the middle of a
  2553.         // token, except as part of a string.
  2554.         specials = ',"\'{}()/:[\\]',
  2555.         // Match text (at least two characters) that does not contain any of the above special characters,
  2556.         // although some of the special characters are allowed to start it (all but the colon and comma).
  2557.         // The text can contain spaces, but leading or trailing spaces are skipped.
  2558.         everyThingElse = '[^\\s:,/][^' + specials + ']*[^\\s' + specials + ']',
  2559.         // Match any non-space character not matched already. This will match colons and commas, since they're
  2560.         // not matched by "everyThingElse", but will also match any other single character that wasn't already
  2561.         // matched (for example: in "a: 1, b: 2", each of the non-space characters will be matched by oneNotSpace).
  2562.         oneNotSpace = '[^\\s]',
  2563.  
  2564.         // Create the actual regular expression by or-ing the above strings. The order is important.
  2565.         bindingToken = RegExp(stringDouble + '|' + stringSingle + '|' + stringRegexp + '|' + everyThingElse + '|' + oneNotSpace, 'g'),
  2566.  
  2567.         // Match end of previous token to determine whether a slash is a division or regex.
  2568.         divisionLookBehind = /[\])"'A-Za-z0-9_$]+$/,
  2569.         keywordRegexLookBehind = {'in':1,'return':1,'typeof':1};
  2570.  
  2571.     function parseObjectLiteral(objectLiteralString) {
  2572.         // Trim leading and trailing spaces from the string
  2573.         var str = ko.utils.stringTrim(objectLiteralString);
  2574.  
  2575.         // Trim braces '{' surrounding the whole object literal
  2576.         if (str.charCodeAt(0) === 123) str = str.slice(1, -1);
  2577.  
  2578.         // Split into tokens
  2579.         var result = [], toks = str.match(bindingToken), key, values = [], depth = 0;
  2580.  
  2581.         if (toks) {
  2582.             // Append a comma so that we don't need a separate code block to deal with the last item
  2583.             toks.push(',');
  2584.  
  2585.             for (var i = 0, tok; tok = toks[i]; ++i) {
  2586.                 var c = tok.charCodeAt(0);
  2587.                 // A comma signals the end of a key/value pair if depth is zero
  2588.                 if (c === 44) { // ","
  2589.                     if (depth <= 0) {
  2590.                         result.push((key && values.length) ? {key: key, value: values.join('')} : {'unknown': key || values.join('')});
  2591.                         key = depth = 0;
  2592.                         values = [];
  2593.                         continue;
  2594.                     }
  2595.                 // Simply skip the colon that separates the name and value
  2596.                 } else if (c === 58) { // ":"
  2597.                     if (!depth && !key && values.length === 1) {
  2598.                         key = values.pop();
  2599.                         continue;
  2600.                     }
  2601.                 // A set of slashes is initially matched as a regular expression, but could be division
  2602.                 } else if (c === 47 && i && tok.length > 1) {  // "/"
  2603.                     // Look at the end of the previous token to determine if the slash is actually division
  2604.                     var match = toks[i-1].match(divisionLookBehind);
  2605.                     if (match && !keywordRegexLookBehind[match[0]]) {
  2606.                         // The slash is actually a division punctuator; re-parse the remainder of the string (not including the slash)
  2607.                         str = str.substr(str.indexOf(tok) + 1);
  2608.                         toks = str.match(bindingToken);
  2609.                         toks.push(',');
  2610.                         i = -1;
  2611.                         // Continue with just the slash
  2612.                         tok = '/';
  2613.                     }
  2614.                 // Increment depth for parentheses, braces, and brackets so that interior commas are ignored
  2615.                 } else if (c === 40 || c === 123 || c === 91) { // '(', '{', '['
  2616.                     ++depth;
  2617.                 } else if (c === 41 || c === 125 || c === 93) { // ')', '}', ']'
  2618.                     --depth;
  2619.                 // The key will be the first token; if it's a string, trim the quotes
  2620.                 } else if (!key && !values.length && (c === 34 || c === 39)) { // '"', "'"
  2621.                     tok = tok.slice(1, -1);
  2622.                 }
  2623.                 values.push(tok);
  2624.             }
  2625.         }
  2626.         return result;
  2627.     }
  2628.  
  2629.     // Two-way bindings include a write function that allow the handler to update the value even if it's not an observable.
  2630.     var twoWayBindings = {};
  2631.  
  2632.     function preProcessBindings(bindingsStringOrKeyValueArray, bindingOptions) {
  2633.         bindingOptions = bindingOptions || {};
  2634.  
  2635.         function processKeyValue(key, val) {
  2636.             var writableVal;
  2637.             function callPreprocessHook(obj) {
  2638.                 return (obj && obj['preprocess']) ? (val = obj['preprocess'](val, key, processKeyValue)) : true;
  2639.             }
  2640.             if (!bindingParams) {
  2641.                 if (!callPreprocessHook(ko['getBindingHandler'](key)))
  2642.                     return;
  2643.  
  2644.                 if (twoWayBindings[key] && (writableVal = getWriteableValue(val))) {
  2645.                     // For two-way bindings, provide a write method in case the value
  2646.                     // isn't a writable observable.
  2647.                     propertyAccessorResultStrings.push("'" + key + "':function(_z){" + writableVal + "=_z}");
  2648.                 }
  2649.             }
  2650.             // Values are wrapped in a function so that each value can be accessed independently
  2651.             if (makeValueAccessors) {
  2652.                 val = 'function(){return ' + val + ' }';
  2653.             }
  2654.             resultStrings.push("'" + key + "':" + val);
  2655.         }
  2656.  
  2657.         var resultStrings = [],
  2658.             propertyAccessorResultStrings = [],
  2659.             makeValueAccessors = bindingOptions['valueAccessors'],
  2660.             bindingParams = bindingOptions['bindingParams'],
  2661.             keyValueArray = typeof bindingsStringOrKeyValueArray === "string" ?
  2662.                 parseObjectLiteral(bindingsStringOrKeyValueArray) : bindingsStringOrKeyValueArray;
  2663.  
  2664.         ko.utils.arrayForEach(keyValueArray, function(keyValue) {
  2665.             processKeyValue(keyValue.key || keyValue['unknown'], keyValue.value);
  2666.         });
  2667.  
  2668.         if (propertyAccessorResultStrings.length)
  2669.             processKeyValue('_ko_property_writers', "{" + propertyAccessorResultStrings.join(",") + " }");
  2670.  
  2671.         return resultStrings.join(",");
  2672.     }
  2673.  
  2674.     return {
  2675.         bindingRewriteValidators: [],
  2676.  
  2677.         twoWayBindings: twoWayBindings,
  2678.  
  2679.         parseObjectLiteral: parseObjectLiteral,
  2680.  
  2681.         preProcessBindings: preProcessBindings,
  2682.  
  2683.         keyValueArrayContainsKey: function(keyValueArray, key) {
  2684.             for (var i = 0; i < keyValueArray.length; i++)
  2685.                 if (keyValueArray[i]['key'] == key)
  2686.                     return true;
  2687.             return false;
  2688.         },
  2689.  
  2690.         // Internal, private KO utility for updating model properties from within bindings
  2691.         // property:            If the property being updated is (or might be) an observable, pass it here
  2692.         //                      If it turns out to be a writable observable, it will be written to directly
  2693.         // allBindings:         An object with a get method to retrieve bindings in the current execution context.
  2694.         //                      This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
  2695.         // key:                 The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
  2696.         // value:               The value to be written
  2697.         // checkIfDifferent:    If true, and if the property being written is a writable observable, the value will only be written if
  2698.         //                      it is !== existing value on that writable observable
  2699.         writeValueToProperty: function(property, allBindings, key, value, checkIfDifferent) {
  2700.             if (!property || !ko.isObservable(property)) {
  2701.                 var propWriters = allBindings.get('_ko_property_writers');
  2702.                 if (propWriters && propWriters[key])
  2703.                     propWriters[key](value);
  2704.             } else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {
  2705.                 property(value);
  2706.             }
  2707.         }
  2708.     };
  2709. })();
  2710.  
  2711. ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
  2712. ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
  2713. ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
  2714. ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
  2715.  
  2716. // Making bindings explicitly declare themselves as "two way" isn't ideal in the long term (it would be better if
  2717. // all bindings could use an official 'property writer' API without needing to declare that they might). However,
  2718. // since this is not, and has never been, a public API (_ko_property_writers was never documented), it's acceptable
  2719. // as an internal implementation detail in the short term.
  2720. // For those developers who rely on _ko_property_writers in their custom bindings, we expose _twoWayBindings as an
  2721. // undocumented feature that makes it relatively easy to upgrade to KO 3.0. However, this is still not an official
  2722. // public API, and we reserve the right to remove it at any time if we create a real public property writers API.
  2723. ko.exportSymbol('expressionRewriting._twoWayBindings', ko.expressionRewriting.twoWayBindings);
  2724.  
  2725. // For backward compatibility, define the following aliases. (Previously, these function names were misleading because
  2726. // they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
  2727. ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
  2728. ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);
  2729. (function() {
  2730.     // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
  2731.     // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
  2732.     // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
  2733.     // of that virtual hierarchy
  2734.     //
  2735.     // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
  2736.     // without having to scatter special cases all over the binding and templating code.
  2737.  
  2738.     // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
  2739.     // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
  2740.     // So, use node.text where available, and node.nodeValue elsewhere
  2741.     var commentNodesHaveTextProperty = document && document.createComment("test").text === "<!--test-->";
  2742.  
  2743.     var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/;
  2744.     var endCommentRegex =   commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
  2745.     var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
  2746.  
  2747.     function isStartComment(node) {
  2748.         return (node.nodeType == 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
  2749.     }
  2750.  
  2751.     function isEndComment(node) {
  2752.         return (node.nodeType == 8) && endCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
  2753.     }
  2754.  
  2755.     function getVirtualChildren(startComment, allowUnbalanced) {
  2756.         var currentNode = startComment;
  2757.         var depth = 1;
  2758.         var children = [];
  2759.         while (currentNode = currentNode.nextSibling) {
  2760.             if (isEndComment(currentNode)) {
  2761.                 depth--;
  2762.                 if (depth === 0)
  2763.                     return children;
  2764.             }
  2765.  
  2766.             children.push(currentNode);
  2767.  
  2768.             if (isStartComment(currentNode))
  2769.                 depth++;
  2770.         }
  2771.         if (!allowUnbalanced)
  2772.             throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
  2773.         return null;
  2774.     }
  2775.  
  2776.     function getMatchingEndComment(startComment, allowUnbalanced) {
  2777.         var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
  2778.         if (allVirtualChildren) {
  2779.             if (allVirtualChildren.length > 0)
  2780.                 return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
  2781.             return startComment.nextSibling;
  2782.         } else
  2783.             return null; // Must have no matching end comment, and allowUnbalanced is true
  2784.     }
  2785.  
  2786.     function getUnbalancedChildTags(node) {
  2787.         // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
  2788.         //       from <div>OK</div><!-- /ko --><!-- /ko -->,             returns: <!-- /ko --><!-- /ko -->
  2789.         var childNode = node.firstChild, captureRemaining = null;
  2790.         if (childNode) {
  2791.             do {
  2792.                 if (captureRemaining)                   // We already hit an unbalanced node and are now just scooping up all subsequent nodes
  2793.                     captureRemaining.push(childNode);
  2794.                 else if (isStartComment(childNode)) {
  2795.                     var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
  2796.                     if (matchingEndComment)             // It's a balanced tag, so skip immediately to the end of this virtual set
  2797.                         childNode = matchingEndComment;
  2798.                     else
  2799.                         captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
  2800.                 } else if (isEndComment(childNode)) {
  2801.                     captureRemaining = [childNode];     // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
  2802.                 }
  2803.             } while (childNode = childNode.nextSibling);
  2804.         }
  2805.         return captureRemaining;
  2806.     }
  2807.  
  2808.     ko.virtualElements = {
  2809.         allowedBindings: {},
  2810.  
  2811.         childNodes: function(node) {
  2812.             return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
  2813.         },
  2814.  
  2815.         emptyNode: function(node) {
  2816.             if (!isStartComment(node))
  2817.                 ko.utils.emptyDomNode(node);
  2818.             else {
  2819.                 var virtualChildren = ko.virtualElements.childNodes(node);
  2820.                 for (var i = 0, j = virtualChildren.length; i < j; i++)
  2821.                     ko.removeNode(virtualChildren[i]);
  2822.             }
  2823.         },
  2824.  
  2825.         setDomNodeChildren: function(node, childNodes) {
  2826.             if (!isStartComment(node))
  2827.                 ko.utils.setDomNodeChildren(node, childNodes);
  2828.             else {
  2829.                 ko.virtualElements.emptyNode(node);
  2830.                 var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
  2831.                 for (var i = 0, j = childNodes.length; i < j; i++)
  2832.                     endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
  2833.             }
  2834.         },
  2835.  
  2836.         prepend: function(containerNode, nodeToPrepend) {
  2837.             if (!isStartComment(containerNode)) {
  2838.                 if (containerNode.firstChild)
  2839.                     containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
  2840.                 else
  2841.                     containerNode.appendChild(nodeToPrepend);
  2842.             } else {
  2843.                 // Start comments must always have a parent and at least one following sibling (the end comment)
  2844.                 containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
  2845.             }
  2846.         },
  2847.  
  2848.         insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
  2849.             if (!insertAfterNode) {
  2850.                 ko.virtualElements.prepend(containerNode, nodeToInsert);
  2851.             } else if (!isStartComment(containerNode)) {
  2852.                 // Insert after insertion point
  2853.                 if (insertAfterNode.nextSibling)
  2854.                     containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
  2855.                 else
  2856.                     containerNode.appendChild(nodeToInsert);
  2857.             } else {
  2858.                 // Children of start comments must always have a parent and at least one following sibling (the end comment)
  2859.                 containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
  2860.             }
  2861.         },
  2862.  
  2863.         firstChild: function(node) {
  2864.             if (!isStartComment(node))
  2865.                 return node.firstChild;
  2866.             if (!node.nextSibling || isEndComment(node.nextSibling))
  2867.                 return null;
  2868.             return node.nextSibling;
  2869.         },
  2870.  
  2871.         nextSibling: function(node) {
  2872.             if (isStartComment(node))
  2873.                 node = getMatchingEndComment(node);
  2874.             if (node.nextSibling && isEndComment(node.nextSibling))
  2875.                 return null;
  2876.             return node.nextSibling;
  2877.         },
  2878.  
  2879.         hasBindingValue: isStartComment,
  2880.  
  2881.         virtualNodeBindingValue: function(node) {
  2882.             var regexMatch = (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
  2883.             return regexMatch ? regexMatch[1] : null;
  2884.         },
  2885.  
  2886.         normaliseVirtualElementDomStructure: function(elementVerified) {
  2887.             // Workaround for https://github.com/SteveSanderson/knockout/issues/155
  2888.             // (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
  2889.             // that are direct descendants of <ul> into the preceding <li>)
  2890.             if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
  2891.                 return;
  2892.  
  2893.             // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
  2894.             // must be intended to appear *after* that child, so move them there.
  2895.             var childNode = elementVerified.firstChild;
  2896.             if (childNode) {
  2897.                 do {
  2898.                     if (childNode.nodeType === 1) {
  2899.                         var unbalancedTags = getUnbalancedChildTags(childNode);
  2900.                         if (unbalancedTags) {
  2901.                             // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
  2902.                             var nodeToInsertBefore = childNode.nextSibling;
  2903.                             for (var i = 0; i < unbalancedTags.length; i++) {
  2904.                                 if (nodeToInsertBefore)
  2905.                                     elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
  2906.                                 else
  2907.                                     elementVerified.appendChild(unbalancedTags[i]);
  2908.                             }
  2909.                         }
  2910.                     }
  2911.                 } while (childNode = childNode.nextSibling);
  2912.             }
  2913.         }
  2914.     };
  2915. })();
  2916. ko.exportSymbol('virtualElements', ko.virtualElements);
  2917. ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
  2918. ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
  2919. //ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild);     // firstChild is not minified
  2920. ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
  2921. //ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling);   // nextSibling is not minified
  2922. ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
  2923. ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
  2924. (function() {
  2925.     var defaultBindingAttributeName = "data-bind";
  2926.  
  2927.     ko.bindingProvider = function() {
  2928.         this.bindingCache = {};
  2929.     };
  2930.  
  2931.     ko.utils.extend(ko.bindingProvider.prototype, {
  2932.         'nodeHasBindings': function(node) {
  2933.             switch (node.nodeType) {
  2934.                 case 1: // Element
  2935.                     return node.getAttribute(defaultBindingAttributeName) != null
  2936.                         || ko.components['getComponentNameForNode'](node);
  2937.                 case 8: // Comment node
  2938.                     return ko.virtualElements.hasBindingValue(node);
  2939.                 default: return false;
  2940.             }
  2941.         },
  2942.  
  2943.         'getBindings': function(node, bindingContext) {
  2944.             var bindingsString = this['getBindingsString'](node, bindingContext),
  2945.                 parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
  2946.             return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ false);
  2947.         },
  2948.  
  2949.         'getBindingAccessors': function(node, bindingContext) {
  2950.             var bindingsString = this['getBindingsString'](node, bindingContext),
  2951.                 parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node, { 'valueAccessors': true }) : null;
  2952.             return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ true);
  2953.         },
  2954.  
  2955.         // The following function is only used internally by this default provider.
  2956.         // It's not part of the interface definition for a general binding provider.
  2957.         'getBindingsString': function(node, bindingContext) {
  2958.             switch (node.nodeType) {
  2959.                 case 1: return node.getAttribute(defaultBindingAttributeName);   // Element
  2960.                 case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
  2961.                 default: return null;
  2962.             }
  2963.         },
  2964.  
  2965.         // The following function is only used internally by this default provider.
  2966.         // It's not part of the interface definition for a general binding provider.
  2967.         'parseBindingsString': function(bindingsString, bindingContext, node, options) {
  2968.             try {
  2969.                 var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache, options);
  2970.                 return bindingFunction(bindingContext, node);
  2971.             } catch (ex) {
  2972.                 ex.message = "Unable to parse bindings.\nBindings value: " + bindingsString + "\nMessage: " + ex.message;
  2973.                 throw ex;
  2974.             }
  2975.         }
  2976.     });
  2977.  
  2978.     ko.bindingProvider['instance'] = new ko.bindingProvider();
  2979.  
  2980.     function createBindingsStringEvaluatorViaCache(bindingsString, cache, options) {
  2981.         var cacheKey = bindingsString + (options && options['valueAccessors'] || '');
  2982.         return cache[cacheKey]
  2983.             || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, options));
  2984.     }
  2985.  
  2986.     function createBindingsStringEvaluator(bindingsString, options) {
  2987.         // Build the source for a function that evaluates "expression"
  2988.         // For each scope variable, add an extra level of "with" nesting
  2989.         // Example result: with(sc1) { with(sc0) { return (expression) } }
  2990.         var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString, options),
  2991.             functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
  2992.         return new Function("$context", "$element", functionBody);
  2993.     }
  2994. })();
  2995.  
  2996. ko.exportSymbol('bindingProvider', ko.bindingProvider);
  2997. (function () {
  2998.     ko.bindingHandlers = {};
  2999.  
  3000.     // The following element types will not be recursed into during binding.
  3001.     var bindingDoesNotRecurseIntoElementTypes = {
  3002.         // Don't want bindings that operate on text nodes to mutate <script> and <textarea> contents,
  3003.         // because it's unexpected and a potential XSS issue.
  3004.         // Also bindings should not operate on <template> elements since this breaks in Internet Explorer
  3005.         // and because such elements' contents are always intended to be bound in a different context
  3006.         // from where they appear in the document.
  3007.         'script': true,
  3008.         'textarea': true,
  3009.         'template': true
  3010.     };
  3011.  
  3012.     // Use an overridable method for retrieving binding handlers so that a plugins may support dynamically created handlers
  3013.     ko['getBindingHandler'] = function(bindingKey) {
  3014.         return ko.bindingHandlers[bindingKey];
  3015.     };
  3016.  
  3017.     // The ko.bindingContext constructor is only called directly to create the root context. For child
  3018.     // contexts, use bindingContext.createChildContext or bindingContext.extend.
  3019.     ko.bindingContext = function(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback, options) {
  3020.  
  3021.         // The binding context object includes static properties for the current, parent, and root view models.
  3022.         // If a view model is actually stored in an observable, the corresponding binding context object, and
  3023.         // any child contexts, must be updated when the view model is changed.
  3024.         function updateContext() {
  3025.             // Most of the time, the context will directly get a view model object, but if a function is given,
  3026.             // we call the function to retrieve the view model. If the function accesses any observables or returns
  3027.             // an observable, the dependency is tracked, and those observables can later cause the binding
  3028.             // context to be updated.
  3029.             var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
  3030.                 dataItem = ko.utils.unwrapObservable(dataItemOrObservable);
  3031.  
  3032.             if (parentContext) {
  3033.                 // When a "parent" context is given, register a dependency on the parent context. Thus whenever the
  3034.                 // parent context is updated, this context will also be updated.
  3035.                 if (parentContext._subscribable)
  3036.                     parentContext._subscribable();
  3037.  
  3038.                 // Copy $root and any custom properties from the parent context
  3039.                 ko.utils.extend(self, parentContext);
  3040.  
  3041.                 // Because the above copy overwrites our own properties, we need to reset them.
  3042.                 self._subscribable = subscribable;
  3043.             } else {
  3044.                 self['$parents'] = [];
  3045.                 self['$root'] = dataItem;
  3046.  
  3047.                 // Export 'ko' in the binding context so it will be available in bindings and templates
  3048.                 // even if 'ko' isn't exported as a global, such as when using an AMD loader.
  3049.                 // See https://github.com/SteveSanderson/knockout/issues/490
  3050.                 self['ko'] = ko;
  3051.             }
  3052.             self['$rawData'] = dataItemOrObservable;
  3053.             self['$data'] = dataItem;
  3054.             if (dataItemAlias)
  3055.                 self[dataItemAlias] = dataItem;
  3056.  
  3057.             // The extendCallback function is provided when creating a child context or extending a context.
  3058.             // It handles the specific actions needed to finish setting up the binding context. Actions in this
  3059.             // function could also add dependencies to this binding context.
  3060.             if (extendCallback)
  3061.                 extendCallback(self, parentContext, dataItem);
  3062.  
  3063.             return self['$data'];
  3064.         }
  3065.         function disposeWhen() {
  3066.             return nodes && !ko.utils.anyDomNodeIsAttachedToDocument(nodes);
  3067.         }
  3068.  
  3069.         var self = this,
  3070.             isFunc = typeof(dataItemOrAccessor) == "function" && !ko.isObservable(dataItemOrAccessor),
  3071.             nodes,
  3072.             subscribable;
  3073.  
  3074.         if (options && options['exportDependencies']) {
  3075.             // The "exportDependencies" option means that the calling code will track any dependencies and re-create
  3076.             // the binding context when they change.
  3077.             updateContext();
  3078.         } else {
  3079.             subscribable = ko.dependentObservable(updateContext, null, { disposeWhen: disposeWhen, disposeWhenNodeIsRemoved: true });
  3080.  
  3081.             // At this point, the binding context has been initialized, and the "subscribable" computed observable is
  3082.             // subscribed to any observables that were accessed in the process. If there is nothing to track, the
  3083.             // computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
  3084.             // the context object.
  3085.             if (subscribable.isActive()) {
  3086.                 self._subscribable = subscribable;
  3087.  
  3088.                 // Always notify because even if the model ($data) hasn't changed, other context properties might have changed
  3089.                 subscribable['equalityComparer'] = null;
  3090.  
  3091.                 // We need to be able to dispose of this computed observable when it's no longer needed. This would be
  3092.                 // easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
  3093.                 // we cannot assume that those nodes have any relation to each other. So instead we track any node that
  3094.                 // the context is attached to, and dispose the computed when all of those nodes have been cleaned.
  3095.  
  3096.                 // Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
  3097.                 nodes = [];
  3098.                 subscribable._addNode = function(node) {
  3099.                     nodes.push(node);
  3100.                     ko.utils.domNodeDisposal.addDisposeCallback(node, function(node) {
  3101.                         ko.utils.arrayRemoveItem(nodes, node);
  3102.                         if (!nodes.length) {
  3103.                             subscribable.dispose();
  3104.                             self._subscribable = subscribable = undefined;
  3105.                         }
  3106.                     });
  3107.                 };
  3108.             }
  3109.         }
  3110.     }
  3111.  
  3112.     // Extend the binding context hierarchy with a new view model object. If the parent context is watching
  3113.     // any observables, the new child context will automatically get a dependency on the parent context.
  3114.     // But this does not mean that the $data value of the child context will also get updated. If the child
  3115.     // view model also depends on the parent view model, you must provide a function that returns the correct
  3116.     // view model on each update.
  3117.     ko.bindingContext.prototype['createChildContext'] = function (dataItemOrAccessor, dataItemAlias, extendCallback, options) {
  3118.         return new ko.bindingContext(dataItemOrAccessor, this, dataItemAlias, function(self, parentContext) {
  3119.             // Extend the context hierarchy by setting the appropriate pointers
  3120.             self['$parentContext'] = parentContext;
  3121.             self['$parent'] = parentContext['$data'];
  3122.             self['$parents'] = (parentContext['$parents'] || []).slice(0);
  3123.             self['$parents'].unshift(self['$parent']);
  3124.             if (extendCallback)
  3125.                 extendCallback(self);
  3126.         }, options);
  3127.     };
  3128.  
  3129.     // Extend the binding context with new custom properties. This doesn't change the context hierarchy.
  3130.     // Similarly to "child" contexts, provide a function here to make sure that the correct values are set
  3131.     // when an observable view model is updated.
  3132.     ko.bindingContext.prototype['extend'] = function(properties) {
  3133.         // If the parent context references an observable view model, "_subscribable" will always be the
  3134.         // latest view model object. If not, "_subscribable" isn't set, and we can use the static "$data" value.
  3135.         return new ko.bindingContext(this._subscribable || this['$data'], this, null, function(self, parentContext) {
  3136.             // This "child" context doesn't directly track a parent observable view model,
  3137.             // so we need to manually set the $rawData value to match the parent.
  3138.             self['$rawData'] = parentContext['$rawData'];
  3139.             ko.utils.extend(self, typeof(properties) == "function" ? properties() : properties);
  3140.         });
  3141.     };
  3142.  
  3143.     ko.bindingContext.prototype.createStaticChildContext = function (dataItemOrAccessor, dataItemAlias) {
  3144.         return this['createChildContext'](dataItemOrAccessor, dataItemAlias, null, { "exportDependencies": true });
  3145.     };
  3146.  
  3147.     // Returns the valueAccesor function for a binding value
  3148.     function makeValueAccessor(value) {
  3149.         return function() {
  3150.             return value;
  3151.         };
  3152.     }
  3153.  
  3154.     // Returns the value of a valueAccessor function
  3155.     function evaluateValueAccessor(valueAccessor) {
  3156.         return valueAccessor();
  3157.     }
  3158.  
  3159.     // Given a function that returns bindings, create and return a new object that contains
  3160.     // binding value-accessors functions. Each accessor function calls the original function
  3161.     // so that it always gets the latest value and all dependencies are captured. This is used
  3162.     // by ko.applyBindingsToNode and getBindingsAndMakeAccessors.
  3163.     function makeAccessorsFromFunction(callback) {
  3164.         return ko.utils.objectMap(ko.dependencyDetection.ignore(callback), function(value, key) {
  3165.             return function() {
  3166.                 return callback()[key];
  3167.             };
  3168.         });
  3169.     }
  3170.  
  3171.     // Given a bindings function or object, create and return a new object that contains
  3172.     // binding value-accessors functions. This is used by ko.applyBindingsToNode.
  3173.     function makeBindingAccessors(bindings, context, node) {
  3174.         if (typeof bindings === 'function') {
  3175.             return makeAccessorsFromFunction(bindings.bind(null, context, node));
  3176.         } else {
  3177.             return ko.utils.objectMap(bindings, makeValueAccessor);
  3178.         }
  3179.     }
  3180.  
  3181.     // This function is used if the binding provider doesn't include a getBindingAccessors function.
  3182.     // It must be called with 'this' set to the provider instance.
  3183.     function getBindingsAndMakeAccessors(node, context) {
  3184.         return makeAccessorsFromFunction(this['getBindings'].bind(this, node, context));
  3185.     }
  3186.  
  3187.     function validateThatBindingIsAllowedForVirtualElements(bindingName) {
  3188.         var validator = ko.virtualElements.allowedBindings[bindingName];
  3189.         if (!validator)
  3190.             throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
  3191.     }
  3192.  
  3193.     function applyBindingsToDescendantsInternal (bindingContext, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
  3194.         var currentChild,
  3195.             nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement),
  3196.             provider = ko.bindingProvider['instance'],
  3197.             preprocessNode = provider['preprocessNode'];
  3198.  
  3199.         // Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's
  3200.         // possible to insert new siblings after it, and/or replace the node with a different one. This can be used to
  3201.         // implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that
  3202.         // trigger insertion of <template> contents at that point in the document.
  3203.         if (preprocessNode) {
  3204.             while (currentChild = nextInQueue) {
  3205.                 nextInQueue = ko.virtualElements.nextSibling(currentChild);
  3206.                 preprocessNode.call(provider, currentChild);
  3207.             }
  3208.             // Reset nextInQueue for the next loop
  3209.             nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
  3210.         }
  3211.  
  3212.         while (currentChild = nextInQueue) {
  3213.             // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
  3214.             nextInQueue = ko.virtualElements.nextSibling(currentChild);
  3215.             applyBindingsToNodeAndDescendantsInternal(bindingContext, currentChild, bindingContextsMayDifferFromDomParentElement);
  3216.         }
  3217.     }
  3218.  
  3219.     function applyBindingsToNodeAndDescendantsInternal (bindingContext, nodeVerified, bindingContextMayDifferFromDomParentElement) {
  3220.         var shouldBindDescendants = true;
  3221.  
  3222.         // Perf optimisation: Apply bindings only if...
  3223.         // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
  3224.         //     Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
  3225.         // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
  3226.         var isElement = (nodeVerified.nodeType === 1);
  3227.         if (isElement) // Workaround IE <= 8 HTML parsing weirdness
  3228.             ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
  3229.  
  3230.         var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement)             // Case (1)
  3231.                                || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified);       // Case (2)
  3232.         if (shouldApplyBindings)
  3233.             shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, bindingContext, bindingContextMayDifferFromDomParentElement)['shouldBindDescendants'];
  3234.  
  3235.         if (shouldBindDescendants && !bindingDoesNotRecurseIntoElementTypes[ko.utils.tagNameLower(nodeVerified)]) {
  3236.             // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
  3237.             //  * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
  3238.             //    hence bindingContextsMayDifferFromDomParentElement is false
  3239.             //  * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
  3240.             //    skip over any number of intermediate virtual elements, any of which might define a custom binding context,
  3241.             //    hence bindingContextsMayDifferFromDomParentElement is true
  3242.             applyBindingsToDescendantsInternal(bindingContext, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
  3243.         }
  3244.     }
  3245.  
  3246.     var boundElementDomDataKey = ko.utils.domData.nextKey();
  3247.  
  3248.  
  3249.     function topologicalSortBindings(bindings) {
  3250.         // Depth-first sort
  3251.         var result = [],                // The list of key/handler pairs that we will return
  3252.             bindingsConsidered = {},    // A temporary record of which bindings are already in 'result'
  3253.             cyclicDependencyStack = []; // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it
  3254.         ko.utils.objectForEach(bindings, function pushBinding(bindingKey) {
  3255.             if (!bindingsConsidered[bindingKey]) {
  3256.                 var binding = ko['getBindingHandler'](bindingKey);
  3257.                 if (binding) {
  3258.                     // First add dependencies (if any) of the current binding
  3259.                     if (binding['after']) {
  3260.                         cyclicDependencyStack.push(bindingKey);
  3261.                         ko.utils.arrayForEach(binding['after'], function(bindingDependencyKey) {
  3262.                             if (bindings[bindingDependencyKey]) {
  3263.                                 if (ko.utils.arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) {
  3264.                                     throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + cyclicDependencyStack.join(", "));
  3265.                                 } else {
  3266.                                     pushBinding(bindingDependencyKey);
  3267.                                 }
  3268.                             }
  3269.                         });
  3270.                         cyclicDependencyStack.length--;
  3271.                     }
  3272.                     // Next add the current binding
  3273.                     result.push({ key: bindingKey, handler: binding });
  3274.                 }
  3275.                 bindingsConsidered[bindingKey] = true;
  3276.             }
  3277.         });
  3278.  
  3279.         return result;
  3280.     }
  3281.  
  3282.     function applyBindingsToNodeInternal(node, sourceBindings, bindingContext, bindingContextMayDifferFromDomParentElement) {
  3283.         // Prevent multiple applyBindings calls for the same node, except when a binding value is specified
  3284.         var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
  3285.         if (!sourceBindings) {
  3286.             if (alreadyBound) {
  3287.                 throw Error("You cannot apply bindings multiple times to the same element.");
  3288.             }
  3289.             ko.utils.domData.set(node, boundElementDomDataKey, true);
  3290.         }
  3291.  
  3292.         // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
  3293.         // we can easily recover it just by scanning up the node's ancestors in the DOM
  3294.         // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
  3295.         if (!alreadyBound && bindingContextMayDifferFromDomParentElement)
  3296.             ko.storedBindingContextForNode(node, bindingContext);
  3297.  
  3298.         // Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings
  3299.         var bindings;
  3300.         if (sourceBindings && typeof sourceBindings !== 'function') {
  3301.             bindings = sourceBindings;
  3302.         } else {
  3303.             var provider = ko.bindingProvider['instance'],
  3304.                 getBindings = provider['getBindingAccessors'] || getBindingsAndMakeAccessors;
  3305.  
  3306.             // Get the binding from the provider within a computed observable so that we can update the bindings whenever
  3307.             // the binding context is updated or if the binding provider accesses observables.
  3308.             var bindingsUpdater = ko.dependentObservable(
  3309.                 function() {
  3310.                     bindings = sourceBindings ? sourceBindings(bindingContext, node) : getBindings.call(provider, node, bindingContext);
  3311.                     // Register a dependency on the binding context to support observable view models.
  3312.                     if (bindings && bindingContext._subscribable)
  3313.                         bindingContext._subscribable();
  3314.                     return bindings;
  3315.                 },
  3316.                 null, { disposeWhenNodeIsRemoved: node }
  3317.             );
  3318.  
  3319.             if (!bindings || !bindingsUpdater.isActive())
  3320.                 bindingsUpdater = null;
  3321.         }
  3322.  
  3323.         var bindingHandlerThatControlsDescendantBindings;
  3324.         if (bindings) {
  3325.             // Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding
  3326.             // context update), just return the value accessor from the binding. Otherwise, return a function that always gets
  3327.             // the latest binding value and registers a dependency on the binding updater.
  3328.             var getValueAccessor = bindingsUpdater
  3329.                 ? function(bindingKey) {
  3330.                     return function() {
  3331.                         return evaluateValueAccessor(bindingsUpdater()[bindingKey]);
  3332.                     };
  3333.                 } : function(bindingKey) {
  3334.                     return bindings[bindingKey];
  3335.                 };
  3336.  
  3337.             // Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated
  3338.             function allBindings() {
  3339.                 return ko.utils.objectMap(bindingsUpdater ? bindingsUpdater() : bindings, evaluateValueAccessor);
  3340.             }
  3341.             // The following is the 3.x allBindings API
  3342.             allBindings['get'] = function(key) {
  3343.                 return bindings[key] && evaluateValueAccessor(getValueAccessor(key));
  3344.             };
  3345.             allBindings['has'] = function(key) {
  3346.                 return key in bindings;
  3347.             };
  3348.  
  3349.             // First put the bindings into the right order
  3350.             var orderedBindings = topologicalSortBindings(bindings);
  3351.  
  3352.             // Go through the sorted bindings, calling init and update for each
  3353.             ko.utils.arrayForEach(orderedBindings, function(bindingKeyAndHandler) {
  3354.                 // Note that topologicalSortBindings has already filtered out any nonexistent binding handlers,
  3355.                 // so bindingKeyAndHandler.handler will always be nonnull.
  3356.                 var handlerInitFn = bindingKeyAndHandler.handler["init"],
  3357.                     handlerUpdateFn = bindingKeyAndHandler.handler["update"],
  3358.                     bindingKey = bindingKeyAndHandler.key;
  3359.  
  3360.                 if (node.nodeType === 8) {
  3361.                     validateThatBindingIsAllowedForVirtualElements(bindingKey);
  3362.                 }
  3363.  
  3364.                 try {
  3365.                     // Run init, ignoring any dependencies
  3366.                     if (typeof handlerInitFn == "function") {
  3367.                         ko.dependencyDetection.ignore(function() {
  3368.                             var initResult = handlerInitFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
  3369.  
  3370.                             // If this binding handler claims to control descendant bindings, make a note of this
  3371.                             if (initResult && initResult['controlsDescendantBindings']) {
  3372.                                 if (bindingHandlerThatControlsDescendantBindings !== undefined)
  3373.                                     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.");
  3374.                                 bindingHandlerThatControlsDescendantBindings = bindingKey;
  3375.                             }
  3376.                         });
  3377.                     }
  3378.  
  3379.                     // Run update in its own computed wrapper
  3380.                     if (typeof handlerUpdateFn == "function") {
  3381.                         ko.dependentObservable(
  3382.                             function() {
  3383.                                 handlerUpdateFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
  3384.                             },
  3385.                             null,
  3386.                             { disposeWhenNodeIsRemoved: node }
  3387.                         );
  3388.                     }
  3389.                 } catch (ex) {
  3390.                     ex.message = "Unable to process binding \"" + bindingKey + ": " + bindings[bindingKey] + "\"\nMessage: " + ex.message;
  3391.                     throw ex;
  3392.                 }
  3393.             });
  3394.         }
  3395.  
  3396.         return {
  3397.             'shouldBindDescendants': bindingHandlerThatControlsDescendantBindings === undefined
  3398.         };
  3399.     };
  3400.  
  3401.     var storedBindingContextDomDataKey = ko.utils.domData.nextKey();
  3402.     ko.storedBindingContextForNode = function (node, bindingContext) {
  3403.         if (arguments.length == 2) {
  3404.             ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
  3405.             if (bindingContext._subscribable)
  3406.                 bindingContext._subscribable._addNode(node);
  3407.         } else {
  3408.             return ko.utils.domData.get(node, storedBindingContextDomDataKey);
  3409.         }
  3410.     }
  3411.  
  3412.     function getBindingContext(viewModelOrBindingContext) {
  3413.         return viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
  3414.             ? viewModelOrBindingContext
  3415.             : new ko.bindingContext(viewModelOrBindingContext);
  3416.     }
  3417.  
  3418.     ko.applyBindingAccessorsToNode = function (node, bindings, viewModelOrBindingContext) {
  3419.         if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
  3420.             ko.virtualElements.normaliseVirtualElementDomStructure(node);
  3421.         return applyBindingsToNodeInternal(node, bindings, getBindingContext(viewModelOrBindingContext), true);
  3422.     };
  3423.  
  3424.     ko.applyBindingsToNode = function (node, bindings, viewModelOrBindingContext) {
  3425.         var context = getBindingContext(viewModelOrBindingContext);
  3426.         return ko.applyBindingAccessorsToNode(node, makeBindingAccessors(bindings, context, node), context);
  3427.     };
  3428.  
  3429.     ko.applyBindingsToDescendants = function(viewModelOrBindingContext, rootNode) {
  3430.         if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
  3431.             applyBindingsToDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
  3432.     };
  3433.  
  3434.     ko.applyBindings = function (viewModelOrBindingContext, rootNode) {
  3435.         // If jQuery is loaded after Knockout, we won't initially have access to it. So save it here.
  3436.         if (!jQueryInstance && window['jQuery']) {
  3437.             jQueryInstance = window['jQuery'];
  3438.         }
  3439.  
  3440.         if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
  3441.             throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
  3442.         rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
  3443.  
  3444.         applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
  3445.     };
  3446.  
  3447.     // Retrieving binding context from arbitrary nodes
  3448.     ko.contextFor = function(node) {
  3449.         // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
  3450.         switch (node.nodeType) {
  3451.             case 1:
  3452.             case 8:
  3453.                 var context = ko.storedBindingContextForNode(node);
  3454.                 if (context) return context;
  3455.                 if (node.parentNode) return ko.contextFor(node.parentNode);
  3456.                 break;
  3457.         }
  3458.         return undefined;
  3459.     };
  3460.     ko.dataFor = function(node) {
  3461.         var context = ko.contextFor(node);
  3462.         return context ? context['$data'] : undefined;
  3463.     };
  3464.  
  3465.     ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
  3466.     ko.exportSymbol('applyBindings', ko.applyBindings);
  3467.     ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
  3468.     ko.exportSymbol('applyBindingAccessorsToNode', ko.applyBindingAccessorsToNode);
  3469.     ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
  3470.     ko.exportSymbol('contextFor', ko.contextFor);
  3471.     ko.exportSymbol('dataFor', ko.dataFor);
  3472. })();
  3473. (function(undefined) {
  3474.     var loadingSubscribablesCache = {}, // Tracks component loads that are currently in flight
  3475.         loadedDefinitionsCache = {};    // Tracks component loads that have already completed
  3476.  
  3477.     ko.components = {
  3478.         get: function(componentName, callback) {
  3479.             var cachedDefinition = getObjectOwnProperty(loadedDefinitionsCache, componentName);
  3480.             if (cachedDefinition) {
  3481.                 // It's already loaded and cached. Reuse the same definition object.
  3482.                 // Note that for API consistency, even cache hits complete asynchronously by default.
  3483.                 // You can bypass this by putting synchronous:true on your component config.
  3484.                 if (cachedDefinition.isSynchronousComponent) {
  3485.                     ko.dependencyDetection.ignore(function() { // See comment in loaderRegistryBehaviors.js for reasoning
  3486.                         callback(cachedDefinition.definition);
  3487.                     });
  3488.                 } else {
  3489.                     ko.tasks.schedule(function() { callback(cachedDefinition.definition); });
  3490.                 }
  3491.             } else {
  3492.                 // Join the loading process that is already underway, or start a new one.
  3493.                 loadComponentAndNotify(componentName, callback);
  3494.             }
  3495.         },
  3496.  
  3497.         clearCachedDefinition: function(componentName) {
  3498.             delete loadedDefinitionsCache[componentName];
  3499.         },
  3500.  
  3501.         _getFirstResultFromLoaders: getFirstResultFromLoaders
  3502.     };
  3503.  
  3504.     function getObjectOwnProperty(obj, propName) {
  3505.         return obj.hasOwnProperty(propName) ? obj[propName] : undefined;
  3506.     }
  3507.  
  3508.     function loadComponentAndNotify(componentName, callback) {
  3509.         var subscribable = getObjectOwnProperty(loadingSubscribablesCache, componentName),
  3510.             completedAsync;
  3511.         if (!subscribable) {
  3512.             // It's not started loading yet. Start loading, and when it's done, move it to loadedDefinitionsCache.
  3513.             subscribable = loadingSubscribablesCache[componentName] = new ko.subscribable();
  3514.             subscribable.subscribe(callback);
  3515.  
  3516.             beginLoadingComponent(componentName, function(definition, config) {
  3517.                 var isSynchronousComponent = !!(config && config['synchronous']);
  3518.                 loadedDefinitionsCache[componentName] = { definition: definition, isSynchronousComponent: isSynchronousComponent };
  3519.                 delete loadingSubscribablesCache[componentName];
  3520.  
  3521.                 // For API consistency, all loads complete asynchronously. However we want to avoid
  3522.                 // adding an extra task schedule if it's unnecessary (i.e., the completion is already
  3523.                 // async).
  3524.                 //
  3525.                 // You can bypass the 'always asynchronous' feature by putting the synchronous:true
  3526.                 // flag on your component configuration when you register it.
  3527.                 if (completedAsync || isSynchronousComponent) {
  3528.                     // Note that notifySubscribers ignores any dependencies read within the callback.
  3529.                     // See comment in loaderRegistryBehaviors.js for reasoning
  3530.                     subscribable['notifySubscribers'](definition);
  3531.                 } else {
  3532.                     ko.tasks.schedule(function() {
  3533.                         subscribable['notifySubscribers'](definition);
  3534.                     });
  3535.                 }
  3536.             });
  3537.             completedAsync = true;
  3538.         } else {
  3539.             subscribable.subscribe(callback);
  3540.         }
  3541.     }
  3542.  
  3543.     function beginLoadingComponent(componentName, callback) {
  3544.         getFirstResultFromLoaders('getConfig', [componentName], function(config) {
  3545.             if (config) {
  3546.                 // We have a config, so now load its definition
  3547.                 getFirstResultFromLoaders('loadComponent', [componentName, config], function(definition) {
  3548.                     callback(definition, config);
  3549.                 });
  3550.             } else {
  3551.                 // The component has no config - it's unknown to all the loaders.
  3552.                 // Note that this is not an error (e.g., a module loading error) - that would abort the
  3553.                 // process and this callback would not run. For this callback to run, all loaders must
  3554.                 // have confirmed they don't know about this component.
  3555.                 callback(null, null);
  3556.             }
  3557.         });
  3558.     }
  3559.  
  3560.     function getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders) {
  3561.         // On the first call in the stack, start with the full set of loaders
  3562.         if (!candidateLoaders) {
  3563.             candidateLoaders = ko.components['loaders'].slice(0); // Use a copy, because we'll be mutating this array
  3564.         }
  3565.  
  3566.         // Try the next candidate
  3567.         var currentCandidateLoader = candidateLoaders.shift();
  3568.         if (currentCandidateLoader) {
  3569.             var methodInstance = currentCandidateLoader[methodName];
  3570.             if (methodInstance) {
  3571.                 var wasAborted = false,
  3572.                     synchronousReturnValue = methodInstance.apply(currentCandidateLoader, argsExceptCallback.concat(function(result) {
  3573.                         if (wasAborted) {
  3574.                             callback(null);
  3575.                         } else if (result !== null) {
  3576.                             // This candidate returned a value. Use it.
  3577.                             callback(result);
  3578.                         } else {
  3579.                             // Try the next candidate
  3580.                             getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);
  3581.                         }
  3582.                     }));
  3583.  
  3584.                 // Currently, loaders may not return anything synchronously. This leaves open the possibility
  3585.                 // that we'll extend the API to support synchronous return values in the future. It won't be
  3586.                 // a breaking change, because currently no loader is allowed to return anything except undefined.
  3587.                 if (synchronousReturnValue !== undefined) {
  3588.                     wasAborted = true;
  3589.  
  3590.                     // Method to suppress exceptions will remain undocumented. This is only to keep
  3591.                     // KO's specs running tidily, since we can observe the loading got aborted without
  3592.                     // having exceptions cluttering up the console too.
  3593.                     if (!currentCandidateLoader['suppressLoaderExceptions']) {
  3594.                         throw new Error('Component loaders must supply values by invoking the callback, not by returning values synchronously.');
  3595.                     }
  3596.                 }
  3597.             } else {
  3598.                 // This candidate doesn't have the relevant handler. Synchronously move on to the next one.
  3599.                 getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);
  3600.             }
  3601.         } else {
  3602.             // No candidates returned a value
  3603.             callback(null);
  3604.         }
  3605.     }
  3606.  
  3607.     // Reference the loaders via string name so it's possible for developers
  3608.     // to replace the whole array by assigning to ko.components.loaders
  3609.     ko.components['loaders'] = [];
  3610.  
  3611.     ko.exportSymbol('components', ko.components);
  3612.     ko.exportSymbol('components.get', ko.components.get);
  3613.     ko.exportSymbol('components.clearCachedDefinition', ko.components.clearCachedDefinition);
  3614. })();
  3615. (function(undefined) {
  3616.  
  3617.     // The default loader is responsible for two things:
  3618.     // 1. Maintaining the default in-memory registry of component configuration objects
  3619.     //    (i.e., the thing you're writing to when you call ko.components.register(someName, ...))
  3620.     // 2. Answering requests for components by fetching configuration objects
  3621.     //    from that default in-memory registry and resolving them into standard
  3622.     //    component definition objects (of the form { createViewModel: ..., template: ... })
  3623.     // Custom loaders may override either of these facilities, i.e.,
  3624.     // 1. To supply configuration objects from some other source (e.g., conventions)
  3625.     // 2. Or, to resolve configuration objects by loading viewmodels/templates via arbitrary logic.
  3626.  
  3627.     var defaultConfigRegistry = {};
  3628.  
  3629.     ko.components.register = function(componentName, config) {
  3630.         if (!config) {
  3631.             throw new Error('Invalid configuration for ' + componentName);
  3632.         }
  3633.  
  3634.         if (ko.components.isRegistered(componentName)) {
  3635.             throw new Error('Component ' + componentName + ' is already registered');
  3636.         }
  3637.  
  3638.         defaultConfigRegistry[componentName] = config;
  3639.     };
  3640.  
  3641.     ko.components.isRegistered = function(componentName) {
  3642.         return defaultConfigRegistry.hasOwnProperty(componentName);
  3643.     };
  3644.  
  3645.     ko.components.unregister = function(componentName) {
  3646.         delete defaultConfigRegistry[componentName];
  3647.         ko.components.clearCachedDefinition(componentName);
  3648.     };
  3649.  
  3650.     ko.components.defaultLoader = {
  3651.         'getConfig': function(componentName, callback) {
  3652.             var result = defaultConfigRegistry.hasOwnProperty(componentName)
  3653.                 ? defaultConfigRegistry[componentName]
  3654.                 : null;
  3655.             callback(result);
  3656.         },
  3657.  
  3658.         'loadComponent': function(componentName, config, callback) {
  3659.             var errorCallback = makeErrorCallback(componentName);
  3660.             possiblyGetConfigFromAmd(errorCallback, config, function(loadedConfig) {
  3661.                 resolveConfig(componentName, errorCallback, loadedConfig, callback);
  3662.             });
  3663.         },
  3664.  
  3665.         'loadTemplate': function(componentName, templateConfig, callback) {
  3666.             resolveTemplate(makeErrorCallback(componentName), templateConfig, callback);
  3667.         },
  3668.  
  3669.         'loadViewModel': function(componentName, viewModelConfig, callback) {
  3670.             resolveViewModel(makeErrorCallback(componentName), viewModelConfig, callback);
  3671.         }
  3672.     };
  3673.  
  3674.     var createViewModelKey = 'createViewModel';
  3675.  
  3676.     // Takes a config object of the form { template: ..., viewModel: ... }, and asynchronously convert it
  3677.     // into the standard component definition format:
  3678.     //    { template: <ArrayOfDomNodes>, createViewModel: function(params, componentInfo) { ... } }.
  3679.     // Since both template and viewModel may need to be resolved asynchronously, both tasks are performed
  3680.     // in parallel, and the results joined when both are ready. We don't depend on any promises infrastructure,
  3681.     // so this is implemented manually below.
  3682.     function resolveConfig(componentName, errorCallback, config, callback) {
  3683.         var result = {},
  3684.             makeCallBackWhenZero = 2,
  3685.             tryIssueCallback = function() {
  3686.                 if (--makeCallBackWhenZero === 0) {
  3687.                     callback(result);
  3688.                 }
  3689.             },
  3690.             templateConfig = config['template'],
  3691.             viewModelConfig = config['viewModel'];
  3692.  
  3693.         if (templateConfig) {
  3694.             possiblyGetConfigFromAmd(errorCallback, templateConfig, function(loadedConfig) {
  3695.                 ko.components._getFirstResultFromLoaders('loadTemplate', [componentName, loadedConfig], function(resolvedTemplate) {
  3696.                     result['template'] = resolvedTemplate;
  3697.                     tryIssueCallback();
  3698.                 });
  3699.             });
  3700.         } else {
  3701.             tryIssueCallback();
  3702.         }
  3703.  
  3704.         if (viewModelConfig) {
  3705.             possiblyGetConfigFromAmd(errorCallback, viewModelConfig, function(loadedConfig) {
  3706.                 ko.components._getFirstResultFromLoaders('loadViewModel', [componentName, loadedConfig], function(resolvedViewModel) {
  3707.                     result[createViewModelKey] = resolvedViewModel;
  3708.                     tryIssueCallback();
  3709.                 });
  3710.             });
  3711.         } else {
  3712.             tryIssueCallback();
  3713.         }
  3714.     }
  3715.  
  3716.     function resolveTemplate(errorCallback, templateConfig, callback) {
  3717.         if (typeof templateConfig === 'string') {
  3718.             // Markup - parse it
  3719.             callback(ko.utils.parseHtmlFragment(templateConfig));
  3720.         } else if (templateConfig instanceof Array) {
  3721.             // Assume already an array of DOM nodes - pass through unchanged
  3722.             callback(templateConfig);
  3723.         } else if (isDocumentFragment(templateConfig)) {
  3724.             // Document fragment - use its child nodes
  3725.             callback(ko.utils.makeArray(templateConfig.childNodes));
  3726.         } else if (templateConfig['element']) {
  3727.             var element = templateConfig['element'];
  3728.             if (isDomElement(element)) {
  3729.                 // Element instance - copy its child nodes
  3730.                 callback(cloneNodesFromTemplateSourceElement(element));
  3731.             } else if (typeof element === 'string') {
  3732.                 // Element ID - find it, then copy its child nodes
  3733.                 var elemInstance = document.getElementById(element);
  3734.                 if (elemInstance) {
  3735.                     callback(cloneNodesFromTemplateSourceElement(elemInstance));
  3736.                 } else {
  3737.                     errorCallback('Cannot find element with ID ' + element);
  3738.                 }
  3739.             } else {
  3740.                 errorCallback('Unknown element type: ' + element);
  3741.             }
  3742.         } else {
  3743.             errorCallback('Unknown template value: ' + templateConfig);
  3744.         }
  3745.     }
  3746.  
  3747.     function resolveViewModel(errorCallback, viewModelConfig, callback) {
  3748.         if (typeof viewModelConfig === 'function') {
  3749.             // Constructor - convert to standard factory function format
  3750.             // By design, this does *not* supply componentInfo to the constructor, as the intent is that
  3751.             // componentInfo contains non-viewmodel data (e.g., the component's element) that should only
  3752.             // be used in factory functions, not viewmodel constructors.
  3753.             callback(function (params /*, componentInfo */) {
  3754.                 return new viewModelConfig(params);
  3755.             });
  3756.         } else if (typeof viewModelConfig[createViewModelKey] === 'function') {
  3757.             // Already a factory function - use it as-is
  3758.             callback(viewModelConfig[createViewModelKey]);
  3759.         } else if ('instance' in viewModelConfig) {
  3760.             // Fixed object instance - promote to createViewModel format for API consistency
  3761.             var fixedInstance = viewModelConfig['instance'];
  3762.             callback(function (params, componentInfo) {
  3763.                 return fixedInstance;
  3764.             });
  3765.         } else if ('viewModel' in viewModelConfig) {
  3766.             // Resolved AMD module whose value is of the form { viewModel: ... }
  3767.             resolveViewModel(errorCallback, viewModelConfig['viewModel'], callback);
  3768.         } else {
  3769.             errorCallback('Unknown viewModel value: ' + viewModelConfig);
  3770.         }
  3771.     }
  3772.  
  3773.     function cloneNodesFromTemplateSourceElement(elemInstance) {
  3774.         switch (ko.utils.tagNameLower(elemInstance)) {
  3775.             case 'script':
  3776.                 return ko.utils.parseHtmlFragment(elemInstance.text);
  3777.             case 'textarea':
  3778.                 return ko.utils.parseHtmlFragment(elemInstance.value);
  3779.             case 'template':
  3780.                 // For browsers with proper <template> element support (i.e., where the .content property
  3781.                 // gives a document fragment), use that document fragment.
  3782.                 if (isDocumentFragment(elemInstance.content)) {
  3783.                     return ko.utils.cloneNodes(elemInstance.content.childNodes);
  3784.                 }
  3785.         }
  3786.  
  3787.         // Regular elements such as <div>, and <template> elements on old browsers that don't really
  3788.         // understand <template> and just treat it as a regular container
  3789.         return ko.utils.cloneNodes(elemInstance.childNodes);
  3790.     }
  3791.  
  3792.     function isDomElement(obj) {
  3793.         if (window['HTMLElement']) {
  3794.             return obj instanceof HTMLElement;
  3795.         } else {
  3796.             return obj && obj.tagName && obj.nodeType === 1;
  3797.         }
  3798.     }
  3799.  
  3800.     function isDocumentFragment(obj) {
  3801.         if (window['DocumentFragment']) {
  3802.             return obj instanceof DocumentFragment;
  3803.         } else {
  3804.             return obj && obj.nodeType === 11;
  3805.         }
  3806.     }
  3807.  
  3808.     function possiblyGetConfigFromAmd(errorCallback, config, callback) {
  3809.         if (typeof config['require'] === 'string') {
  3810.             // The config is the value of an AMD module
  3811.             if (amdRequire || window['require']) {
  3812.                 (amdRequire || window['require'])([config['require']], callback);
  3813.             } else {
  3814.                 errorCallback('Uses require, but no AMD loader is present');
  3815.             }
  3816.         } else {
  3817.             callback(config);
  3818.         }
  3819.     }
  3820.  
  3821.     function makeErrorCallback(componentName) {
  3822.         return function (message) {
  3823.             throw new Error('Component \'' + componentName + '\': ' + message);
  3824.         };
  3825.     }
  3826.  
  3827.     ko.exportSymbol('components.register', ko.components.register);
  3828.     ko.exportSymbol('components.isRegistered', ko.components.isRegistered);
  3829.     ko.exportSymbol('components.unregister', ko.components.unregister);
  3830.  
  3831.     // Expose the default loader so that developers can directly ask it for configuration
  3832.     // or to resolve configuration
  3833.     ko.exportSymbol('components.defaultLoader', ko.components.defaultLoader);
  3834.  
  3835.     // By default, the default loader is the only registered component loader
  3836.     ko.components['loaders'].push(ko.components.defaultLoader);
  3837.  
  3838.     // Privately expose the underlying config registry for use in old-IE shim
  3839.     ko.components._allRegisteredComponents = defaultConfigRegistry;
  3840. })();
  3841. (function (undefined) {
  3842.     // Overridable API for determining which component name applies to a given node. By overriding this,
  3843.     // you can for example map specific tagNames to components that are not preregistered.
  3844.     ko.components['getComponentNameForNode'] = function(node) {
  3845.         var tagNameLower = ko.utils.tagNameLower(node);
  3846.         if (ko.components.isRegistered(tagNameLower)) {
  3847.             // Try to determine that this node can be considered a *custom* element; see https://github.com/knockout/knockout/issues/1603
  3848.             if (tagNameLower.indexOf('-') != -1 || ('' + node) == "[object HTMLUnknownElement]" || (ko.utils.ieVersion <= 8 && node.tagName === tagNameLower)) {
  3849.                 return tagNameLower;
  3850.             }
  3851.         }
  3852.     };
  3853.  
  3854.     ko.components.addBindingsForCustomElement = function(allBindings, node, bindingContext, valueAccessors) {
  3855.         // Determine if it's really a custom element matching a component
  3856.         if (node.nodeType === 1) {
  3857.             var componentName = ko.components['getComponentNameForNode'](node);
  3858.             if (componentName) {
  3859.                 // It does represent a component, so add a component binding for it
  3860.                 allBindings = allBindings || {};
  3861.  
  3862.                 if (allBindings['component']) {
  3863.                     // Avoid silently overwriting some other 'component' binding that may already be on the element
  3864.                     throw new Error('Cannot use the "component" binding on a custom element matching a component');
  3865.                 }
  3866.  
  3867.                 var componentBindingValue = { 'name': componentName, 'params': getComponentParamsFromCustomElement(node, bindingContext) };
  3868.  
  3869.                 allBindings['component'] = valueAccessors
  3870.                     ? function() { return componentBindingValue; }
  3871.                     : componentBindingValue;
  3872.             }
  3873.         }
  3874.  
  3875.         return allBindings;
  3876.     }
  3877.  
  3878.     var nativeBindingProviderInstance = new ko.bindingProvider();
  3879.  
  3880.     function getComponentParamsFromCustomElement(elem, bindingContext) {
  3881.         var paramsAttribute = elem.getAttribute('params');
  3882.  
  3883.         if (paramsAttribute) {
  3884.             var params = nativeBindingProviderInstance['parseBindingsString'](paramsAttribute, bindingContext, elem, { 'valueAccessors': true, 'bindingParams': true }),
  3885.                 rawParamComputedValues = ko.utils.objectMap(params, function(paramValue, paramName) {
  3886.                     return ko.computed(paramValue, null, { disposeWhenNodeIsRemoved: elem });
  3887.                 }),
  3888.                 result = ko.utils.objectMap(rawParamComputedValues, function(paramValueComputed, paramName) {
  3889.                     var paramValue = paramValueComputed.peek();
  3890.                     // Does the evaluation of the parameter value unwrap any observables?
  3891.                     if (!paramValueComputed.isActive()) {
  3892.                         // No it doesn't, so there's no need for any computed wrapper. Just pass through the supplied value directly.
  3893.                         // Example: "someVal: firstName, age: 123" (whether or not firstName is an observable/computed)
  3894.                         return paramValue;
  3895.                     } else {
  3896.                         // Yes it does. Supply a computed property that unwraps both the outer (binding expression)
  3897.                         // level of observability, and any inner (resulting model value) level of observability.
  3898.                         // This means the component doesn't have to worry about multiple unwrapping. If the value is a
  3899.                         // writable observable, the computed will also be writable and pass the value on to the observable.
  3900.                         return ko.computed({
  3901.                             'read': function() {
  3902.                                 return ko.utils.unwrapObservable(paramValueComputed());
  3903.                             },
  3904.                             'write': ko.isWriteableObservable(paramValue) && function(value) {
  3905.                                 paramValueComputed()(value);
  3906.                             },
  3907.                             disposeWhenNodeIsRemoved: elem
  3908.                         });
  3909.                     }
  3910.                 });
  3911.  
  3912.             // Give access to the raw computeds, as long as that wouldn't overwrite any custom param also called '$raw'
  3913.             // This is in case the developer wants to react to outer (binding) observability separately from inner
  3914.             // (model value) observability, or in case the model value observable has subobservables.
  3915.             if (!result.hasOwnProperty('$raw')) {
  3916.                 result['$raw'] = rawParamComputedValues;
  3917.             }
  3918.  
  3919.             return result;
  3920.         } else {
  3921.             // For consistency, absence of a "params" attribute is treated the same as the presence of
  3922.             // any empty one. Otherwise component viewmodels need special code to check whether or not
  3923.             // 'params' or 'params.$raw' is null/undefined before reading subproperties, which is annoying.
  3924.             return { '$raw': {} };
  3925.         }
  3926.     }
  3927.  
  3928.     // --------------------------------------------------------------------------------
  3929.     // Compatibility code for older (pre-HTML5) IE browsers
  3930.  
  3931.     if (ko.utils.ieVersion < 9) {
  3932.         // Whenever you preregister a component, enable it as a custom element in the current document
  3933.         ko.components['register'] = (function(originalFunction) {
  3934.             return function(componentName) {
  3935.                 document.createElement(componentName); // Allows IE<9 to parse markup containing the custom element
  3936.                 return originalFunction.apply(this, arguments);
  3937.             }
  3938.         })(ko.components['register']);
  3939.  
  3940.         // Whenever you create a document fragment, enable all preregistered component names as custom elements
  3941.         // This is needed to make innerShiv/jQuery HTML parsing correctly handle the custom elements
  3942.         document.createDocumentFragment = (function(originalFunction) {
  3943.             return function() {
  3944.                 var newDocFrag = originalFunction(),
  3945.                     allComponents = ko.components._allRegisteredComponents;
  3946.                 for (var componentName in allComponents) {
  3947.                     if (allComponents.hasOwnProperty(componentName)) {
  3948.                         newDocFrag.createElement(componentName);
  3949.                     }
  3950.                 }
  3951.                 return newDocFrag;
  3952.             };
  3953.         })(document.createDocumentFragment);
  3954.     }
  3955. })();(function(undefined) {
  3956.  
  3957.     var componentLoadingOperationUniqueId = 0;
  3958.  
  3959.     ko.bindingHandlers['component'] = {
  3960.         'init': function(element, valueAccessor, ignored1, ignored2, bindingContext) {
  3961.             var currentViewModel,
  3962.                 currentLoadingOperationId,
  3963.                 disposeAssociatedComponentViewModel = function () {
  3964.                     var currentViewModelDispose = currentViewModel && currentViewModel['dispose'];
  3965.                     if (typeof currentViewModelDispose === 'function') {
  3966.                         currentViewModelDispose.call(currentViewModel);
  3967.                     }
  3968.                     currentViewModel = null;
  3969.                     // Any in-flight loading operation is no longer relevant, so make sure we ignore its completion
  3970.                     currentLoadingOperationId = null;
  3971.                 },
  3972.                 originalChildNodes = ko.utils.makeArray(ko.virtualElements.childNodes(element));
  3973.  
  3974.             ko.utils.domNodeDisposal.addDisposeCallback(element, disposeAssociatedComponentViewModel);
  3975.  
  3976.             ko.computed(function () {
  3977.                 var value = ko.utils.unwrapObservable(valueAccessor()),
  3978.                     componentName, componentParams;
  3979.  
  3980.                 if (typeof value === 'string') {
  3981.                     componentName = value;
  3982.                 } else {
  3983.                     componentName = ko.utils.unwrapObservable(value['name']);
  3984.                     componentParams = ko.utils.unwrapObservable(value['params']);
  3985.                 }
  3986.  
  3987.                 if (!componentName) {
  3988.                     throw new Error('No component name specified');
  3989.                 }
  3990.  
  3991.                 var loadingOperationId = currentLoadingOperationId = ++componentLoadingOperationUniqueId;
  3992.                 ko.components.get(componentName, function(componentDefinition) {
  3993.                     // If this is not the current load operation for this element, ignore it.
  3994.                     if (currentLoadingOperationId !== loadingOperationId) {
  3995.                         return;
  3996.                     }
  3997.  
  3998.                     // Clean up previous state
  3999.                     disposeAssociatedComponentViewModel();
  4000.  
  4001.                     // Instantiate and bind new component. Implicitly this cleans any old DOM nodes.
  4002.                     if (!componentDefinition) {
  4003.                         throw new Error('Unknown component \'' + componentName + '\'');
  4004.                     }
  4005.                     cloneTemplateIntoElement(componentName, componentDefinition, element);
  4006.                     var componentViewModel = createViewModel(componentDefinition, element, originalChildNodes, componentParams),
  4007.                         childBindingContext = bindingContext['createChildContext'](componentViewModel, /* dataItemAlias */ undefined, function(ctx) {
  4008.                             ctx['$component'] = componentViewModel;
  4009.                             ctx['$componentTemplateNodes'] = originalChildNodes;
  4010.                         });
  4011.                     currentViewModel = componentViewModel;
  4012.                     ko.applyBindingsToDescendants(childBindingContext, element);
  4013.                 });
  4014.             }, null, { disposeWhenNodeIsRemoved: element });
  4015.  
  4016.             return { 'controlsDescendantBindings': true };
  4017.         }
  4018.     };
  4019.  
  4020.     ko.virtualElements.allowedBindings['component'] = true;
  4021.  
  4022.     function cloneTemplateIntoElement(componentName, componentDefinition, element) {
  4023.         var template = componentDefinition['template'];
  4024.         if (!template) {
  4025.             throw new Error('Component \'' + componentName + '\' has no template');
  4026.         }
  4027.  
  4028.         var clonedNodesArray = ko.utils.cloneNodes(template);
  4029.         ko.virtualElements.setDomNodeChildren(element, clonedNodesArray);
  4030.     }
  4031.  
  4032.     function createViewModel(componentDefinition, element, originalChildNodes, componentParams) {
  4033.         var componentViewModelFactory = componentDefinition['createViewModel'];
  4034.         return componentViewModelFactory
  4035.             ? componentViewModelFactory.call(componentDefinition, componentParams, { 'element': element, 'templateNodes': originalChildNodes })
  4036.             : componentParams; // Template-only component
  4037.     }
  4038.  
  4039. })();
  4040. var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
  4041. ko.bindingHandlers['attr'] = {
  4042.     'update': function(element, valueAccessor, allBindings) {
  4043.         var value = ko.utils.unwrapObservable(valueAccessor()) || {};
  4044.         ko.utils.objectForEach(value, function(attrName, attrValue) {
  4045.             attrValue = ko.utils.unwrapObservable(attrValue);
  4046.  
  4047.             // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
  4048.             // when someProp is a "no value"-like value (strictly null, false, or undefined)
  4049.             // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
  4050.             var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
  4051.             if (toRemove)
  4052.                 element.removeAttribute(attrName);
  4053.  
  4054.             // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
  4055.             // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
  4056.             // but instead of figuring out the mode, we'll just set the attribute through the Javascript
  4057.             // property for IE <= 8.
  4058.             if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
  4059.                 attrName = attrHtmlToJavascriptMap[attrName];
  4060.                 if (toRemove)
  4061.                     element.removeAttribute(attrName);
  4062.                 else
  4063.                     element[attrName] = attrValue;
  4064.             } else if (!toRemove) {
  4065.                 element.setAttribute(attrName, attrValue.toString());
  4066.             }
  4067.  
  4068.             // Treat "name" specially - although you can think of it as an attribute, it also needs
  4069.             // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
  4070.             // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
  4071.             // entirely, and there's no strong reason to allow for such casing in HTML.
  4072.             if (attrName === "name") {
  4073.                 ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
  4074.             }
  4075.         });
  4076.     }
  4077. };
  4078. (function() {
  4079.  
  4080. ko.bindingHandlers['checked'] = {
  4081.     'after': ['value', 'attr'],
  4082.     'init': function (element, valueAccessor, allBindings) {
  4083.         var checkedValue = ko.pureComputed(function() {
  4084.             // Treat "value" like "checkedValue" when it is included with "checked" binding
  4085.             if (allBindings['has']('checkedValue')) {
  4086.                 return ko.utils.unwrapObservable(allBindings.get('checkedValue'));
  4087.             } else if (allBindings['has']('value')) {
  4088.                 return ko.utils.unwrapObservable(allBindings.get('value'));
  4089.             }
  4090.  
  4091.             return element.value;
  4092.         });
  4093.  
  4094.         function updateModel() {
  4095.             // This updates the model value from the view value.
  4096.             // It runs in response to DOM events (click) and changes in checkedValue.
  4097.             var isChecked = element.checked,
  4098.                 elemValue = useCheckedValue ? checkedValue() : isChecked;
  4099.  
  4100.             // When we're first setting up this computed, don't change any model state.
  4101.             if (ko.computedContext.isInitial()) {
  4102.                 return;
  4103.             }
  4104.  
  4105.             // We can ignore unchecked radio buttons, because some other radio
  4106.             // button will be getting checked, and that one can take care of updating state.
  4107.             if (isRadio && !isChecked) {
  4108.                 return;
  4109.             }
  4110.  
  4111.             var modelValue = ko.dependencyDetection.ignore(valueAccessor);
  4112.             if (valueIsArray) {
  4113.                 var writableValue = rawValueIsNonArrayObservable ? modelValue.peek() : modelValue;
  4114.                 if (oldElemValue !== elemValue) {
  4115.                     // When we're responding to the checkedValue changing, and the element is
  4116.                     // currently checked, replace the old elem value with the new elem value
  4117.                     // in the model array.
  4118.                     if (isChecked) {
  4119.                         ko.utils.addOrRemoveItem(writableValue, elemValue, true);
  4120.                         ko.utils.addOrRemoveItem(writableValue, oldElemValue, false);
  4121.                     }
  4122.  
  4123.                     oldElemValue = elemValue;
  4124.                 } else {
  4125.                     // When we're responding to the user having checked/unchecked a checkbox,
  4126.                     // add/remove the element value to the model array.
  4127.                     ko.utils.addOrRemoveItem(writableValue, elemValue, isChecked);
  4128.                 }
  4129.                 if (rawValueIsNonArrayObservable && ko.isWriteableObservable(modelValue)) {
  4130.                     modelValue(writableValue);
  4131.                 }
  4132.             } else {
  4133.                 ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'checked', elemValue, true);
  4134.             }
  4135.         };
  4136.  
  4137.         function updateView() {
  4138.             // This updates the view value from the model value.
  4139.             // It runs in response to changes in the bound (checked) value.
  4140.             var modelValue = ko.utils.unwrapObservable(valueAccessor());
  4141.  
  4142.             if (valueIsArray) {
  4143.                 // When a checkbox is bound to an array, being checked represents its value being present in that array
  4144.                 element.checked = ko.utils.arrayIndexOf(modelValue, checkedValue()) >= 0;
  4145.             } else if (isCheckbox) {
  4146.                 // When a checkbox is bound to any other value (not an array), being checked represents the value being trueish
  4147.                 element.checked = modelValue;
  4148.             } else {
  4149.                 // For radio buttons, being checked means that the radio button's value corresponds to the model value
  4150.                 element.checked = (checkedValue() === modelValue);
  4151.             }
  4152.         };
  4153.  
  4154.         var isCheckbox = element.type == "checkbox",
  4155.             isRadio = element.type == "radio";
  4156.  
  4157.         // Only bind to check boxes and radio buttons
  4158.         if (!isCheckbox && !isRadio) {
  4159.             return;
  4160.         }
  4161.  
  4162.         var rawValue = valueAccessor(),
  4163.             valueIsArray = isCheckbox && (ko.utils.unwrapObservable(rawValue) instanceof Array),
  4164.             rawValueIsNonArrayObservable = !(valueIsArray && rawValue.push && rawValue.splice),
  4165.             oldElemValue = valueIsArray ? checkedValue() : undefined,
  4166.             useCheckedValue = isRadio || valueIsArray;
  4167.  
  4168.         // IE 6 won't allow radio buttons to be selected unless they have a name
  4169.         if (isRadio && !element.name)
  4170.             ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
  4171.  
  4172.         // Set up two computeds to update the binding:
  4173.  
  4174.         // The first responds to changes in the checkedValue value and to element clicks
  4175.         ko.computed(updateModel, null, { disposeWhenNodeIsRemoved: element });
  4176.         ko.utils.registerEventHandler(element, "click", updateModel);
  4177.  
  4178.         // The second responds to changes in the model value (the one associated with the checked binding)
  4179.         ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
  4180.  
  4181.         rawValue = undefined;
  4182.     }
  4183. };
  4184. ko.expressionRewriting.twoWayBindings['checked'] = true;
  4185.  
  4186. ko.bindingHandlers['checkedValue'] = {
  4187.     'update': function (element, valueAccessor) {
  4188.         element.value = ko.utils.unwrapObservable(valueAccessor());
  4189.     }
  4190. };
  4191.  
  4192. })();var classesWrittenByBindingKey = '__ko__cssValue';
  4193. ko.bindingHandlers['css'] = {
  4194.     'update': function (element, valueAccessor) {
  4195.         var value = ko.utils.unwrapObservable(valueAccessor());
  4196.         if (value !== null && typeof value == "object") {
  4197.             ko.utils.objectForEach(value, function(className, shouldHaveClass) {
  4198.                 shouldHaveClass = ko.utils.unwrapObservable(shouldHaveClass);
  4199.                 ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
  4200.             });
  4201.         } else {
  4202.             value = ko.utils.stringTrim(String(value || '')); // Make sure we don't try to store or set a non-string value
  4203.             ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
  4204.             element[classesWrittenByBindingKey] = value;
  4205.             ko.utils.toggleDomNodeCssClass(element, value, true);
  4206.         }
  4207.     }
  4208. };
  4209. ko.bindingHandlers['enable'] = {
  4210.     'update': function (element, valueAccessor) {
  4211.         var value = ko.utils.unwrapObservable(valueAccessor());
  4212.         if (value && element.disabled)
  4213.             element.removeAttribute("disabled");
  4214.         else if ((!value) && (!element.disabled))
  4215.             element.disabled = true;
  4216.     }
  4217. };
  4218.  
  4219. ko.bindingHandlers['disable'] = {
  4220.     'update': function (element, valueAccessor) {
  4221.         ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
  4222.     }
  4223. };
  4224. // For certain common events (currently just 'click'), allow a simplified data-binding syntax
  4225. // e.g. click:handler instead of the usual full-length event:{click:handler}
  4226. function makeEventHandlerShortcut(eventName) {
  4227.     ko.bindingHandlers[eventName] = {
  4228.         'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  4229.             var newValueAccessor = function () {
  4230.                 var result = {};
  4231.                 result[eventName] = valueAccessor();
  4232.                 return result;
  4233.             };
  4234.             return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindings, viewModel, bindingContext);
  4235.         }
  4236.     }
  4237. }
  4238.  
  4239. ko.bindingHandlers['event'] = {
  4240.     'init' : function (element, valueAccessor, allBindings, viewModel, bindingContext) {
  4241.         var eventsToHandle = valueAccessor() || {};
  4242.         ko.utils.objectForEach(eventsToHandle, function(eventName) {
  4243.             if (typeof eventName == "string") {
  4244.                 ko.utils.registerEventHandler(element, eventName, function (event) {
  4245.                     var handlerReturnValue;
  4246.                     var handlerFunction = valueAccessor()[eventName];
  4247.                     if (!handlerFunction)
  4248.                         return;
  4249.  
  4250.                     try {
  4251.                         // Take all the event args, and prefix with the viewmodel
  4252.                         var argsForHandler = ko.utils.makeArray(arguments);
  4253.                         viewModel = bindingContext['$data'];
  4254.                         argsForHandler.unshift(viewModel);
  4255.                         handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
  4256.                     } finally {
  4257.                         if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
  4258.                             if (event.preventDefault)
  4259.                                 event.preventDefault();
  4260.                             else
  4261.                                 event.returnValue = false;
  4262.                         }
  4263.                     }
  4264.  
  4265.                     var bubble = allBindings.get(eventName + 'Bubble') !== false;
  4266.                     if (!bubble) {
  4267.                         event.cancelBubble = true;
  4268.                         if (event.stopPropagation)
  4269.                             event.stopPropagation();
  4270.                     }
  4271.                 });
  4272.             }
  4273.         });
  4274.     }
  4275. };
  4276. // "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
  4277. // "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
  4278. ko.bindingHandlers['foreach'] = {
  4279.     makeTemplateValueAccessor: function(valueAccessor) {
  4280.         return function() {
  4281.             var modelValue = valueAccessor(),
  4282.                 unwrappedValue = ko.utils.peekObservable(modelValue);    // Unwrap without setting a dependency here
  4283.  
  4284.             // If unwrappedValue is the array, pass in the wrapped value on its own
  4285.             // The value will be unwrapped and tracked within the template binding
  4286.             // (See https://github.com/SteveSanderson/knockout/issues/523)
  4287.             if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
  4288.                 return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
  4289.  
  4290.             // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
  4291.             ko.utils.unwrapObservable(modelValue);
  4292.             return {
  4293.                 'foreach': unwrappedValue['data'],
  4294.                 'as': unwrappedValue['as'],
  4295.                 'includeDestroyed': unwrappedValue['includeDestroyed'],
  4296.                 'afterAdd': unwrappedValue['afterAdd'],
  4297.                 'beforeRemove': unwrappedValue['beforeRemove'],
  4298.                 'afterRender': unwrappedValue['afterRender'],
  4299.                 'beforeMove': unwrappedValue['beforeMove'],
  4300.                 'afterMove': unwrappedValue['afterMove'],
  4301.                 'templateEngine': ko.nativeTemplateEngine.instance
  4302.             };
  4303.         };
  4304.     },
  4305.     'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  4306.         return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
  4307.     },
  4308.     'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  4309.         return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindings, viewModel, bindingContext);
  4310.     }
  4311. };
  4312. ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
  4313. ko.virtualElements.allowedBindings['foreach'] = true;
  4314. var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
  4315. var hasfocusLastValue = '__ko_hasfocusLastValue';
  4316. ko.bindingHandlers['hasfocus'] = {
  4317.     'init': function(element, valueAccessor, allBindings) {
  4318.         var handleElementFocusChange = function(isFocused) {
  4319.             // Where possible, ignore which event was raised and determine focus state using activeElement,
  4320.             // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
  4321.             // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
  4322.             // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
  4323.             // from calling 'blur()' on the element when it loses focus.
  4324.             // Discussion at https://github.com/SteveSanderson/knockout/pull/352
  4325.             element[hasfocusUpdatingProperty] = true;
  4326.             var ownerDoc = element.ownerDocument;
  4327.             if ("activeElement" in ownerDoc) {
  4328.                 var active;
  4329.                 try {
  4330.                     active = ownerDoc.activeElement;
  4331.                 } catch(e) {
  4332.                     // IE9 throws if you access activeElement during page load (see issue #703)
  4333.                     active = ownerDoc.body;
  4334.                 }
  4335.                 isFocused = (active === element);
  4336.             }
  4337.             var modelValue = valueAccessor();
  4338.             ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'hasfocus', isFocused, true);
  4339.  
  4340.             //cache the latest value, so we can avoid unnecessarily calling focus/blur in the update function
  4341.             element[hasfocusLastValue] = isFocused;
  4342.             element[hasfocusUpdatingProperty] = false;
  4343.         };
  4344.         var handleElementFocusIn = handleElementFocusChange.bind(null, true);
  4345.         var handleElementFocusOut = handleElementFocusChange.bind(null, false);
  4346.  
  4347.         ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
  4348.         ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
  4349.         ko.utils.registerEventHandler(element, "blur",  handleElementFocusOut);
  4350.         ko.utils.registerEventHandler(element, "focusout",  handleElementFocusOut); // For IE
  4351.     },
  4352.     'update': function(element, valueAccessor) {
  4353.         var value = !!ko.utils.unwrapObservable(valueAccessor());
  4354.  
  4355.         if (!element[hasfocusUpdatingProperty] && element[hasfocusLastValue] !== value) {
  4356.             value ? element.focus() : element.blur();
  4357.  
  4358.             // In IE, the blur method doesn't always cause the element to lose focus (for example, if the window is not in focus).
  4359.             // Setting focus to the body element does seem to be reliable in IE, but should only be used if we know that the current
  4360.             // element was focused already.
  4361.             if (!value && element[hasfocusLastValue]) {
  4362.                 element.ownerDocument.body.focus();
  4363.             }
  4364.  
  4365.             // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
  4366.             ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]);
  4367.         }
  4368.     }
  4369. };
  4370. ko.expressionRewriting.twoWayBindings['hasfocus'] = true;
  4371.  
  4372. ko.bindingHandlers['hasFocus'] = ko.bindingHandlers['hasfocus']; // Make "hasFocus" an alias
  4373. ko.expressionRewriting.twoWayBindings['hasFocus'] = true;
  4374. ko.bindingHandlers['html'] = {
  4375.     'init': function() {
  4376.         // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
  4377.         return { 'controlsDescendantBindings': true };
  4378.     },
  4379.     'update': function (element, valueAccessor) {
  4380.         // setHtml will unwrap the value if needed
  4381.         ko.utils.setHtml(element, valueAccessor());
  4382.     }
  4383. };
  4384. // Makes a binding like with or if
  4385. function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
  4386.     ko.bindingHandlers[bindingKey] = {
  4387.         'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  4388.             var didDisplayOnLastUpdate,
  4389.                 savedNodes;
  4390.             ko.computed(function() {
  4391.                 var rawValue = valueAccessor(),
  4392.                     dataValue = ko.utils.unwrapObservable(rawValue),
  4393.                     shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
  4394.                     isFirstRender = !savedNodes,
  4395.                     needsRefresh = isFirstRender || isWith || (shouldDisplay !== didDisplayOnLastUpdate);
  4396.  
  4397.                 if (needsRefresh) {
  4398.                     // Save a copy of the inner nodes on the initial update, but only if we have dependencies.
  4399.                     if (isFirstRender && ko.computedContext.getDependenciesCount()) {
  4400.                         savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
  4401.                     }
  4402.  
  4403.                     if (shouldDisplay) {
  4404.                         if (!isFirstRender) {
  4405.                             ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes));
  4406.                         }
  4407.                         ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, rawValue) : bindingContext, element);
  4408.                     } else {
  4409.                         ko.virtualElements.emptyNode(element);
  4410.                     }
  4411.  
  4412.                     didDisplayOnLastUpdate = shouldDisplay;
  4413.                 }
  4414.             }, null, { disposeWhenNodeIsRemoved: element });
  4415.             return { 'controlsDescendantBindings': true };
  4416.         }
  4417.     };
  4418.     ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
  4419.     ko.virtualElements.allowedBindings[bindingKey] = true;
  4420. }
  4421.  
  4422. // Construct the actual binding handlers
  4423. makeWithIfBinding('if');
  4424. makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
  4425. makeWithIfBinding('with', true /* isWith */, false /* isNot */,
  4426.     function(bindingContext, dataValue) {
  4427.         return bindingContext.createStaticChildContext(dataValue);
  4428.     }
  4429. );
  4430. var captionPlaceholder = {};
  4431. ko.bindingHandlers['options'] = {
  4432.     'init': function(element) {
  4433.         if (ko.utils.tagNameLower(element) !== "select")
  4434.             throw new Error("options binding applies only to SELECT elements");
  4435.  
  4436.         // Remove all existing <option>s.
  4437.         while (element.length > 0) {
  4438.             element.remove(0);
  4439.         }
  4440.  
  4441.         // Ensures that the binding processor doesn't try to bind the options
  4442.         return { 'controlsDescendantBindings': true };
  4443.     },
  4444.     'update': function (element, valueAccessor, allBindings) {
  4445.         function selectedOptions() {
  4446.             return ko.utils.arrayFilter(element.options, function (node) { return node.selected; });
  4447.         }
  4448.  
  4449.         var selectWasPreviouslyEmpty = element.length == 0,
  4450.             multiple = element.multiple,
  4451.             previousScrollTop = (!selectWasPreviouslyEmpty && multiple) ? element.scrollTop : null,
  4452.             unwrappedArray = ko.utils.unwrapObservable(valueAccessor()),
  4453.             valueAllowUnset = allBindings.get('valueAllowUnset') && allBindings['has']('value'),
  4454.             includeDestroyed = allBindings.get('optionsIncludeDestroyed'),
  4455.             arrayToDomNodeChildrenOptions = {},
  4456.             captionValue,
  4457.             filteredArray,
  4458.             previousSelectedValues = [];
  4459.  
  4460.         if (!valueAllowUnset) {
  4461.             if (multiple) {
  4462.                 previousSelectedValues = ko.utils.arrayMap(selectedOptions(), ko.selectExtensions.readValue);
  4463.             } else if (element.selectedIndex >= 0) {
  4464.                 previousSelectedValues.push(ko.selectExtensions.readValue(element.options[element.selectedIndex]));
  4465.             }
  4466.         }
  4467.  
  4468.         if (unwrappedArray) {
  4469.             if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
  4470.                 unwrappedArray = [unwrappedArray];
  4471.  
  4472.             // Filter out any entries marked as destroyed
  4473.             filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
  4474.                 return includeDestroyed || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
  4475.             });
  4476.  
  4477.             // If caption is included, add it to the array
  4478.             if (allBindings['has']('optionsCaption')) {
  4479.                 captionValue = ko.utils.unwrapObservable(allBindings.get('optionsCaption'));
  4480.                 // If caption value is null or undefined, don't show a caption
  4481.                 if (captionValue !== null && captionValue !== undefined) {
  4482.                     filteredArray.unshift(captionPlaceholder);
  4483.                 }
  4484.             }
  4485.         } else {
  4486.             // If a falsy value is provided (e.g. null), we'll simply empty the select element
  4487.         }
  4488.  
  4489.         function applyToObject(object, predicate, defaultValue) {
  4490.             var predicateType = typeof predicate;
  4491.             if (predicateType == "function")    // Given a function; run it against the data value
  4492.                 return predicate(object);
  4493.             else if (predicateType == "string") // Given a string; treat it as a property name on the data value
  4494.                 return object[predicate];
  4495.             else                                // Given no optionsText arg; use the data value itself
  4496.                 return defaultValue;
  4497.         }
  4498.  
  4499.         // The following functions can run at two different times:
  4500.         // The first is when the whole array is being updated directly from this binding handler.
  4501.         // The second is when an observable value for a specific array entry is updated.
  4502.         // oldOptions will be empty in the first case, but will be filled with the previously generated option in the second.
  4503.         var itemUpdate = false;
  4504.         function optionForArrayItem(arrayEntry, index, oldOptions) {
  4505.             if (oldOptions.length) {
  4506.                 previousSelectedValues = !valueAllowUnset && oldOptions[0].selected ? [ ko.selectExtensions.readValue(oldOptions[0]) ] : [];
  4507.                 itemUpdate = true;
  4508.             }
  4509.             var option = element.ownerDocument.createElement("option");
  4510.             if (arrayEntry === captionPlaceholder) {
  4511.                 ko.utils.setTextContent(option, allBindings.get('optionsCaption'));
  4512.                 ko.selectExtensions.writeValue(option, undefined);
  4513.             } else {
  4514.                 // Apply a value to the option element
  4515.                 var optionValue = applyToObject(arrayEntry, allBindings.get('optionsValue'), arrayEntry);
  4516.                 ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
  4517.  
  4518.                 // Apply some text to the option element
  4519.                 var optionText = applyToObject(arrayEntry, allBindings.get('optionsText'), optionValue);
  4520.                 ko.utils.setTextContent(option, optionText);
  4521.             }
  4522.             return [option];
  4523.         }
  4524.  
  4525.         // By using a beforeRemove callback, we delay the removal until after new items are added. This fixes a selection
  4526.         // problem in IE<=8 and Firefox. See https://github.com/knockout/knockout/issues/1208
  4527.         arrayToDomNodeChildrenOptions['beforeRemove'] =
  4528.             function (option) {
  4529.                 element.removeChild(option);
  4530.             };
  4531.  
  4532.         function setSelectionCallback(arrayEntry, newOptions) {
  4533.             if (itemUpdate && valueAllowUnset) {
  4534.                 // The model value is authoritative, so make sure its value is the one selected
  4535.                 // There is no need to use dependencyDetection.ignore since setDomNodeChildrenFromArrayMapping does so already.
  4536.                 ko.selectExtensions.writeValue(element, ko.utils.unwrapObservable(allBindings.get('value')), true /* allowUnset */);
  4537.             } else if (previousSelectedValues.length) {
  4538.                 // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
  4539.                 // That's why we first added them without selection. Now it's time to set the selection.
  4540.                 var isSelected = ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[0])) >= 0;
  4541.                 ko.utils.setOptionNodeSelectionState(newOptions[0], isSelected);
  4542.  
  4543.                 // If this option was changed from being selected during a single-item update, notify the change
  4544.                 if (itemUpdate && !isSelected) {
  4545.                     ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
  4546.                 }
  4547.             }
  4548.         }
  4549.  
  4550.         var callback = setSelectionCallback;
  4551.         if (allBindings['has']('optionsAfterRender') && typeof allBindings.get('optionsAfterRender') == "function") {
  4552.             callback = function(arrayEntry, newOptions) {
  4553.                 setSelectionCallback(arrayEntry, newOptions);
  4554.                 ko.dependencyDetection.ignore(allBindings.get('optionsAfterRender'), null, [newOptions[0], arrayEntry !== captionPlaceholder ? arrayEntry : undefined]);
  4555.             }
  4556.         }
  4557.  
  4558.         ko.utils.setDomNodeChildrenFromArrayMapping(element, filteredArray, optionForArrayItem, arrayToDomNodeChildrenOptions, callback);
  4559.  
  4560.         ko.dependencyDetection.ignore(function () {
  4561.             if (valueAllowUnset) {
  4562.                 // The model value is authoritative, so make sure its value is the one selected
  4563.                 ko.selectExtensions.writeValue(element, ko.utils.unwrapObservable(allBindings.get('value')), true /* allowUnset */);
  4564.             } else {
  4565.                 // Determine if the selection has changed as a result of updating the options list
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement