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