ko/fx/src/main/resources/org/apidesign/bck2brwsr/kofx/knockout-2.2.1.js
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 26 Jun 2013 20:11:13 +0200
branchclassloader
changeset 1232 17ca7fe5c486
parent 1230 ko/fx/src/main/resources/org/apidesign/html/kofx/knockout-2.2.1.js@466c30fd9cb0
permissions -rw-r--r--
ko-fx tests are passing now
     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     dependentObservable.valueHasMutated = function() {
  1308         _hasBeenEvaluated = false;
  1309         evaluateImmediate();
  1310     };
  1311 
  1312     ko.subscribable.call(dependentObservable);
  1313     ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
  1314 
  1315     ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
  1316     ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
  1317     ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
  1318     ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
  1319 
  1320     // Evaluate, unless deferEvaluation is true
  1321     if (options['deferEvaluation'] !== true)
  1322         evaluateImmediate();
  1323 
  1324     // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values.
  1325     // But skip if isActive is false (there will never be any dependencies to dispose).
  1326     // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
  1327     // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
  1328     if (disposeWhenNodeIsRemoved && isActive()) {
  1329         dispose = function() {
  1330             ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
  1331             disposeAllSubscriptionsToDependencies();
  1332         };
  1333         ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
  1334         var existingDisposeWhenFunction = disposeWhen;
  1335         disposeWhen = function () {
  1336             return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
  1337         }
  1338     }
  1339 
  1340     return dependentObservable;
  1341 };
  1342 
  1343 ko.isComputed = function(instance) {
  1344     return ko.hasPrototype(instance, ko.dependentObservable);
  1345 };
  1346 
  1347 var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
  1348 ko.dependentObservable[protoProp] = ko.observable;
  1349 
  1350 ko.dependentObservable['fn'] = {};
  1351 ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
  1352 
  1353 ko.exportSymbol('dependentObservable', ko.dependentObservable);
  1354 ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
  1355 ko.exportSymbol('isComputed', ko.isComputed);
  1356 
  1357 (function() {
  1358     var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
  1359 
  1360     ko.toJS = function(rootObject) {
  1361         if (arguments.length == 0)
  1362             throw new Error("When calling ko.toJS, pass the object you want to convert.");
  1363 
  1364         // We just unwrap everything at every level in the object graph
  1365         return mapJsObjectGraph(rootObject, function(valueToMap) {
  1366             // Loop because an observable's value might in turn be another observable wrapper
  1367             for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
  1368                 valueToMap = valueToMap();
  1369             return valueToMap;
  1370         });
  1371     };
  1372 
  1373     ko.toJSON = function(rootObject, replacer, space) {     // replacer and space are optional
  1374         var plainJavaScriptObject = ko.toJS(rootObject);
  1375         return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
  1376     };
  1377 
  1378     function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
  1379         visitedObjects = visitedObjects || new objectLookup();
  1380 
  1381         rootObject = mapInputCallback(rootObject);
  1382         var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
  1383         if (!canHaveProperties)
  1384             return rootObject;
  1385 
  1386         var outputProperties = rootObject instanceof Array ? [] : {};
  1387         visitedObjects.save(rootObject, outputProperties);
  1388 
  1389         visitPropertiesOrArrayEntries(rootObject, function(indexer) {
  1390             var propertyValue = mapInputCallback(rootObject[indexer]);
  1391 
  1392             switch (typeof propertyValue) {
  1393                 case "boolean":
  1394                 case "number":
  1395                 case "string":
  1396                 case "function":
  1397                     outputProperties[indexer] = propertyValue;
  1398                     break;
  1399                 case "object":
  1400                 case "undefined":
  1401                     var previouslyMappedValue = visitedObjects.get(propertyValue);
  1402                     outputProperties[indexer] = (previouslyMappedValue !== undefined)
  1403                         ? previouslyMappedValue
  1404                         : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
  1405                     break;
  1406             }
  1407         });
  1408 
  1409         return outputProperties;
  1410     }
  1411 
  1412     function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
  1413         if (rootObject instanceof Array) {
  1414             for (var i = 0; i < rootObject.length; i++)
  1415                 visitorCallback(i);
  1416 
  1417             // For arrays, also respect toJSON property for custom mappings (fixes #278)
  1418             if (typeof rootObject['toJSON'] == 'function')
  1419                 visitorCallback('toJSON');
  1420         } else {
  1421             for (var propertyName in rootObject)
  1422                 visitorCallback(propertyName);
  1423         }
  1424     };
  1425 
  1426     function objectLookup() {
  1427         var keys = [];
  1428         var values = [];
  1429         this.save = function(key, value) {
  1430             var existingIndex = ko.utils.arrayIndexOf(keys, key);
  1431             if (existingIndex >= 0)
  1432                 values[existingIndex] = value;
  1433             else {
  1434                 keys.push(key);
  1435                 values.push(value);
  1436             }
  1437         };
  1438         this.get = function(key) {
  1439             var existingIndex = ko.utils.arrayIndexOf(keys, key);
  1440             return (existingIndex >= 0) ? values[existingIndex] : undefined;
  1441         };
  1442     };
  1443 })();
  1444 
  1445 ko.exportSymbol('toJS', ko.toJS);
  1446 ko.exportSymbol('toJSON', ko.toJSON);
  1447 (function () {
  1448     var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
  1449 
  1450     // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
  1451     // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
  1452     // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
  1453     ko.selectExtensions = {
  1454         readValue : function(element) {
  1455             switch (ko.utils.tagNameLower(element)) {
  1456                 case 'option':
  1457                     if (element[hasDomDataExpandoProperty] === true)
  1458                         return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
  1459                     return ko.utils.ieVersion <= 7
  1460                         ? (element.getAttributeNode('value').specified ? element.value : element.text)
  1461                         : element.value;
  1462                 case 'select':
  1463                     return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
  1464                 default:
  1465                     return element.value;
  1466             }
  1467         },
  1468 
  1469         writeValue: function(element, value) {
  1470             switch (ko.utils.tagNameLower(element)) {
  1471                 case 'option':
  1472                     switch(typeof value) {
  1473                         case "string":
  1474                             ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
  1475                             if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
  1476                                 delete element[hasDomDataExpandoProperty];
  1477                             }
  1478                             element.value = value;
  1479                             break;
  1480                         default:
  1481                             // Store arbitrary object using DomData
  1482                             ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
  1483                             element[hasDomDataExpandoProperty] = true;
  1484 
  1485                             // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
  1486                             element.value = typeof value === "number" ? value : "";
  1487                             break;
  1488                     }
  1489                     break;
  1490                 case 'select':
  1491                     for (var i = element.options.length - 1; i >= 0; i--) {
  1492                         if (ko.selectExtensions.readValue(element.options[i]) == value) {
  1493                             element.selectedIndex = i;
  1494                             break;
  1495                         }
  1496                     }
  1497                     break;
  1498                 default:
  1499                     if ((value === null) || (value === undefined))
  1500                         value = "";
  1501                     element.value = value;
  1502                     break;
  1503             }
  1504         }
  1505     };
  1506 })();
  1507 
  1508 ko.exportSymbol('selectExtensions', ko.selectExtensions);
  1509 ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
  1510 ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
  1511 ko.expressionRewriting = (function () {
  1512     var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
  1513     var javaScriptReservedWords = ["true", "false"];
  1514 
  1515     // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
  1516     // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
  1517     var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
  1518 
  1519     function restoreTokens(string, tokens) {
  1520         var prevValue = null;
  1521         while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
  1522             prevValue = string;
  1523             string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
  1524                 return tokens[tokenIndex];
  1525             });
  1526         }
  1527         return string;
  1528     }
  1529 
  1530     function getWriteableValue(expression) {
  1531         if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
  1532             return false;
  1533         var match = expression.match(javaScriptAssignmentTarget);
  1534         return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
  1535     }
  1536 
  1537     function ensureQuoted(key) {
  1538         var trimmedKey = ko.utils.stringTrim(key);
  1539         switch (trimmedKey.length && trimmedKey.charAt(0)) {
  1540             case "'":
  1541             case '"':
  1542                 return key;
  1543             default:
  1544                 return "'" + trimmedKey + "'";
  1545         }
  1546     }
  1547 
  1548     return {
  1549         bindingRewriteValidators: [],
  1550 
  1551         parseObjectLiteral: function(objectLiteralString) {
  1552             // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
  1553             // that is sufficient just to split an object literal string into a set of top-level key-value pairs
  1554 
  1555             var str = ko.utils.stringTrim(objectLiteralString);
  1556             if (str.length < 3)
  1557                 return [];
  1558             if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
  1559                 str = str.substring(1, str.length - 1);
  1560 
  1561             // Pull out any string literals and regex literals
  1562             var tokens = [];
  1563             var tokenStart = null, tokenEndChar;
  1564             for (var position = 0; position < str.length; position++) {
  1565                 var c = str.charAt(position);
  1566                 if (tokenStart === null) {
  1567                     switch (c) {
  1568                         case '"':
  1569                         case "'":
  1570                         case "/":
  1571                             tokenStart = position;
  1572                             tokenEndChar = c;
  1573                             break;
  1574                     }
  1575                 } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
  1576                     var token = str.substring(tokenStart, position + 1);
  1577                     tokens.push(token);
  1578                     var replacement = "@ko_token_" + (tokens.length - 1) + "@";
  1579                     str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
  1580                     position -= (token.length - replacement.length);
  1581                     tokenStart = null;
  1582                 }
  1583             }
  1584 
  1585             // Next pull out balanced paren, brace, and bracket blocks
  1586             tokenStart = null;
  1587             tokenEndChar = null;
  1588             var tokenDepth = 0, tokenStartChar = null;
  1589             for (var position = 0; position < str.length; position++) {
  1590                 var c = str.charAt(position);
  1591                 if (tokenStart === null) {
  1592                     switch (c) {
  1593                         case "{": tokenStart = position; tokenStartChar = c;
  1594                                   tokenEndChar = "}";
  1595                                   break;
  1596                         case "(": tokenStart = position; tokenStartChar = c;
  1597                                   tokenEndChar = ")";
  1598                                   break;
  1599                         case "[": tokenStart = position; tokenStartChar = c;
  1600                                   tokenEndChar = "]";
  1601                                   break;
  1602                     }
  1603                 }
  1604 
  1605                 if (c === tokenStartChar)
  1606                     tokenDepth++;
  1607                 else if (c === tokenEndChar) {
  1608                     tokenDepth--;
  1609                     if (tokenDepth === 0) {
  1610                         var token = str.substring(tokenStart, position + 1);
  1611                         tokens.push(token);
  1612                         var replacement = "@ko_token_" + (tokens.length - 1) + "@";
  1613                         str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
  1614                         position -= (token.length - replacement.length);
  1615                         tokenStart = null;
  1616                     }
  1617                 }
  1618             }
  1619 
  1620             // Now we can safely split on commas to get the key/value pairs
  1621             var result = [];
  1622             var keyValuePairs = str.split(",");
  1623             for (var i = 0, j = keyValuePairs.length; i < j; i++) {
  1624                 var pair = keyValuePairs[i];
  1625                 var colonPos = pair.indexOf(":");
  1626                 if ((colonPos > 0) && (colonPos < pair.length - 1)) {
  1627                     var key = pair.substring(0, colonPos);
  1628                     var value = pair.substring(colonPos + 1);
  1629                     result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
  1630                 } else {
  1631                     result.push({ 'unknown': restoreTokens(pair, tokens) });
  1632                 }
  1633             }
  1634             return result;
  1635         },
  1636 
  1637         preProcessBindings: function (objectLiteralStringOrKeyValueArray) {
  1638             var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
  1639                 ? ko.expressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
  1640                 : objectLiteralStringOrKeyValueArray;
  1641             var resultStrings = [], propertyAccessorResultStrings = [];
  1642 
  1643             var keyValueEntry;
  1644             for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
  1645                 if (resultStrings.length > 0)
  1646                     resultStrings.push(",");
  1647 
  1648                 if (keyValueEntry['key']) {
  1649                     var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
  1650                     resultStrings.push(quotedKey);
  1651                     resultStrings.push(":");
  1652                     resultStrings.push(val);
  1653 
  1654                     if (val = getWriteableValue(ko.utils.stringTrim(val))) {
  1655                         if (propertyAccessorResultStrings.length > 0)
  1656                             propertyAccessorResultStrings.push(", ");
  1657                         propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
  1658                     }
  1659                 } else if (keyValueEntry['unknown']) {
  1660                     resultStrings.push(keyValueEntry['unknown']);
  1661                 }
  1662             }
  1663 
  1664             var combinedResult = resultStrings.join("");
  1665             if (propertyAccessorResultStrings.length > 0) {
  1666                 var allPropertyAccessors = propertyAccessorResultStrings.join("");
  1667                 combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
  1668             }
  1669 
  1670             return combinedResult;
  1671         },
  1672 
  1673         keyValueArrayContainsKey: function(keyValueArray, key) {
  1674             for (var i = 0; i < keyValueArray.length; i++)
  1675                 if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
  1676                     return true;
  1677             return false;
  1678         },
  1679 
  1680         // Internal, private KO utility for updating model properties from within bindings
  1681         // property:            If the property being updated is (or might be) an observable, pass it here
  1682         //                      If it turns out to be a writable observable, it will be written to directly
  1683         // allBindingsAccessor: All bindings in the current execution context.
  1684         //                      This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
  1685         // key:                 The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
  1686         // value:               The value to be written
  1687         // checkIfDifferent:    If true, and if the property being written is a writable observable, the value will only be written if
  1688         //                      it is !== existing value on that writable observable
  1689         writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
  1690             if (!property || !ko.isWriteableObservable(property)) {
  1691                 var propWriters = allBindingsAccessor()['_ko_property_writers'];
  1692                 if (propWriters && propWriters[key])
  1693                     propWriters[key](value);
  1694             } else if (!checkIfDifferent || property.peek() !== value) {
  1695                 property(value);
  1696             }
  1697         }
  1698     };
  1699 })();
  1700 
  1701 ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
  1702 ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
  1703 ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
  1704 ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
  1705 
  1706 // For backward compatibility, define the following aliases. (Previously, these function names were misleading because
  1707 // they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
  1708 ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
  1709 ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);(function() {
  1710     // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
  1711     // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
  1712     // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
  1713     // of that virtual hierarchy
  1714     //
  1715     // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
  1716     // without having to scatter special cases all over the binding and templating code.
  1717 
  1718     // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
  1719     // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
  1720     // So, use node.text where available, and node.nodeValue elsewhere
  1721     var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
  1722 
  1723     var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*-->$/ : /^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/;
  1724     var endCommentRegex =   commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
  1725     var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
  1726 
  1727     function isStartComment(node) {
  1728         return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
  1729     }
  1730 
  1731     function isEndComment(node) {
  1732         return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
  1733     }
  1734 
  1735     function getVirtualChildren(startComment, allowUnbalanced) {
  1736         var currentNode = startComment;
  1737         var depth = 1;
  1738         var children = [];
  1739         while (currentNode = currentNode.nextSibling) {
  1740             if (isEndComment(currentNode)) {
  1741                 depth--;
  1742                 if (depth === 0)
  1743                     return children;
  1744             }
  1745 
  1746             children.push(currentNode);
  1747 
  1748             if (isStartComment(currentNode))
  1749                 depth++;
  1750         }
  1751         if (!allowUnbalanced)
  1752             throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
  1753         return null;
  1754     }
  1755 
  1756     function getMatchingEndComment(startComment, allowUnbalanced) {
  1757         var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
  1758         if (allVirtualChildren) {
  1759             if (allVirtualChildren.length > 0)
  1760                 return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
  1761             return startComment.nextSibling;
  1762         } else
  1763             return null; // Must have no matching end comment, and allowUnbalanced is true
  1764     }
  1765 
  1766     function getUnbalancedChildTags(node) {
  1767         // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
  1768         //       from <div>OK</div><!-- /ko --><!-- /ko -->,             returns: <!-- /ko --><!-- /ko -->
  1769         var childNode = node.firstChild, captureRemaining = null;
  1770         if (childNode) {
  1771             do {
  1772                 if (captureRemaining)                   // We already hit an unbalanced node and are now just scooping up all subsequent nodes
  1773                     captureRemaining.push(childNode);
  1774                 else if (isStartComment(childNode)) {
  1775                     var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
  1776                     if (matchingEndComment)             // It's a balanced tag, so skip immediately to the end of this virtual set
  1777                         childNode = matchingEndComment;
  1778                     else
  1779                         captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
  1780                 } else if (isEndComment(childNode)) {
  1781                     captureRemaining = [childNode];     // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
  1782                 }
  1783             } while (childNode = childNode.nextSibling);
  1784         }
  1785         return captureRemaining;
  1786     }
  1787 
  1788     ko.virtualElements = {
  1789         allowedBindings: {},
  1790 
  1791         childNodes: function(node) {
  1792             return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
  1793         },
  1794 
  1795         emptyNode: function(node) {
  1796             if (!isStartComment(node))
  1797                 ko.utils.emptyDomNode(node);
  1798             else {
  1799                 var virtualChildren = ko.virtualElements.childNodes(node);
  1800                 for (var i = 0, j = virtualChildren.length; i < j; i++)
  1801                     ko.removeNode(virtualChildren[i]);
  1802             }
  1803         },
  1804 
  1805         setDomNodeChildren: function(node, childNodes) {
  1806             if (!isStartComment(node))
  1807                 ko.utils.setDomNodeChildren(node, childNodes);
  1808             else {
  1809                 ko.virtualElements.emptyNode(node);
  1810                 var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
  1811                 for (var i = 0, j = childNodes.length; i < j; i++)
  1812                     endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
  1813             }
  1814         },
  1815 
  1816         prepend: function(containerNode, nodeToPrepend) {
  1817             if (!isStartComment(containerNode)) {
  1818                 if (containerNode.firstChild)
  1819                     containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
  1820                 else
  1821                     containerNode.appendChild(nodeToPrepend);
  1822             } else {
  1823                 // Start comments must always have a parent and at least one following sibling (the end comment)
  1824                 containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
  1825             }
  1826         },
  1827 
  1828         insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
  1829             if (!insertAfterNode) {
  1830                 ko.virtualElements.prepend(containerNode, nodeToInsert);
  1831             } else if (!isStartComment(containerNode)) {
  1832                 // Insert after insertion point
  1833                 if (insertAfterNode.nextSibling)
  1834                     containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
  1835                 else
  1836                     containerNode.appendChild(nodeToInsert);
  1837             } else {
  1838                 // Children of start comments must always have a parent and at least one following sibling (the end comment)
  1839                 containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
  1840             }
  1841         },
  1842 
  1843         firstChild: function(node) {
  1844             if (!isStartComment(node))
  1845                 return node.firstChild;
  1846             if (!node.nextSibling || isEndComment(node.nextSibling))
  1847                 return null;
  1848             return node.nextSibling;
  1849         },
  1850 
  1851         nextSibling: function(node) {
  1852             if (isStartComment(node))
  1853                 node = getMatchingEndComment(node);
  1854             if (node.nextSibling && isEndComment(node.nextSibling))
  1855                 return null;
  1856             return node.nextSibling;
  1857         },
  1858 
  1859         virtualNodeBindingValue: function(node) {
  1860             var regexMatch = isStartComment(node);
  1861             return regexMatch ? regexMatch[1] : null;
  1862         },
  1863 
  1864         normaliseVirtualElementDomStructure: function(elementVerified) {
  1865             // Workaround for https://github.com/SteveSanderson/knockout/issues/155
  1866             // (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
  1867             // that are direct descendants of <ul> into the preceding <li>)
  1868             if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
  1869                 return;
  1870 
  1871             // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
  1872             // must be intended to appear *after* that child, so move them there.
  1873             var childNode = elementVerified.firstChild;
  1874             if (childNode) {
  1875                 do {
  1876                     if (childNode.nodeType === 1) {
  1877                         var unbalancedTags = getUnbalancedChildTags(childNode);
  1878                         if (unbalancedTags) {
  1879                             // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
  1880                             var nodeToInsertBefore = childNode.nextSibling;
  1881                             for (var i = 0; i < unbalancedTags.length; i++) {
  1882                                 if (nodeToInsertBefore)
  1883                                     elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
  1884                                 else
  1885                                     elementVerified.appendChild(unbalancedTags[i]);
  1886                             }
  1887                         }
  1888                     }
  1889                 } while (childNode = childNode.nextSibling);
  1890             }
  1891         }
  1892     };
  1893 })();
  1894 ko.exportSymbol('virtualElements', ko.virtualElements);
  1895 ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
  1896 ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
  1897 //ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild);     // firstChild is not minified
  1898 ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
  1899 //ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling);   // nextSibling is not minified
  1900 ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
  1901 ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
  1902 (function() {
  1903     var defaultBindingAttributeName = "data-bind";
  1904 
  1905     ko.bindingProvider = function() {
  1906         this.bindingCache = {};
  1907     };
  1908 
  1909     ko.utils.extend(ko.bindingProvider.prototype, {
  1910         'nodeHasBindings': function(node) {
  1911             switch (node.nodeType) {
  1912                 case 1: return node.getAttribute(defaultBindingAttributeName) != null;   // Element
  1913                 case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
  1914                 default: return false;
  1915             }
  1916         },
  1917 
  1918         'getBindings': function(node, bindingContext) {
  1919             var bindingsString = this['getBindingsString'](node, bindingContext);
  1920             return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
  1921         },
  1922 
  1923         // The following function is only used internally by this default provider.
  1924         // It's not part of the interface definition for a general binding provider.
  1925         'getBindingsString': function(node, bindingContext) {
  1926             switch (node.nodeType) {
  1927                 case 1: return node.getAttribute(defaultBindingAttributeName);   // Element
  1928                 case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
  1929                 default: return null;
  1930             }
  1931         },
  1932 
  1933         // The following function is only used internally by this default provider.
  1934         // It's not part of the interface definition for a general binding provider.
  1935         'parseBindingsString': function(bindingsString, bindingContext, node) {
  1936             try {
  1937                 var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
  1938                 return bindingFunction(bindingContext, node);
  1939             } catch (ex) {
  1940                 throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
  1941             }
  1942         }
  1943     });
  1944 
  1945     ko.bindingProvider['instance'] = new ko.bindingProvider();
  1946 
  1947     function createBindingsStringEvaluatorViaCache(bindingsString, cache) {
  1948         var cacheKey = bindingsString;
  1949         return cache[cacheKey]
  1950             || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString));
  1951     }
  1952 
  1953     function createBindingsStringEvaluator(bindingsString) {
  1954         // Build the source for a function that evaluates "expression"
  1955         // For each scope variable, add an extra level of "with" nesting
  1956         // Example result: with(sc1) { with(sc0) { return (expression) } }
  1957         var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString),
  1958             functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
  1959         return new Function("$context", "$element", functionBody);
  1960     }
  1961 })();
  1962 
  1963 ko.exportSymbol('bindingProvider', ko.bindingProvider);
  1964 (function () {
  1965     ko.bindingHandlers = {};
  1966 
  1967     ko.bindingContext = function(dataItem, parentBindingContext, dataItemAlias) {
  1968         if (parentBindingContext) {
  1969             ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
  1970             this['$parentContext'] = parentBindingContext;
  1971             this['$parent'] = parentBindingContext['$data'];
  1972             this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
  1973             this['$parents'].unshift(this['$parent']);
  1974         } else {
  1975             this['$parents'] = [];
  1976             this['$root'] = dataItem;
  1977             // Export 'ko' in the binding context so it will be available in bindings and templates
  1978             // even if 'ko' isn't exported as a global, such as when using an AMD loader.
  1979             // See https://github.com/SteveSanderson/knockout/issues/490
  1980             this['ko'] = ko;
  1981         }
  1982         this['$data'] = dataItem;
  1983         if (dataItemAlias)
  1984             this[dataItemAlias] = dataItem;
  1985     }
  1986     ko.bindingContext.prototype['createChildContext'] = function (dataItem, dataItemAlias) {
  1987         return new ko.bindingContext(dataItem, this, dataItemAlias);
  1988     };
  1989     ko.bindingContext.prototype['extend'] = function(properties) {
  1990         var clone = ko.utils.extend(new ko.bindingContext(), this);
  1991         return ko.utils.extend(clone, properties);
  1992     };
  1993 
  1994     function validateThatBindingIsAllowedForVirtualElements(bindingName) {
  1995         var validator = ko.virtualElements.allowedBindings[bindingName];
  1996         if (!validator)
  1997             throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
  1998     }
  1999 
  2000     function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
  2001         var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
  2002         while (currentChild = nextInQueue) {
  2003             // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
  2004             nextInQueue = ko.virtualElements.nextSibling(currentChild);
  2005             applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
  2006         }
  2007     }
  2008 
  2009     function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
  2010         var shouldBindDescendants = true;
  2011 
  2012         // Perf optimisation: Apply bindings only if...
  2013         // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
  2014         //     Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
  2015         // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
  2016         var isElement = (nodeVerified.nodeType === 1);
  2017         if (isElement) // Workaround IE <= 8 HTML parsing weirdness
  2018             ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
  2019 
  2020         var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement)             // Case (1)
  2021                                || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified);       // Case (2)
  2022         if (shouldApplyBindings)
  2023             shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
  2024 
  2025         if (shouldBindDescendants) {
  2026             // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
  2027             //  * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
  2028             //    hence bindingContextsMayDifferFromDomParentElement is false
  2029             //  * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
  2030             //    skip over any number of intermediate virtual elements, any of which might define a custom binding context,
  2031             //    hence bindingContextsMayDifferFromDomParentElement is true
  2032             applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
  2033         }
  2034     }
  2035 
  2036     function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
  2037         // Need to be sure that inits are only run once, and updates never run until all the inits have been run
  2038         var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
  2039 
  2040         // Each time the dependentObservable is evaluated (after data changes),
  2041         // the binding attribute is reparsed so that it can pick out the correct
  2042         // model properties in the context of the changed data.
  2043         // DOM event callbacks need to be able to access this changed data,
  2044         // so we need a single parsedBindings variable (shared by all callbacks
  2045         // associated with this node's bindings) that all the closures can access.
  2046         var parsedBindings;
  2047         function makeValueAccessor(bindingKey) {
  2048             return function () { return parsedBindings[bindingKey] }
  2049         }
  2050         function parsedBindingsAccessor() {
  2051             return parsedBindings;
  2052         }
  2053 
  2054         var bindingHandlerThatControlsDescendantBindings;
  2055         ko.dependentObservable(
  2056             function () {
  2057                 // Ensure we have a nonnull binding context to work with
  2058                 var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
  2059                     ? viewModelOrBindingContext
  2060                     : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
  2061                 var viewModel = bindingContextInstance['$data'];
  2062 
  2063                 // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
  2064                 // we can easily recover it just by scanning up the node's ancestors in the DOM
  2065                 // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
  2066                 if (bindingContextMayDifferFromDomParentElement)
  2067                     ko.storedBindingContextForNode(node, bindingContextInstance);
  2068 
  2069                 // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
  2070                 var evaluatedBindings = (typeof bindings == "function") ? bindings(bindingContextInstance, node) : bindings;
  2071                 parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
  2072 
  2073                 if (parsedBindings) {
  2074                     // First run all the inits, so bindings can register for notification on changes
  2075                     if (initPhase === 0) {
  2076                         initPhase = 1;
  2077                         for (var bindingKey in parsedBindings) {
  2078                             var binding = ko.bindingHandlers[bindingKey];
  2079                             if (binding && node.nodeType === 8)
  2080                                 validateThatBindingIsAllowedForVirtualElements(bindingKey);
  2081 
  2082                             if (binding && typeof binding["init"] == "function") {
  2083                                 var handlerInitFn = binding["init"];
  2084                                 var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
  2085 
  2086                                 // If this binding handler claims to control descendant bindings, make a note of this
  2087                                 if (initResult && initResult['controlsDescendantBindings']) {
  2088                                     if (bindingHandlerThatControlsDescendantBindings !== undefined)
  2089                                         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.");
  2090                                     bindingHandlerThatControlsDescendantBindings = bindingKey;
  2091                                 }
  2092                             }
  2093                         }
  2094                         initPhase = 2;
  2095                     }
  2096 
  2097                     // ... then run all the updates, which might trigger changes even on the first evaluation
  2098                     if (initPhase === 2) {
  2099                         for (var bindingKey in parsedBindings) {
  2100                             var binding = ko.bindingHandlers[bindingKey];
  2101                             if (binding && typeof binding["update"] == "function") {
  2102                                 var handlerUpdateFn = binding["update"];
  2103                                 handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
  2104                             }
  2105                         }
  2106                     }
  2107                 }
  2108             },
  2109             null,
  2110             { disposeWhenNodeIsRemoved : node }
  2111         );
  2112 
  2113         return {
  2114             shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
  2115         };
  2116     };
  2117 
  2118     var storedBindingContextDomDataKey = "__ko_bindingContext__";
  2119     ko.storedBindingContextForNode = function (node, bindingContext) {
  2120         if (arguments.length == 2)
  2121             ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
  2122         else
  2123             return ko.utils.domData.get(node, storedBindingContextDomDataKey);
  2124     }
  2125 
  2126     ko.applyBindingsToNode = function (node, bindings, viewModel) {
  2127         if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
  2128             ko.virtualElements.normaliseVirtualElementDomStructure(node);
  2129         return applyBindingsToNodeInternal(node, bindings, viewModel, true);
  2130     };
  2131 
  2132     ko.applyBindingsToDescendants = function(viewModel, rootNode) {
  2133         if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
  2134             applyBindingsToDescendantsInternal(viewModel, rootNode, true);
  2135     };
  2136 
  2137     ko.applyBindings = function (viewModel, rootNode) {
  2138         if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
  2139             throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
  2140         rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
  2141 
  2142         applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
  2143     };
  2144 
  2145     // Retrieving binding context from arbitrary nodes
  2146     ko.contextFor = function(node) {
  2147         // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
  2148         switch (node.nodeType) {
  2149             case 1:
  2150             case 8:
  2151                 var context = ko.storedBindingContextForNode(node);
  2152                 if (context) return context;
  2153                 if (node.parentNode) return ko.contextFor(node.parentNode);
  2154                 break;
  2155         }
  2156         return undefined;
  2157     };
  2158     ko.dataFor = function(node) {
  2159         var context = ko.contextFor(node);
  2160         return context ? context['$data'] : undefined;
  2161     };
  2162 
  2163     ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
  2164     ko.exportSymbol('applyBindings', ko.applyBindings);
  2165     ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
  2166     ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
  2167     ko.exportSymbol('contextFor', ko.contextFor);
  2168     ko.exportSymbol('dataFor', ko.dataFor);
  2169 })();
  2170 var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
  2171 ko.bindingHandlers['attr'] = {
  2172     'update': function(element, valueAccessor, allBindingsAccessor) {
  2173         var value = ko.utils.unwrapObservable(valueAccessor()) || {};
  2174         for (var attrName in value) {
  2175             if (typeof attrName == "string") {
  2176                 var attrValue = ko.utils.unwrapObservable(value[attrName]);
  2177 
  2178                 // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
  2179                 // when someProp is a "no value"-like value (strictly null, false, or undefined)
  2180                 // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
  2181                 var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
  2182                 if (toRemove)
  2183                     element.removeAttribute(attrName);
  2184 
  2185                 // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
  2186                 // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
  2187                 // but instead of figuring out the mode, we'll just set the attribute through the Javascript
  2188                 // property for IE <= 8.
  2189                 if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
  2190                     attrName = attrHtmlToJavascriptMap[attrName];
  2191                     if (toRemove)
  2192                         element.removeAttribute(attrName);
  2193                     else
  2194                         element[attrName] = attrValue;
  2195                 } else if (!toRemove) {
  2196                     try {
  2197                         element.setAttribute(attrName, attrValue.toString());
  2198                     } catch (err) {
  2199                         // ignore for now
  2200                         if (console) {
  2201                             console.log("Can't set attribute " + attrName + " to " + attrValue + " error: " + err);
  2202                         }
  2203                     }
  2204                 }
  2205 
  2206                 // Treat "name" specially - although you can think of it as an attribute, it also needs
  2207                 // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
  2208                 // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
  2209                 // entirely, and there's no strong reason to allow for such casing in HTML.
  2210                 if (attrName === "name") {
  2211                     ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
  2212                 }
  2213             }
  2214         }
  2215     }
  2216 };
  2217 ko.bindingHandlers['checked'] = {
  2218     'init': function (element, valueAccessor, allBindingsAccessor) {
  2219         var updateHandler = function() {
  2220             var valueToWrite;
  2221             if (element.type == "checkbox") {
  2222                 valueToWrite = element.checked;
  2223             } else if ((element.type == "radio") && (element.checked)) {
  2224                 valueToWrite = element.value;
  2225             } else {
  2226                 return; // "checked" binding only responds to checkboxes and selected radio buttons
  2227             }
  2228 
  2229             var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
  2230             if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
  2231                 // For checkboxes bound to an array, we add/remove the checkbox value to that array
  2232                 // This works for both observable and non-observable arrays
  2233                 var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
  2234                 if (element.checked && (existingEntryIndex < 0))
  2235                     modelValue.push(element.value);
  2236                 else if ((!element.checked) && (existingEntryIndex >= 0))
  2237                     modelValue.splice(existingEntryIndex, 1);
  2238             } else {
  2239                 ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
  2240             }
  2241         };
  2242         ko.utils.registerEventHandler(element, "click", updateHandler);
  2243 
  2244         // IE 6 won't allow radio buttons to be selected unless they have a name
  2245         if ((element.type == "radio") && !element.name)
  2246             ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
  2247     },
  2248     'update': function (element, valueAccessor) {
  2249         var value = ko.utils.unwrapObservable(valueAccessor());
  2250 
  2251         if (element.type == "checkbox") {
  2252             if (value instanceof Array) {
  2253                 // When bound to an array, the checkbox being checked represents its value being present in that array
  2254                 element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
  2255             } else {
  2256                 // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
  2257                 element.checked = value;
  2258             }
  2259         } else if (element.type == "radio") {
  2260             element.checked = (element.value == value);
  2261         }
  2262     }
  2263 };
  2264 var classesWrittenByBindingKey = '__ko__cssValue';
  2265 ko.bindingHandlers['css'] = {
  2266     'update': function (element, valueAccessor) {
  2267         var value = ko.utils.unwrapObservable(valueAccessor());
  2268         if (typeof value == "object") {
  2269             for (var className in value) {
  2270                 var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
  2271                 ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
  2272             }
  2273         } else {
  2274             value = String(value || ''); // Make sure we don't try to store or set a non-string value
  2275             ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
  2276             element[classesWrittenByBindingKey] = value;
  2277             ko.utils.toggleDomNodeCssClass(element, value, true);
  2278         }
  2279     }
  2280 };
  2281 ko.bindingHandlers['enable'] = {
  2282     'update': function (element, valueAccessor) {
  2283         var value = ko.utils.unwrapObservable(valueAccessor());
  2284         if (value && element.disabled)
  2285             element.removeAttribute("disabled");
  2286         else if ((!value) && (!element.disabled))
  2287             element.disabled = true;
  2288     }
  2289 };
  2290 
  2291 ko.bindingHandlers['disable'] = {
  2292     'update': function (element, valueAccessor) {
  2293         ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
  2294     }
  2295 };
  2296 // For certain common events (currently just 'click'), allow a simplified data-binding syntax
  2297 // e.g. click:handler instead of the usual full-length event:{click:handler}
  2298 function makeEventHandlerShortcut(eventName) {
  2299     ko.bindingHandlers[eventName] = {
  2300         'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
  2301             var newValueAccessor = function () {
  2302                 var result = {};
  2303                 result[eventName] = valueAccessor();
  2304                 return result;
  2305             };
  2306             return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
  2307         }
  2308     }
  2309 }
  2310 
  2311 ko.bindingHandlers['event'] = {
  2312     'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
  2313         var eventsToHandle = valueAccessor() || {};
  2314         for(var eventNameOutsideClosure in eventsToHandle) {
  2315             (function() {
  2316                 var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
  2317                 if (typeof eventName == "string") {
  2318                     ko.utils.registerEventHandler(element, eventName, function (event) {
  2319                         var handlerReturnValue;
  2320                         var handlerFunction = valueAccessor()[eventName];
  2321                         if (!handlerFunction)
  2322                             return;
  2323                         var allBindings = allBindingsAccessor();
  2324 
  2325                         try {
  2326                             // Take all the event args, and prefix with the viewmodel
  2327                             var argsForHandler = ko.utils.makeArray(arguments);
  2328                             argsForHandler.unshift(viewModel);
  2329                             handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
  2330                         } finally {
  2331                             if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
  2332                                 if (event.preventDefault)
  2333                                     event.preventDefault();
  2334                                 else
  2335                                     event.returnValue = false;
  2336                             }
  2337                         }
  2338 
  2339                         var bubble = allBindings[eventName + 'Bubble'] !== false;
  2340                         if (!bubble) {
  2341                             event.cancelBubble = true;
  2342                             if (event.stopPropagation)
  2343                                 event.stopPropagation();
  2344                         }
  2345                     });
  2346                 }
  2347             })();
  2348         }
  2349     }
  2350 };
  2351 // "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
  2352 // "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
  2353 ko.bindingHandlers['foreach'] = {
  2354     makeTemplateValueAccessor: function(valueAccessor) {
  2355         return function() {
  2356             var modelValue = valueAccessor(),
  2357                 unwrappedValue = ko.utils.peekObservable(modelValue);    // Unwrap without setting a dependency here
  2358 
  2359             // If unwrappedValue is the array, pass in the wrapped value on its own
  2360             // The value will be unwrapped and tracked within the template binding
  2361             // (See https://github.com/SteveSanderson/knockout/issues/523)
  2362             if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
  2363                 return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
  2364 
  2365             // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
  2366             ko.utils.unwrapObservable(modelValue);
  2367             return {
  2368                 'foreach': unwrappedValue['data'],
  2369                 'as': unwrappedValue['as'],
  2370                 'includeDestroyed': unwrappedValue['includeDestroyed'],
  2371                 'afterAdd': unwrappedValue['afterAdd'],
  2372                 'beforeRemove': unwrappedValue['beforeRemove'],
  2373                 'afterRender': unwrappedValue['afterRender'],
  2374                 'beforeMove': unwrappedValue['beforeMove'],
  2375                 'afterMove': unwrappedValue['afterMove'],
  2376                 'templateEngine': ko.nativeTemplateEngine.instance
  2377             };
  2378         };
  2379     },
  2380     'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2381         return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
  2382     },
  2383     'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2384         return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
  2385     }
  2386 };
  2387 ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
  2388 ko.virtualElements.allowedBindings['foreach'] = true;
  2389 var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
  2390 ko.bindingHandlers['hasfocus'] = {
  2391     'init': function(element, valueAccessor, allBindingsAccessor) {
  2392         var handleElementFocusChange = function(isFocused) {
  2393             // Where possible, ignore which event was raised and determine focus state using activeElement,
  2394             // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
  2395             // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
  2396             // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
  2397             // from calling 'blur()' on the element when it loses focus.
  2398             // Discussion at https://github.com/SteveSanderson/knockout/pull/352
  2399             element[hasfocusUpdatingProperty] = true;
  2400             var ownerDoc = element.ownerDocument;
  2401             if ("activeElement" in ownerDoc) {
  2402                 isFocused = (ownerDoc.activeElement === element);
  2403             }
  2404             var modelValue = valueAccessor();
  2405             ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true);
  2406             element[hasfocusUpdatingProperty] = false;
  2407         };
  2408         var handleElementFocusIn = handleElementFocusChange.bind(null, true);
  2409         var handleElementFocusOut = handleElementFocusChange.bind(null, false);
  2410 
  2411         ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
  2412         ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
  2413         ko.utils.registerEventHandler(element, "blur",  handleElementFocusOut);
  2414         ko.utils.registerEventHandler(element, "focusout",  handleElementFocusOut); // For IE
  2415     },
  2416     'update': function(element, valueAccessor) {
  2417         var value = ko.utils.unwrapObservable(valueAccessor());
  2418         if (!element[hasfocusUpdatingProperty]) {
  2419             value ? element.focus() : element.blur();
  2420             ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
  2421         }
  2422     }
  2423 };
  2424 ko.bindingHandlers['html'] = {
  2425     'init': function() {
  2426         // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
  2427         return { 'controlsDescendantBindings': true };
  2428     },
  2429     'update': function (element, valueAccessor) {
  2430         // setHtml will unwrap the value if needed
  2431         ko.utils.setHtml(element, valueAccessor());
  2432     }
  2433 };
  2434 var withIfDomDataKey = '__ko_withIfBindingData';
  2435 // Makes a binding like with or if
  2436 function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
  2437     ko.bindingHandlers[bindingKey] = {
  2438         'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2439             ko.utils.domData.set(element, withIfDomDataKey, {});
  2440             return { 'controlsDescendantBindings': true };
  2441         },
  2442         'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2443             var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
  2444                 dataValue = ko.utils.unwrapObservable(valueAccessor()),
  2445                 shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
  2446                 isFirstRender = !withIfData.savedNodes,
  2447                 needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
  2448 
  2449             if (needsRefresh) {
  2450                 if (isFirstRender) {
  2451                     withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
  2452                 }
  2453 
  2454                 if (shouldDisplay) {
  2455                     if (!isFirstRender) {
  2456                         ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
  2457                     }
  2458                     ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
  2459                 } else {
  2460                     ko.virtualElements.emptyNode(element);
  2461                 }
  2462 
  2463                 withIfData.didDisplayOnLastUpdate = shouldDisplay;
  2464             }
  2465         }
  2466     };
  2467     ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
  2468     ko.virtualElements.allowedBindings[bindingKey] = true;
  2469 }
  2470 
  2471 // Construct the actual binding handlers
  2472 makeWithIfBinding('if');
  2473 makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
  2474 makeWithIfBinding('with', true /* isWith */, false /* isNot */,
  2475     function(bindingContext, dataValue) {
  2476         return bindingContext['createChildContext'](dataValue);
  2477     }
  2478 );
  2479 function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
  2480     if (preferModelValue) {
  2481         if (modelValue !== ko.selectExtensions.readValue(element))
  2482             ko.selectExtensions.writeValue(element, modelValue);
  2483     }
  2484 
  2485     // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
  2486     // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
  2487     // change the model value to match the dropdown.
  2488     if (modelValue !== ko.selectExtensions.readValue(element))
  2489         ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
  2490 };
  2491 
  2492 ko.bindingHandlers['options'] = {
  2493     'update': function (element, valueAccessor, allBindingsAccessor) {
  2494         if (ko.utils.tagNameLower(element) !== "select")
  2495             throw new Error("options binding applies only to SELECT elements");
  2496 
  2497         var selectWasPreviouslyEmpty = element.length == 0;
  2498         var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
  2499             return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
  2500         }), function (node) {
  2501             return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
  2502         });
  2503         var previousScrollTop = element.scrollTop;
  2504 
  2505         var value = ko.utils.unwrapObservable(valueAccessor());
  2506         var selectedValue = element.value;
  2507 
  2508         // Remove all existing <option>s.
  2509         // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
  2510         while (element.length > 0) {
  2511             ko.cleanNode(element.options[0]);
  2512             element.remove(0);
  2513         }
  2514 
  2515         if (value) {
  2516             var allBindings = allBindingsAccessor(),
  2517                 includeDestroyed = allBindings['optionsIncludeDestroyed'];
  2518 
  2519             if (typeof value.length != "number")
  2520                 value = [value];
  2521             if (allBindings['optionsCaption']) {
  2522                 var option = document.createElement("option");
  2523                 ko.utils.setHtml(option, allBindings['optionsCaption']);
  2524                 ko.selectExtensions.writeValue(option, undefined);
  2525                 element.appendChild(option);
  2526             }
  2527 
  2528             for (var i = 0, j = value.length; i < j; i++) {
  2529                 // Skip destroyed items
  2530                 var arrayEntry = value[i];
  2531                 if (arrayEntry && arrayEntry['_destroy'] && !includeDestroyed)
  2532                     continue;
  2533 
  2534                 var option = document.createElement("option");
  2535 
  2536                 function applyToObject(object, predicate, defaultValue) {
  2537                     var predicateType = typeof predicate;
  2538                     if (predicateType == "function")    // Given a function; run it against the data value
  2539                         return predicate(object);
  2540                     else if (predicateType == "string") // Given a string; treat it as a property name on the data value
  2541                         return object[predicate];
  2542                     else                                // Given no optionsText arg; use the data value itself
  2543                         return defaultValue;
  2544                 }
  2545 
  2546                 // Apply a value to the option element
  2547                 var optionValue = applyToObject(arrayEntry, allBindings['optionsValue'], arrayEntry);
  2548                 ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
  2549 
  2550                 // Apply some text to the option element
  2551                 var optionText = applyToObject(arrayEntry, allBindings['optionsText'], optionValue);
  2552                 ko.utils.setTextContent(option, optionText);
  2553 
  2554                 element.appendChild(option);
  2555             }
  2556 
  2557             // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
  2558             // That's why we first added them without selection. Now it's time to set the selection.
  2559             var newOptions = element.getElementsByTagName("option");
  2560             var countSelectionsRetained = 0;
  2561             for (var i = 0, j = newOptions.length; i < j; i++) {
  2562                 if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
  2563                     ko.utils.setOptionNodeSelectionState(newOptions[i], true);
  2564                     countSelectionsRetained++;
  2565                 }
  2566             }
  2567 
  2568             element.scrollTop = previousScrollTop;
  2569 
  2570             if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
  2571                 // Ensure consistency between model value and selected option.
  2572                 // If the dropdown is being populated for the first time here (or was otherwise previously empty),
  2573                 // the dropdown selection state is meaningless, so we preserve the model value.
  2574                 ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.peekObservable(allBindings['value']), /* preferModelValue */ true);
  2575             }
  2576 
  2577             // Workaround for IE9 bug
  2578             ko.utils.ensureSelectElementIsRenderedCorrectly(element);
  2579         }
  2580     }
  2581 };
  2582 ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
  2583 ko.bindingHandlers['selectedOptions'] = {
  2584     'init': function (element, valueAccessor, allBindingsAccessor) {
  2585         ko.utils.registerEventHandler(element, "change", function () {
  2586             var value = valueAccessor(), valueToWrite = [];
  2587             ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
  2588                 if (node.selected)
  2589                     valueToWrite.push(ko.selectExtensions.readValue(node));
  2590             });
  2591             ko.expressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
  2592         });
  2593     },
  2594     'update': function (element, valueAccessor) {
  2595         if (ko.utils.tagNameLower(element) != "select")
  2596             throw new Error("values binding applies only to SELECT elements");
  2597 
  2598         var newValue = ko.utils.unwrapObservable(valueAccessor());
  2599         if (newValue && typeof newValue.length == "number") {
  2600             ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
  2601                 var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
  2602                 ko.utils.setOptionNodeSelectionState(node, isSelected);
  2603             });
  2604         }
  2605     }
  2606 };
  2607 ko.bindingHandlers['style'] = {
  2608     'update': function (element, valueAccessor) {
  2609         var value = ko.utils.unwrapObservable(valueAccessor() || {});
  2610         for (var styleName in value) {
  2611             if (typeof styleName == "string") {
  2612                 var styleValue = ko.utils.unwrapObservable(value[styleName]);
  2613                 element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
  2614             }
  2615         }
  2616     }
  2617 };
  2618 ko.bindingHandlers['submit'] = {
  2619     'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
  2620         if (typeof valueAccessor() != "function")
  2621             throw new Error("The value for a submit binding must be a function");
  2622         ko.utils.registerEventHandler(element, "submit", function (event) {
  2623             var handlerReturnValue;
  2624             var value = valueAccessor();
  2625             try { handlerReturnValue = value.call(viewModel, element); }
  2626             finally {
  2627                 if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
  2628                     if (event.preventDefault)
  2629                         event.preventDefault();
  2630                     else
  2631                         event.returnValue = false;
  2632                 }
  2633             }
  2634         });
  2635     }
  2636 };
  2637 ko.bindingHandlers['text'] = {
  2638     'update': function (element, valueAccessor) {
  2639         ko.utils.setTextContent(element, valueAccessor());
  2640     }
  2641 };
  2642 ko.virtualElements.allowedBindings['text'] = true;
  2643 ko.bindingHandlers['uniqueName'] = {
  2644     'init': function (element, valueAccessor) {
  2645         if (valueAccessor()) {
  2646             var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
  2647             ko.utils.setElementName(element, name);
  2648         }
  2649     }
  2650 };
  2651 ko.bindingHandlers['uniqueName'].currentIndex = 0;
  2652 ko.bindingHandlers['value'] = {
  2653     'init': function (element, valueAccessor, allBindingsAccessor) {
  2654         // Always catch "change" event; possibly other events too if asked
  2655         var eventsToCatch = ["change"];
  2656         var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
  2657         var propertyChangedFired = false;
  2658         if (requestedEventsToCatch) {
  2659             if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
  2660                 requestedEventsToCatch = [requestedEventsToCatch];
  2661             ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
  2662             eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
  2663         }
  2664 
  2665         var valueUpdateHandler = function() {
  2666             propertyChangedFired = false;
  2667             var modelValue = valueAccessor();
  2668             var elementValue = ko.selectExtensions.readValue(element);
  2669             ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
  2670         }
  2671 
  2672         // Workaround for https://github.com/SteveSanderson/knockout/issues/122
  2673         // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
  2674         var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
  2675                                        && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
  2676         if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
  2677             ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
  2678             ko.utils.registerEventHandler(element, "blur", function() {
  2679                 if (propertyChangedFired) {
  2680                     valueUpdateHandler();
  2681                 }
  2682             });
  2683         }
  2684 
  2685         ko.utils.arrayForEach(eventsToCatch, function(eventName) {
  2686             // The syntax "after<eventname>" means "run the handler asynchronously after the event"
  2687             // This is useful, for example, to catch "keydown" events after the browser has updated the control
  2688             // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
  2689             var handler = valueUpdateHandler;
  2690             if (ko.utils.stringStartsWith(eventName, "after")) {
  2691                 handler = function() { setTimeout(valueUpdateHandler, 0) };
  2692                 eventName = eventName.substring("after".length);
  2693             }
  2694             ko.utils.registerEventHandler(element, eventName, handler);
  2695         });
  2696     },
  2697     'update': function (element, valueAccessor) {
  2698         var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
  2699         var newValue = ko.utils.unwrapObservable(valueAccessor());
  2700         var elementValue = ko.selectExtensions.readValue(element);
  2701         var valueHasChanged = (newValue != elementValue);
  2702 
  2703         // 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).
  2704         // 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.
  2705         if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
  2706             valueHasChanged = true;
  2707 
  2708         if (valueHasChanged) {
  2709             var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
  2710             applyValueAction();
  2711 
  2712             // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
  2713             // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
  2714             // to apply the value as well.
  2715             var alsoApplyAsynchronously = valueIsSelectOption;
  2716             if (alsoApplyAsynchronously)
  2717                 setTimeout(applyValueAction, 0);
  2718         }
  2719 
  2720         // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
  2721         // because you're not allowed to have a model value that disagrees with a visible UI selection.
  2722         if (valueIsSelectOption && (element.length > 0))
  2723             ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
  2724     }
  2725 };
  2726 ko.bindingHandlers['visible'] = {
  2727     'update': function (element, valueAccessor) {
  2728         var value = ko.utils.unwrapObservable(valueAccessor());
  2729         var isCurrentlyVisible = !(element.style.display == "none");
  2730         if (value && !isCurrentlyVisible)
  2731             element.style.display = "";
  2732         else if ((!value) && isCurrentlyVisible)
  2733             element.style.display = "none";
  2734     }
  2735 };
  2736 // 'click' is just a shorthand for the usual full-length event:{click:handler}
  2737 makeEventHandlerShortcut('click');
  2738 // If you want to make a custom template engine,
  2739 //
  2740 // [1] Inherit from this class (like ko.nativeTemplateEngine does)
  2741 // [2] Override 'renderTemplateSource', supplying a function with this signature:
  2742 //
  2743 //        function (templateSource, bindingContext, options) {
  2744 //            // - templateSource.text() is the text of the template you should render
  2745 //            // - bindingContext.$data is the data you should pass into the template
  2746 //            //   - you might also want to make bindingContext.$parent, bindingContext.$parents,
  2747 //            //     and bindingContext.$root available in the template too
  2748 //            // - options gives you access to any other properties set on "data-bind: { template: options }"
  2749 //            //
  2750 //            // Return value: an array of DOM nodes
  2751 //        }
  2752 //
  2753 // [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
  2754 //
  2755 //        function (script) {
  2756 //            // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
  2757 //            //               For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
  2758 //        }
  2759 //
  2760 //     This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
  2761 //     If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
  2762 //     and then you don't need to override 'createJavaScriptEvaluatorBlock'.
  2763 
  2764 ko.templateEngine = function () { };
  2765 
  2766 ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
  2767     throw new Error("Override renderTemplateSource");
  2768 };
  2769 
  2770 ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
  2771     throw new Error("Override createJavaScriptEvaluatorBlock");
  2772 };
  2773 
  2774 ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
  2775     // Named template
  2776     if (typeof template == "string") {
  2777         templateDocument = templateDocument || document;
  2778         var elem = templateDocument.getElementById(template);
  2779         if (!elem)
  2780             throw new Error("Cannot find template with ID " + template);
  2781         return new ko.templateSources.domElement(elem);
  2782     } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
  2783         // Anonymous template
  2784         return new ko.templateSources.anonymousTemplate(template);
  2785     } else
  2786         throw new Error("Unknown template type: " + template);
  2787 };
  2788 
  2789 ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
  2790     var templateSource = this['makeTemplateSource'](template, templateDocument);
  2791     return this['renderTemplateSource'](templateSource, bindingContext, options);
  2792 };
  2793 
  2794 ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
  2795     // Skip rewriting if requested
  2796     if (this['allowTemplateRewriting'] === false)
  2797         return true;
  2798     return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
  2799 };
  2800 
  2801 ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
  2802     var templateSource = this['makeTemplateSource'](template, templateDocument);
  2803     var rewritten = rewriterCallback(templateSource['text']());
  2804     templateSource['text'](rewritten);
  2805     templateSource['data']("isRewritten", true);
  2806 };
  2807 
  2808 ko.exportSymbol('templateEngine', ko.templateEngine);
  2809 
  2810 ko.templateRewriting = (function () {
  2811     var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
  2812     var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
  2813 
  2814     function validateDataBindValuesForRewriting(keyValueArray) {
  2815         var allValidators = ko.expressionRewriting.bindingRewriteValidators;
  2816         for (var i = 0; i < keyValueArray.length; i++) {
  2817             var key = keyValueArray[i]['key'];
  2818             if (allValidators.hasOwnProperty(key)) {
  2819                 var validator = allValidators[key];
  2820 
  2821                 if (typeof validator === "function") {
  2822                     var possibleErrorMessage = validator(keyValueArray[i]['value']);
  2823                     if (possibleErrorMessage)
  2824                         throw new Error(possibleErrorMessage);
  2825                 } else if (!validator) {
  2826                     throw new Error("This template engine does not support the '" + key + "' binding within its templates");
  2827                 }
  2828             }
  2829         }
  2830     }
  2831 
  2832     function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
  2833         var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
  2834         validateDataBindValuesForRewriting(dataBindKeyValueArray);
  2835         var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray);
  2836 
  2837         // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
  2838         // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
  2839         // extra indirection.
  2840         var applyBindingsToNextSiblingScript =
  2841             "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()})";
  2842         return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
  2843     }
  2844 
  2845     return {
  2846         ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
  2847             if (!templateEngine['isTemplateRewritten'](template, templateDocument))
  2848                 templateEngine['rewriteTemplate'](template, function (htmlString) {
  2849                     return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
  2850                 }, templateDocument);
  2851         },
  2852 
  2853         memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
  2854             return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
  2855                 return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
  2856             }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
  2857                 return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
  2858             });
  2859         },
  2860 
  2861         applyMemoizedBindingsToNextSibling: function (bindings) {
  2862             return ko.memoization.memoize(function (domNode, bindingContext) {
  2863                 if (domNode.nextSibling)
  2864                     ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
  2865             });
  2866         }
  2867     }
  2868 })();
  2869 
  2870 
  2871 // Exported only because it has to be referenced by string lookup from within rewritten template
  2872 ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
  2873 (function() {
  2874     // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
  2875     // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
  2876     //
  2877     // Two are provided by default:
  2878     //  1. ko.templateSources.domElement       - reads/writes the text content of an arbitrary DOM element
  2879     //  2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
  2880     //                                           without reading/writing the actual element text content, since it will be overwritten
  2881     //                                           with the rendered template output.
  2882     // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
  2883     // Template sources need to have the following functions:
  2884     //   text() 			- returns the template text from your storage location
  2885     //   text(value)		- writes the supplied template text to your storage location
  2886     //   data(key)			- reads values stored using data(key, value) - see below
  2887     //   data(key, value)	- associates "value" with this template and the key "key". Is used to store information like "isRewritten".
  2888     //
  2889     // Optionally, template sources can also have the following functions:
  2890     //   nodes()            - returns a DOM element containing the nodes of this template, where available
  2891     //   nodes(value)       - writes the given DOM element to your storage location
  2892     // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
  2893     // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
  2894     //
  2895     // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
  2896     // using and overriding "makeTemplateSource" to return an instance of your custom template source.
  2897 
  2898     ko.templateSources = {};
  2899 
  2900     // ---- ko.templateSources.domElement -----
  2901 
  2902     ko.templateSources.domElement = function(element) {
  2903         this.domElement = element;
  2904     }
  2905 
  2906     ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
  2907         var tagNameLower = ko.utils.tagNameLower(this.domElement),
  2908             elemContentsProperty = tagNameLower === "script" ? "text"
  2909                                  : tagNameLower === "textarea" ? "value"
  2910                                  : "innerHTML";
  2911 
  2912         if (arguments.length == 0) {
  2913             return this.domElement[elemContentsProperty];
  2914         } else {
  2915             var valueToWrite = arguments[0];
  2916             if (elemContentsProperty === "innerHTML")
  2917                 ko.utils.setHtml(this.domElement, valueToWrite);
  2918             else
  2919                 this.domElement[elemContentsProperty] = valueToWrite;
  2920         }
  2921     };
  2922 
  2923     ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
  2924         if (arguments.length === 1) {
  2925             return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
  2926         } else {
  2927             ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
  2928         }
  2929     };
  2930 
  2931     // ---- ko.templateSources.anonymousTemplate -----
  2932     // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
  2933     // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
  2934     // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
  2935 
  2936     var anonymousTemplatesDomDataKey = "__ko_anon_template__";
  2937     ko.templateSources.anonymousTemplate = function(element) {
  2938         this.domElement = element;
  2939     }
  2940     ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
  2941     ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
  2942         if (arguments.length == 0) {
  2943             var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
  2944             if (templateData.textData === undefined && templateData.containerData)
  2945                 templateData.textData = templateData.containerData.innerHTML;
  2946             return templateData.textData;
  2947         } else {
  2948             var valueToWrite = arguments[0];
  2949             ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
  2950         }
  2951     };
  2952     ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
  2953         if (arguments.length == 0) {
  2954             var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
  2955             return templateData.containerData;
  2956         } else {
  2957             var valueToWrite = arguments[0];
  2958             ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
  2959         }
  2960     };
  2961 
  2962     ko.exportSymbol('templateSources', ko.templateSources);
  2963     ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
  2964     ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
  2965 })();
  2966 (function () {
  2967     var _templateEngine;
  2968     ko.setTemplateEngine = function (templateEngine) {
  2969         if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
  2970             throw new Error("templateEngine must inherit from ko.templateEngine");
  2971         _templateEngine = templateEngine;
  2972     }
  2973 
  2974     function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
  2975         var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
  2976         while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
  2977             nextInQueue = ko.virtualElements.nextSibling(node);
  2978             if (node.nodeType === 1 || node.nodeType === 8)
  2979                 action(node);
  2980         }
  2981     }
  2982 
  2983     function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
  2984         // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
  2985         // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
  2986         // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
  2987         // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
  2988         // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
  2989 
  2990         if (continuousNodeArray.length) {
  2991             var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
  2992 
  2993             // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
  2994             // whereas a regular applyBindings won't introduce new memoized nodes
  2995             invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
  2996                 ko.applyBindings(bindingContext, node);
  2997             });
  2998             invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
  2999                 ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
  3000             });
  3001         }
  3002     }
  3003 
  3004     function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
  3005         return nodeOrNodeArray.nodeType ? nodeOrNodeArray
  3006                                         : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
  3007                                         : null;
  3008     }
  3009 
  3010     function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
  3011         options = options || {};
  3012         var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  3013         var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
  3014         var templateEngineToUse = (options['templateEngine'] || _templateEngine);
  3015         ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
  3016         var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
  3017 
  3018         // Loosely check result is an array of DOM nodes
  3019         if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
  3020             throw new Error("Template engine must return an array of DOM nodes");
  3021 
  3022         var haveAddedNodesToParent = false;
  3023         switch (renderMode) {
  3024             case "replaceChildren":
  3025                 ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
  3026                 haveAddedNodesToParent = true;
  3027                 break;
  3028             case "replaceNode":
  3029                 ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
  3030                 haveAddedNodesToParent = true;
  3031                 break;
  3032             case "ignoreTargetNode": break;
  3033             default:
  3034                 throw new Error("Unknown renderMode: " + renderMode);
  3035         }
  3036 
  3037         if (haveAddedNodesToParent) {
  3038             activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
  3039             if (options['afterRender'])
  3040                 ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
  3041         }
  3042 
  3043         return renderedNodesArray;
  3044     }
  3045 
  3046     ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
  3047         options = options || {};
  3048         if ((options['templateEngine'] || _templateEngine) == undefined)
  3049             throw new Error("Set a template engine before calling renderTemplate");
  3050         renderMode = renderMode || "replaceChildren";
  3051 
  3052         if (targetNodeOrNodeArray) {
  3053             var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  3054 
  3055             var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
  3056             var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
  3057 
  3058             return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
  3059                 function () {
  3060                     // Ensure we've got a proper binding context to work with
  3061                     var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
  3062                         ? dataOrBindingContext
  3063                         : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
  3064 
  3065                     // Support selecting template as a function of the data being rendered
  3066                     var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
  3067 
  3068                     var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
  3069                     if (renderMode == "replaceNode") {
  3070                         targetNodeOrNodeArray = renderedNodesArray;
  3071                         firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  3072                     }
  3073                 },
  3074                 null,
  3075                 { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
  3076             );
  3077         } else {
  3078             // 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
  3079             return ko.memoization.memoize(function (domNode) {
  3080                 ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
  3081             });
  3082         }
  3083     };
  3084 
  3085     ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
  3086         // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
  3087         // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
  3088         var arrayItemContext;
  3089 
  3090         // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
  3091         var executeTemplateForArrayItem = function (arrayValue, index) {
  3092             // Support selecting template as a function of the data being rendered
  3093             arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue), options['as']);
  3094             arrayItemContext['$index'] = index;
  3095             var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
  3096             return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
  3097         }
  3098 
  3099         // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
  3100         var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
  3101             activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
  3102             if (options['afterRender'])
  3103                 options['afterRender'](addedNodesArray, arrayValue);
  3104         };
  3105 
  3106         return ko.dependentObservable(function () {
  3107             var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
  3108             if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
  3109                 unwrappedArray = [unwrappedArray];
  3110 
  3111             // Filter out any entries marked as destroyed
  3112             var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
  3113                 return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
  3114             });
  3115 
  3116             // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
  3117             // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
  3118             ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
  3119 
  3120         }, null, { disposeWhenNodeIsRemoved: targetNode });
  3121     };
  3122 
  3123     var templateComputedDomDataKey = '__ko__templateComputedDomDataKey__';
  3124     function disposeOldComputedAndStoreNewOne(element, newComputed) {
  3125         var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
  3126         if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
  3127             oldComputed.dispose();
  3128         ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
  3129     }
  3130 
  3131     ko.bindingHandlers['template'] = {
  3132         'init': function(element, valueAccessor) {
  3133             // Support anonymous templates
  3134             var bindingValue = ko.utils.unwrapObservable(valueAccessor());
  3135             if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
  3136                 // It's an anonymous template - store the element contents, then clear the element
  3137                 var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
  3138                     container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
  3139                 new ko.templateSources.anonymousTemplate(element)['nodes'](container);
  3140             }
  3141             return { 'controlsDescendantBindings': true };
  3142         },
  3143         'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  3144             var templateName = ko.utils.unwrapObservable(valueAccessor()),
  3145                 options = {},
  3146                 shouldDisplay = true,
  3147                 dataValue,
  3148                 templateComputed = null;
  3149 
  3150             if (typeof templateName != "string") {
  3151                 options = templateName;
  3152                 templateName = options['name'];
  3153 
  3154                 // Support "if"/"ifnot" conditions
  3155                 if ('if' in options)
  3156                     shouldDisplay = ko.utils.unwrapObservable(options['if']);
  3157                 if (shouldDisplay && 'ifnot' in options)
  3158                     shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
  3159 
  3160                 dataValue = ko.utils.unwrapObservable(options['data']);
  3161             }
  3162 
  3163             if ('foreach' in options) {
  3164                 // Render once for each data point (treating data set as empty if shouldDisplay==false)
  3165                 var dataArray = (shouldDisplay && options['foreach']) || [];
  3166                 templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
  3167             } else if (!shouldDisplay) {
  3168                 ko.virtualElements.emptyNode(element);
  3169             } else {
  3170                 // Render once for this single data point (or use the viewModel if no data was provided)
  3171                 var innerBindingContext = ('data' in options) ?
  3172                     bindingContext['createChildContext'](dataValue, options['as']) :  // Given an explitit 'data' value, we create a child binding context for it
  3173                     bindingContext;                                                        // Given no explicit 'data' value, we retain the same binding context
  3174                 templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
  3175             }
  3176 
  3177             // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
  3178             disposeOldComputedAndStoreNewOne(element, templateComputed);
  3179         }
  3180     };
  3181 
  3182     // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
  3183     ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
  3184         var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
  3185 
  3186         if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
  3187             return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
  3188 
  3189         if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
  3190             return null; // Named templates can be rewritten, so return "no error"
  3191         return "This template engine does not support anonymous templates nested within its templates";
  3192     };
  3193 
  3194     ko.virtualElements.allowedBindings['template'] = true;
  3195 })();
  3196 
  3197 ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
  3198 ko.exportSymbol('renderTemplate', ko.renderTemplate);
  3199 
  3200 ko.utils.compareArrays = (function () {
  3201     var statusNotInOld = 'added', statusNotInNew = 'deleted';
  3202 
  3203     // Simple calculation based on Levenshtein distance.
  3204     function compareArrays(oldArray, newArray, dontLimitMoves) {
  3205         oldArray = oldArray || [];
  3206         newArray = newArray || [];
  3207 
  3208         if (oldArray.length <= newArray.length)
  3209             return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, dontLimitMoves);
  3210         else
  3211             return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, dontLimitMoves);
  3212     }
  3213 
  3214     function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, dontLimitMoves) {
  3215         var myMin = Math.min,
  3216             myMax = Math.max,
  3217             editDistanceMatrix = [],
  3218             smlIndex, smlIndexMax = smlArray.length,
  3219             bigIndex, bigIndexMax = bigArray.length,
  3220             compareRange = (bigIndexMax - smlIndexMax) || 1,
  3221             maxDistance = smlIndexMax + bigIndexMax + 1,
  3222             thisRow, lastRow,
  3223             bigIndexMaxForRow, bigIndexMinForRow;
  3224 
  3225         for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
  3226             lastRow = thisRow;
  3227             editDistanceMatrix.push(thisRow = []);
  3228             bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
  3229             bigIndexMinForRow = myMax(0, smlIndex - 1);
  3230             for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
  3231                 if (!bigIndex)
  3232                     thisRow[bigIndex] = smlIndex + 1;
  3233                 else if (!smlIndex)  // Top row - transform empty array into new array via additions
  3234                     thisRow[bigIndex] = bigIndex + 1;
  3235                 else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
  3236                     thisRow[bigIndex] = lastRow[bigIndex - 1];                  // copy value (no edit)
  3237                 else {
  3238                     var northDistance = lastRow[bigIndex] || maxDistance;       // not in big (deletion)
  3239                     var westDistance = thisRow[bigIndex - 1] || maxDistance;    // not in small (addition)
  3240                     thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
  3241                 }
  3242             }
  3243         }
  3244 
  3245         var editScript = [], meMinusOne, notInSml = [], notInBig = [];
  3246         for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
  3247             meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
  3248             if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
  3249                 notInSml.push(editScript[editScript.length] = {     // added
  3250                     'status': statusNotInSml,
  3251                     'value': bigArray[--bigIndex],
  3252                     'index': bigIndex });
  3253             } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
  3254                 notInBig.push(editScript[editScript.length] = {     // deleted
  3255                     'status': statusNotInBig,
  3256                     'value': smlArray[--smlIndex],
  3257                     'index': smlIndex });
  3258             } else {
  3259                 editScript.push({
  3260                     'status': "retained",
  3261                     'value': bigArray[--bigIndex] });
  3262                 --smlIndex;
  3263             }
  3264         }
  3265 
  3266         if (notInSml.length && notInBig.length) {
  3267             // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
  3268             // smlIndexMax keeps the time complexity of this algorithm linear.
  3269             var limitFailedCompares = smlIndexMax * 10, failedCompares,
  3270                 a, d, notInSmlItem, notInBigItem;
  3271             // Go through the items that have been added and deleted and try to find matches between them.
  3272             for (failedCompares = a = 0; (dontLimitMoves || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
  3273                 for (d = 0; notInBigItem = notInBig[d]; d++) {
  3274                     if (notInSmlItem['value'] === notInBigItem['value']) {
  3275                         notInSmlItem['moved'] = notInBigItem['index'];
  3276                         notInBigItem['moved'] = notInSmlItem['index'];
  3277                         notInBig.splice(d,1);       // This item is marked as moved; so remove it from notInBig list
  3278                         failedCompares = d = 0;     // Reset failed compares count because we're checking for consecutive failures
  3279                         break;
  3280                     }
  3281                 }
  3282                 failedCompares += d;
  3283             }
  3284         }
  3285         return editScript.reverse();
  3286     }
  3287 
  3288     return compareArrays;
  3289 })();
  3290 
  3291 ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
  3292 
  3293 (function () {
  3294     // Objective:
  3295     // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
  3296     //   map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
  3297     // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
  3298     //   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
  3299     //   previously mapped - retain those nodes, and just insert/delete other ones
  3300 
  3301     // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
  3302     // You can use this, for example, to activate bindings on those nodes.
  3303 
  3304     function fixUpNodesToBeMovedOrRemoved(contiguousNodeArray) {
  3305         // Before moving, deleting, or replacing a set of nodes that were previously outputted by the "map" function, we have to reconcile
  3306         // them against what is in the DOM right now. It may be that some of the nodes have already been removed from the document,
  3307         // or that new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
  3308         // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
  3309         // So, this function translates the old "map" output array into its best guess of what set of current DOM nodes should be removed.
  3310         //
  3311         // Rules:
  3312         //   [A] Any leading nodes that aren't in the document any more should be ignored
  3313         //       These most likely correspond to memoization nodes that were already removed during binding
  3314         //       See https://github.com/SteveSanderson/knockout/pull/440
  3315         //   [B] We want to output a contiguous series of nodes that are still in the document. So, ignore any nodes that
  3316         //       have already been removed, and include any nodes that have been inserted among the previous collection
  3317 
  3318         // Rule [A]
  3319         while (contiguousNodeArray.length && !ko.utils.domNodeIsAttachedToDocument(contiguousNodeArray[0]))
  3320             contiguousNodeArray.splice(0, 1);
  3321 
  3322         // Rule [B]
  3323         if (contiguousNodeArray.length > 1) {
  3324             // Build up the actual new contiguous node set
  3325             var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
  3326             while (current !== last) {
  3327                 current = current.nextSibling;
  3328                 if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
  3329                     return;
  3330                 newContiguousSet.push(current);
  3331             }
  3332 
  3333             // ... then mutate the input array to match this.
  3334             // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
  3335             Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
  3336         }
  3337         return contiguousNodeArray;
  3338     }
  3339 
  3340     function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
  3341         // Map this array value inside a dependentObservable so we re-map when any dependency changes
  3342         var mappedNodes = [];
  3343         var dependentObservable = ko.dependentObservable(function() {
  3344             var newMappedNodes = mapping(valueToMap, index) || [];
  3345 
  3346             // On subsequent evaluations, just replace the previously-inserted DOM nodes
  3347             if (mappedNodes.length > 0) {
  3348                 ko.utils.replaceDomNodes(fixUpNodesToBeMovedOrRemoved(mappedNodes), newMappedNodes);
  3349                 if (callbackAfterAddingNodes)
  3350                     ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
  3351             }
  3352 
  3353             // Replace the contents of the mappedNodes array, thereby updating the record
  3354             // of which nodes would be deleted if valueToMap was itself later removed
  3355             mappedNodes.splice(0, mappedNodes.length);
  3356             ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
  3357         }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
  3358         return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
  3359     }
  3360 
  3361     var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
  3362 
  3363     ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
  3364         // Compare the provided array against the previous one
  3365         array = array || [];
  3366         options = options || {};
  3367         var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
  3368         var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
  3369         var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
  3370         var editScript = ko.utils.compareArrays(lastArray, array);
  3371 
  3372         // Build the new mapping result
  3373         var newMappingResult = [];
  3374         var lastMappingResultIndex = 0;
  3375         var newMappingResultIndex = 0;
  3376 
  3377         var nodesToDelete = [];
  3378         var itemsToProcess = [];
  3379         var itemsForBeforeRemoveCallbacks = [];
  3380         var itemsForMoveCallbacks = [];
  3381         var itemsForAfterAddCallbacks = [];
  3382         var mapData;
  3383 
  3384         function itemMovedOrRetained(editScriptIndex, oldPosition) {
  3385             mapData = lastMappingResult[oldPosition];
  3386             if (newMappingResultIndex !== oldPosition)
  3387                 itemsForMoveCallbacks[editScriptIndex] = mapData;
  3388             // Since updating the index might change the nodes, do so before calling fixUpNodesToBeMovedOrRemoved
  3389             mapData.indexObservable(newMappingResultIndex++);
  3390             fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes);
  3391             newMappingResult.push(mapData);
  3392             itemsToProcess.push(mapData);
  3393         }
  3394 
  3395         function callCallback(callback, items) {
  3396             if (callback) {
  3397                 for (var i = 0, n = items.length; i < n; i++) {
  3398                     if (items[i]) {
  3399                         ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
  3400                             callback(node, i, items[i].arrayEntry);
  3401                         });
  3402                     }
  3403                 }
  3404             }
  3405         }
  3406 
  3407         for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
  3408             movedIndex = editScriptItem['moved'];
  3409             switch (editScriptItem['status']) {
  3410                 case "deleted":
  3411                     if (movedIndex === undefined) {
  3412                         mapData = lastMappingResult[lastMappingResultIndex];
  3413 
  3414                         // Stop tracking changes to the mapping for these nodes
  3415                         if (mapData.dependentObservable)
  3416                             mapData.dependentObservable.dispose();
  3417 
  3418                         // Queue these nodes for later removal
  3419                         nodesToDelete.push.apply(nodesToDelete, fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes));
  3420                         if (options['beforeRemove']) {
  3421                             itemsForBeforeRemoveCallbacks[i] = mapData;
  3422                             itemsToProcess.push(mapData);
  3423                         }
  3424                     }
  3425                     lastMappingResultIndex++;
  3426                     break;
  3427 
  3428                 case "retained":
  3429                     itemMovedOrRetained(i, lastMappingResultIndex++);
  3430                     break;
  3431 
  3432                 case "added":
  3433                     if (movedIndex !== undefined) {
  3434                         itemMovedOrRetained(i, movedIndex);
  3435                     } else {
  3436                         mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
  3437                         newMappingResult.push(mapData);
  3438                         itemsToProcess.push(mapData);
  3439                         if (!isFirstExecution)
  3440                             itemsForAfterAddCallbacks[i] = mapData;
  3441                     }
  3442                     break;
  3443             }
  3444         }
  3445 
  3446         // Call beforeMove first before any changes have been made to the DOM
  3447         callCallback(options['beforeMove'], itemsForMoveCallbacks);
  3448 
  3449         // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
  3450         ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
  3451 
  3452         // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
  3453         for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
  3454             // Get nodes for newly added items
  3455             if (!mapData.mappedNodes)
  3456                 ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
  3457 
  3458             // Put nodes in the right place if they aren't there already
  3459             for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
  3460                 if (node !== nextNode)
  3461                     ko.virtualElements.insertAfter(domNode, node, lastNode);
  3462             }
  3463 
  3464             // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
  3465             if (!mapData.initialized && callbackAfterAddingNodes) {
  3466                 callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
  3467                 mapData.initialized = true;
  3468             }
  3469         }
  3470 
  3471         // If there's a beforeRemove callback, call it after reordering.
  3472         // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
  3473         // some sort of animation, which is why we first reorder the nodes that will be removed. If the
  3474         // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
  3475         // Perhaps we'll make that change in the future if this scenario becomes more common.
  3476         callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
  3477 
  3478         // Finally call afterMove and afterAdd callbacks
  3479         callCallback(options['afterMove'], itemsForMoveCallbacks);
  3480         callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
  3481 
  3482         // Store a copy of the array items we just considered so we can difference it next time
  3483         ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
  3484     }
  3485 })();
  3486 
  3487 ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
  3488 ko.nativeTemplateEngine = function () {
  3489     this['allowTemplateRewriting'] = false;
  3490 }
  3491 
  3492 ko.nativeTemplateEngine.prototype = new ko.templateEngine();
  3493 ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
  3494     var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
  3495         templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
  3496         templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
  3497 
  3498     if (templateNodes) {
  3499         return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
  3500     } else {
  3501         var templateText = templateSource['text']();
  3502         return ko.utils.parseHtmlFragment(templateText);
  3503     }
  3504 };
  3505 
  3506 ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
  3507 ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
  3508 
  3509 ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
  3510 (function() {
  3511     ko.jqueryTmplTemplateEngine = function () {
  3512         // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
  3513         // doesn't expose a version number, so we have to infer it.
  3514         // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
  3515         // which KO internally refers to as version "2", so older versions are no longer detected.
  3516         var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
  3517             if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
  3518                 return 0;
  3519             // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
  3520             try {
  3521                 if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
  3522                     // Since 1.0.0pre, custom tags should append markup to an array called "__"
  3523                     return 2; // Final version of jquery.tmpl
  3524                 }
  3525             } catch(ex) { /* Apparently not the version we were looking for */ }
  3526 
  3527             return 1; // Any older version that we don't support
  3528         })();
  3529 
  3530         function ensureHasReferencedJQueryTemplates() {
  3531             if (jQueryTmplVersion < 2)
  3532                 throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
  3533         }
  3534 
  3535         function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
  3536             return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
  3537         }
  3538 
  3539         this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
  3540             options = options || {};
  3541             ensureHasReferencedJQueryTemplates();
  3542 
  3543             // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
  3544             var precompiled = templateSource['data']('precompiled');
  3545             if (!precompiled) {
  3546                 var templateText = templateSource['text']() || "";
  3547                 // Wrap in "with($whatever.koBindingContext) { ... }"
  3548                 templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
  3549 
  3550                 precompiled = jQuery['template'](null, templateText);
  3551                 templateSource['data']('precompiled', precompiled);
  3552             }
  3553 
  3554             var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
  3555             var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
  3556 
  3557             var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
  3558             resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
  3559 
  3560             jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
  3561             return resultNodes;
  3562         };
  3563 
  3564         this['createJavaScriptEvaluatorBlock'] = function(script) {
  3565             return "{{ko_code ((function() { return " + script + " })()) }}";
  3566         };
  3567 
  3568         this['addTemplate'] = function(templateName, templateMarkup) {
  3569             document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
  3570         };
  3571 
  3572         if (jQueryTmplVersion > 0) {
  3573             jQuery['tmpl']['tag']['ko_code'] = {
  3574                 open: "__.push($1 || '');"
  3575             };
  3576             jQuery['tmpl']['tag']['ko_with'] = {
  3577                 open: "with($1) {",
  3578                 close: "} "
  3579             };
  3580         }
  3581     };
  3582 
  3583     ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
  3584 
  3585     // Use this one by default *only if jquery.tmpl is referenced*
  3586     var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
  3587     if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
  3588         ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
  3589 
  3590     ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
  3591 })();
  3592 });
  3593 })(window,document,navigator,window["jQuery"]);
  3594 })();