javaquery/api/src/main/resources/org/apidesign/bck2brwsr/htmlpage/knockout-2.2.1.js
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 20 Jan 2013 21:00:46 +0100
branchmodel
changeset 494 7f39fe919c07
parent 493 df3513758d20
child 948 35f4f8af296c
permissions -rw-r--r--
Giving dependentObservable method valueHasMuttated(), to allow easy recomputation of the dependentObservable values
     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                     element.setAttribute(attrName, attrValue.toString());
  2197                 }
  2198 
  2199                 // Treat "name" specially - although you can think of it as an attribute, it also needs
  2200                 // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
  2201                 // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
  2202                 // entirely, and there's no strong reason to allow for such casing in HTML.
  2203                 if (attrName === "name") {
  2204                     ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
  2205                 }
  2206             }
  2207         }
  2208     }
  2209 };
  2210 ko.bindingHandlers['checked'] = {
  2211     'init': function (element, valueAccessor, allBindingsAccessor) {
  2212         var updateHandler = function() {
  2213             var valueToWrite;
  2214             if (element.type == "checkbox") {
  2215                 valueToWrite = element.checked;
  2216             } else if ((element.type == "radio") && (element.checked)) {
  2217                 valueToWrite = element.value;
  2218             } else {
  2219                 return; // "checked" binding only responds to checkboxes and selected radio buttons
  2220             }
  2221 
  2222             var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
  2223             if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
  2224                 // For checkboxes bound to an array, we add/remove the checkbox value to that array
  2225                 // This works for both observable and non-observable arrays
  2226                 var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
  2227                 if (element.checked && (existingEntryIndex < 0))
  2228                     modelValue.push(element.value);
  2229                 else if ((!element.checked) && (existingEntryIndex >= 0))
  2230                     modelValue.splice(existingEntryIndex, 1);
  2231             } else {
  2232                 ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
  2233             }
  2234         };
  2235         ko.utils.registerEventHandler(element, "click", updateHandler);
  2236 
  2237         // IE 6 won't allow radio buttons to be selected unless they have a name
  2238         if ((element.type == "radio") && !element.name)
  2239             ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
  2240     },
  2241     'update': function (element, valueAccessor) {
  2242         var value = ko.utils.unwrapObservable(valueAccessor());
  2243 
  2244         if (element.type == "checkbox") {
  2245             if (value instanceof Array) {
  2246                 // When bound to an array, the checkbox being checked represents its value being present in that array
  2247                 element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
  2248             } else {
  2249                 // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
  2250                 element.checked = value;
  2251             }
  2252         } else if (element.type == "radio") {
  2253             element.checked = (element.value == value);
  2254         }
  2255     }
  2256 };
  2257 var classesWrittenByBindingKey = '__ko__cssValue';
  2258 ko.bindingHandlers['css'] = {
  2259     'update': function (element, valueAccessor) {
  2260         var value = ko.utils.unwrapObservable(valueAccessor());
  2261         if (typeof value == "object") {
  2262             for (var className in value) {
  2263                 var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
  2264                 ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
  2265             }
  2266         } else {
  2267             value = String(value || ''); // Make sure we don't try to store or set a non-string value
  2268             ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
  2269             element[classesWrittenByBindingKey] = value;
  2270             ko.utils.toggleDomNodeCssClass(element, value, true);
  2271         }
  2272     }
  2273 };
  2274 ko.bindingHandlers['enable'] = {
  2275     'update': function (element, valueAccessor) {
  2276         var value = ko.utils.unwrapObservable(valueAccessor());
  2277         if (value && element.disabled)
  2278             element.removeAttribute("disabled");
  2279         else if ((!value) && (!element.disabled))
  2280             element.disabled = true;
  2281     }
  2282 };
  2283 
  2284 ko.bindingHandlers['disable'] = {
  2285     'update': function (element, valueAccessor) {
  2286         ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
  2287     }
  2288 };
  2289 // For certain common events (currently just 'click'), allow a simplified data-binding syntax
  2290 // e.g. click:handler instead of the usual full-length event:{click:handler}
  2291 function makeEventHandlerShortcut(eventName) {
  2292     ko.bindingHandlers[eventName] = {
  2293         'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
  2294             var newValueAccessor = function () {
  2295                 var result = {};
  2296                 result[eventName] = valueAccessor();
  2297                 return result;
  2298             };
  2299             return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
  2300         }
  2301     }
  2302 }
  2303 
  2304 ko.bindingHandlers['event'] = {
  2305     'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
  2306         var eventsToHandle = valueAccessor() || {};
  2307         for(var eventNameOutsideClosure in eventsToHandle) {
  2308             (function() {
  2309                 var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
  2310                 if (typeof eventName == "string") {
  2311                     ko.utils.registerEventHandler(element, eventName, function (event) {
  2312                         var handlerReturnValue;
  2313                         var handlerFunction = valueAccessor()[eventName];
  2314                         if (!handlerFunction)
  2315                             return;
  2316                         var allBindings = allBindingsAccessor();
  2317 
  2318                         try {
  2319                             // Take all the event args, and prefix with the viewmodel
  2320                             var argsForHandler = ko.utils.makeArray(arguments);
  2321                             argsForHandler.unshift(viewModel);
  2322                             handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
  2323                         } finally {
  2324                             if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
  2325                                 if (event.preventDefault)
  2326                                     event.preventDefault();
  2327                                 else
  2328                                     event.returnValue = false;
  2329                             }
  2330                         }
  2331 
  2332                         var bubble = allBindings[eventName + 'Bubble'] !== false;
  2333                         if (!bubble) {
  2334                             event.cancelBubble = true;
  2335                             if (event.stopPropagation)
  2336                                 event.stopPropagation();
  2337                         }
  2338                     });
  2339                 }
  2340             })();
  2341         }
  2342     }
  2343 };
  2344 // "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
  2345 // "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
  2346 ko.bindingHandlers['foreach'] = {
  2347     makeTemplateValueAccessor: function(valueAccessor) {
  2348         return function() {
  2349             var modelValue = valueAccessor(),
  2350                 unwrappedValue = ko.utils.peekObservable(modelValue);    // Unwrap without setting a dependency here
  2351 
  2352             // If unwrappedValue is the array, pass in the wrapped value on its own
  2353             // The value will be unwrapped and tracked within the template binding
  2354             // (See https://github.com/SteveSanderson/knockout/issues/523)
  2355             if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
  2356                 return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
  2357 
  2358             // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
  2359             ko.utils.unwrapObservable(modelValue);
  2360             return {
  2361                 'foreach': unwrappedValue['data'],
  2362                 'as': unwrappedValue['as'],
  2363                 'includeDestroyed': unwrappedValue['includeDestroyed'],
  2364                 'afterAdd': unwrappedValue['afterAdd'],
  2365                 'beforeRemove': unwrappedValue['beforeRemove'],
  2366                 'afterRender': unwrappedValue['afterRender'],
  2367                 'beforeMove': unwrappedValue['beforeMove'],
  2368                 'afterMove': unwrappedValue['afterMove'],
  2369                 'templateEngine': ko.nativeTemplateEngine.instance
  2370             };
  2371         };
  2372     },
  2373     'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2374         return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
  2375     },
  2376     'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2377         return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
  2378     }
  2379 };
  2380 ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
  2381 ko.virtualElements.allowedBindings['foreach'] = true;
  2382 var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
  2383 ko.bindingHandlers['hasfocus'] = {
  2384     'init': function(element, valueAccessor, allBindingsAccessor) {
  2385         var handleElementFocusChange = function(isFocused) {
  2386             // Where possible, ignore which event was raised and determine focus state using activeElement,
  2387             // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
  2388             // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
  2389             // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
  2390             // from calling 'blur()' on the element when it loses focus.
  2391             // Discussion at https://github.com/SteveSanderson/knockout/pull/352
  2392             element[hasfocusUpdatingProperty] = true;
  2393             var ownerDoc = element.ownerDocument;
  2394             if ("activeElement" in ownerDoc) {
  2395                 isFocused = (ownerDoc.activeElement === element);
  2396             }
  2397             var modelValue = valueAccessor();
  2398             ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true);
  2399             element[hasfocusUpdatingProperty] = false;
  2400         };
  2401         var handleElementFocusIn = handleElementFocusChange.bind(null, true);
  2402         var handleElementFocusOut = handleElementFocusChange.bind(null, false);
  2403 
  2404         ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
  2405         ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
  2406         ko.utils.registerEventHandler(element, "blur",  handleElementFocusOut);
  2407         ko.utils.registerEventHandler(element, "focusout",  handleElementFocusOut); // For IE
  2408     },
  2409     'update': function(element, valueAccessor) {
  2410         var value = ko.utils.unwrapObservable(valueAccessor());
  2411         if (!element[hasfocusUpdatingProperty]) {
  2412             value ? element.focus() : element.blur();
  2413             ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
  2414         }
  2415     }
  2416 };
  2417 ko.bindingHandlers['html'] = {
  2418     'init': function() {
  2419         // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
  2420         return { 'controlsDescendantBindings': true };
  2421     },
  2422     'update': function (element, valueAccessor) {
  2423         // setHtml will unwrap the value if needed
  2424         ko.utils.setHtml(element, valueAccessor());
  2425     }
  2426 };
  2427 var withIfDomDataKey = '__ko_withIfBindingData';
  2428 // Makes a binding like with or if
  2429 function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
  2430     ko.bindingHandlers[bindingKey] = {
  2431         'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2432             ko.utils.domData.set(element, withIfDomDataKey, {});
  2433             return { 'controlsDescendantBindings': true };
  2434         },
  2435         'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  2436             var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
  2437                 dataValue = ko.utils.unwrapObservable(valueAccessor()),
  2438                 shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
  2439                 isFirstRender = !withIfData.savedNodes,
  2440                 needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
  2441 
  2442             if (needsRefresh) {
  2443                 if (isFirstRender) {
  2444                     withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
  2445                 }
  2446 
  2447                 if (shouldDisplay) {
  2448                     if (!isFirstRender) {
  2449                         ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
  2450                     }
  2451                     ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
  2452                 } else {
  2453                     ko.virtualElements.emptyNode(element);
  2454                 }
  2455 
  2456                 withIfData.didDisplayOnLastUpdate = shouldDisplay;
  2457             }
  2458         }
  2459     };
  2460     ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
  2461     ko.virtualElements.allowedBindings[bindingKey] = true;
  2462 }
  2463 
  2464 // Construct the actual binding handlers
  2465 makeWithIfBinding('if');
  2466 makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
  2467 makeWithIfBinding('with', true /* isWith */, false /* isNot */,
  2468     function(bindingContext, dataValue) {
  2469         return bindingContext['createChildContext'](dataValue);
  2470     }
  2471 );
  2472 function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
  2473     if (preferModelValue) {
  2474         if (modelValue !== ko.selectExtensions.readValue(element))
  2475             ko.selectExtensions.writeValue(element, modelValue);
  2476     }
  2477 
  2478     // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
  2479     // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
  2480     // change the model value to match the dropdown.
  2481     if (modelValue !== ko.selectExtensions.readValue(element))
  2482         ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
  2483 };
  2484 
  2485 ko.bindingHandlers['options'] = {
  2486     'update': function (element, valueAccessor, allBindingsAccessor) {
  2487         if (ko.utils.tagNameLower(element) !== "select")
  2488             throw new Error("options binding applies only to SELECT elements");
  2489 
  2490         var selectWasPreviouslyEmpty = element.length == 0;
  2491         var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
  2492             return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
  2493         }), function (node) {
  2494             return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
  2495         });
  2496         var previousScrollTop = element.scrollTop;
  2497 
  2498         var value = ko.utils.unwrapObservable(valueAccessor());
  2499         var selectedValue = element.value;
  2500 
  2501         // Remove all existing <option>s.
  2502         // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
  2503         while (element.length > 0) {
  2504             ko.cleanNode(element.options[0]);
  2505             element.remove(0);
  2506         }
  2507 
  2508         if (value) {
  2509             var allBindings = allBindingsAccessor(),
  2510                 includeDestroyed = allBindings['optionsIncludeDestroyed'];
  2511 
  2512             if (typeof value.length != "number")
  2513                 value = [value];
  2514             if (allBindings['optionsCaption']) {
  2515                 var option = document.createElement("option");
  2516                 ko.utils.setHtml(option, allBindings['optionsCaption']);
  2517                 ko.selectExtensions.writeValue(option, undefined);
  2518                 element.appendChild(option);
  2519             }
  2520 
  2521             for (var i = 0, j = value.length; i < j; i++) {
  2522                 // Skip destroyed items
  2523                 var arrayEntry = value[i];
  2524                 if (arrayEntry && arrayEntry['_destroy'] && !includeDestroyed)
  2525                     continue;
  2526 
  2527                 var option = document.createElement("option");
  2528 
  2529                 function applyToObject(object, predicate, defaultValue) {
  2530                     var predicateType = typeof predicate;
  2531                     if (predicateType == "function")    // Given a function; run it against the data value
  2532                         return predicate(object);
  2533                     else if (predicateType == "string") // Given a string; treat it as a property name on the data value
  2534                         return object[predicate];
  2535                     else                                // Given no optionsText arg; use the data value itself
  2536                         return defaultValue;
  2537                 }
  2538 
  2539                 // Apply a value to the option element
  2540                 var optionValue = applyToObject(arrayEntry, allBindings['optionsValue'], arrayEntry);
  2541                 ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
  2542 
  2543                 // Apply some text to the option element
  2544                 var optionText = applyToObject(arrayEntry, allBindings['optionsText'], optionValue);
  2545                 ko.utils.setTextContent(option, optionText);
  2546 
  2547                 element.appendChild(option);
  2548             }
  2549 
  2550             // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
  2551             // That's why we first added them without selection. Now it's time to set the selection.
  2552             var newOptions = element.getElementsByTagName("option");
  2553             var countSelectionsRetained = 0;
  2554             for (var i = 0, j = newOptions.length; i < j; i++) {
  2555                 if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
  2556                     ko.utils.setOptionNodeSelectionState(newOptions[i], true);
  2557                     countSelectionsRetained++;
  2558                 }
  2559             }
  2560 
  2561             element.scrollTop = previousScrollTop;
  2562 
  2563             if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
  2564                 // Ensure consistency between model value and selected option.
  2565                 // If the dropdown is being populated for the first time here (or was otherwise previously empty),
  2566                 // the dropdown selection state is meaningless, so we preserve the model value.
  2567                 ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.peekObservable(allBindings['value']), /* preferModelValue */ true);
  2568             }
  2569 
  2570             // Workaround for IE9 bug
  2571             ko.utils.ensureSelectElementIsRenderedCorrectly(element);
  2572         }
  2573     }
  2574 };
  2575 ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
  2576 ko.bindingHandlers['selectedOptions'] = {
  2577     'init': function (element, valueAccessor, allBindingsAccessor) {
  2578         ko.utils.registerEventHandler(element, "change", function () {
  2579             var value = valueAccessor(), valueToWrite = [];
  2580             ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
  2581                 if (node.selected)
  2582                     valueToWrite.push(ko.selectExtensions.readValue(node));
  2583             });
  2584             ko.expressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
  2585         });
  2586     },
  2587     'update': function (element, valueAccessor) {
  2588         if (ko.utils.tagNameLower(element) != "select")
  2589             throw new Error("values binding applies only to SELECT elements");
  2590 
  2591         var newValue = ko.utils.unwrapObservable(valueAccessor());
  2592         if (newValue && typeof newValue.length == "number") {
  2593             ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
  2594                 var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
  2595                 ko.utils.setOptionNodeSelectionState(node, isSelected);
  2596             });
  2597         }
  2598     }
  2599 };
  2600 ko.bindingHandlers['style'] = {
  2601     'update': function (element, valueAccessor) {
  2602         var value = ko.utils.unwrapObservable(valueAccessor() || {});
  2603         for (var styleName in value) {
  2604             if (typeof styleName == "string") {
  2605                 var styleValue = ko.utils.unwrapObservable(value[styleName]);
  2606                 element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
  2607             }
  2608         }
  2609     }
  2610 };
  2611 ko.bindingHandlers['submit'] = {
  2612     'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
  2613         if (typeof valueAccessor() != "function")
  2614             throw new Error("The value for a submit binding must be a function");
  2615         ko.utils.registerEventHandler(element, "submit", function (event) {
  2616             var handlerReturnValue;
  2617             var value = valueAccessor();
  2618             try { handlerReturnValue = value.call(viewModel, element); }
  2619             finally {
  2620                 if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
  2621                     if (event.preventDefault)
  2622                         event.preventDefault();
  2623                     else
  2624                         event.returnValue = false;
  2625                 }
  2626             }
  2627         });
  2628     }
  2629 };
  2630 ko.bindingHandlers['text'] = {
  2631     'update': function (element, valueAccessor) {
  2632         ko.utils.setTextContent(element, valueAccessor());
  2633     }
  2634 };
  2635 ko.virtualElements.allowedBindings['text'] = true;
  2636 ko.bindingHandlers['uniqueName'] = {
  2637     'init': function (element, valueAccessor) {
  2638         if (valueAccessor()) {
  2639             var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
  2640             ko.utils.setElementName(element, name);
  2641         }
  2642     }
  2643 };
  2644 ko.bindingHandlers['uniqueName'].currentIndex = 0;
  2645 ko.bindingHandlers['value'] = {
  2646     'init': function (element, valueAccessor, allBindingsAccessor) {
  2647         // Always catch "change" event; possibly other events too if asked
  2648         var eventsToCatch = ["change"];
  2649         var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
  2650         var propertyChangedFired = false;
  2651         if (requestedEventsToCatch) {
  2652             if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
  2653                 requestedEventsToCatch = [requestedEventsToCatch];
  2654             ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
  2655             eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
  2656         }
  2657 
  2658         var valueUpdateHandler = function() {
  2659             propertyChangedFired = false;
  2660             var modelValue = valueAccessor();
  2661             var elementValue = ko.selectExtensions.readValue(element);
  2662             ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
  2663         }
  2664 
  2665         // Workaround for https://github.com/SteveSanderson/knockout/issues/122
  2666         // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
  2667         var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
  2668                                        && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
  2669         if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
  2670             ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
  2671             ko.utils.registerEventHandler(element, "blur", function() {
  2672                 if (propertyChangedFired) {
  2673                     valueUpdateHandler();
  2674                 }
  2675             });
  2676         }
  2677 
  2678         ko.utils.arrayForEach(eventsToCatch, function(eventName) {
  2679             // The syntax "after<eventname>" means "run the handler asynchronously after the event"
  2680             // This is useful, for example, to catch "keydown" events after the browser has updated the control
  2681             // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
  2682             var handler = valueUpdateHandler;
  2683             if (ko.utils.stringStartsWith(eventName, "after")) {
  2684                 handler = function() { setTimeout(valueUpdateHandler, 0) };
  2685                 eventName = eventName.substring("after".length);
  2686             }
  2687             ko.utils.registerEventHandler(element, eventName, handler);
  2688         });
  2689     },
  2690     'update': function (element, valueAccessor) {
  2691         var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
  2692         var newValue = ko.utils.unwrapObservable(valueAccessor());
  2693         var elementValue = ko.selectExtensions.readValue(element);
  2694         var valueHasChanged = (newValue != elementValue);
  2695 
  2696         // 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).
  2697         // 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.
  2698         if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
  2699             valueHasChanged = true;
  2700 
  2701         if (valueHasChanged) {
  2702             var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
  2703             applyValueAction();
  2704 
  2705             // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
  2706             // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
  2707             // to apply the value as well.
  2708             var alsoApplyAsynchronously = valueIsSelectOption;
  2709             if (alsoApplyAsynchronously)
  2710                 setTimeout(applyValueAction, 0);
  2711         }
  2712 
  2713         // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
  2714         // because you're not allowed to have a model value that disagrees with a visible UI selection.
  2715         if (valueIsSelectOption && (element.length > 0))
  2716             ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
  2717     }
  2718 };
  2719 ko.bindingHandlers['visible'] = {
  2720     'update': function (element, valueAccessor) {
  2721         var value = ko.utils.unwrapObservable(valueAccessor());
  2722         var isCurrentlyVisible = !(element.style.display == "none");
  2723         if (value && !isCurrentlyVisible)
  2724             element.style.display = "";
  2725         else if ((!value) && isCurrentlyVisible)
  2726             element.style.display = "none";
  2727     }
  2728 };
  2729 // 'click' is just a shorthand for the usual full-length event:{click:handler}
  2730 makeEventHandlerShortcut('click');
  2731 // If you want to make a custom template engine,
  2732 //
  2733 // [1] Inherit from this class (like ko.nativeTemplateEngine does)
  2734 // [2] Override 'renderTemplateSource', supplying a function with this signature:
  2735 //
  2736 //        function (templateSource, bindingContext, options) {
  2737 //            // - templateSource.text() is the text of the template you should render
  2738 //            // - bindingContext.$data is the data you should pass into the template
  2739 //            //   - you might also want to make bindingContext.$parent, bindingContext.$parents,
  2740 //            //     and bindingContext.$root available in the template too
  2741 //            // - options gives you access to any other properties set on "data-bind: { template: options }"
  2742 //            //
  2743 //            // Return value: an array of DOM nodes
  2744 //        }
  2745 //
  2746 // [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
  2747 //
  2748 //        function (script) {
  2749 //            // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
  2750 //            //               For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
  2751 //        }
  2752 //
  2753 //     This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
  2754 //     If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
  2755 //     and then you don't need to override 'createJavaScriptEvaluatorBlock'.
  2756 
  2757 ko.templateEngine = function () { };
  2758 
  2759 ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
  2760     throw new Error("Override renderTemplateSource");
  2761 };
  2762 
  2763 ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
  2764     throw new Error("Override createJavaScriptEvaluatorBlock");
  2765 };
  2766 
  2767 ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
  2768     // Named template
  2769     if (typeof template == "string") {
  2770         templateDocument = templateDocument || document;
  2771         var elem = templateDocument.getElementById(template);
  2772         if (!elem)
  2773             throw new Error("Cannot find template with ID " + template);
  2774         return new ko.templateSources.domElement(elem);
  2775     } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
  2776         // Anonymous template
  2777         return new ko.templateSources.anonymousTemplate(template);
  2778     } else
  2779         throw new Error("Unknown template type: " + template);
  2780 };
  2781 
  2782 ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
  2783     var templateSource = this['makeTemplateSource'](template, templateDocument);
  2784     return this['renderTemplateSource'](templateSource, bindingContext, options);
  2785 };
  2786 
  2787 ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
  2788     // Skip rewriting if requested
  2789     if (this['allowTemplateRewriting'] === false)
  2790         return true;
  2791     return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
  2792 };
  2793 
  2794 ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
  2795     var templateSource = this['makeTemplateSource'](template, templateDocument);
  2796     var rewritten = rewriterCallback(templateSource['text']());
  2797     templateSource['text'](rewritten);
  2798     templateSource['data']("isRewritten", true);
  2799 };
  2800 
  2801 ko.exportSymbol('templateEngine', ko.templateEngine);
  2802 
  2803 ko.templateRewriting = (function () {
  2804     var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
  2805     var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
  2806 
  2807     function validateDataBindValuesForRewriting(keyValueArray) {
  2808         var allValidators = ko.expressionRewriting.bindingRewriteValidators;
  2809         for (var i = 0; i < keyValueArray.length; i++) {
  2810             var key = keyValueArray[i]['key'];
  2811             if (allValidators.hasOwnProperty(key)) {
  2812                 var validator = allValidators[key];
  2813 
  2814                 if (typeof validator === "function") {
  2815                     var possibleErrorMessage = validator(keyValueArray[i]['value']);
  2816                     if (possibleErrorMessage)
  2817                         throw new Error(possibleErrorMessage);
  2818                 } else if (!validator) {
  2819                     throw new Error("This template engine does not support the '" + key + "' binding within its templates");
  2820                 }
  2821             }
  2822         }
  2823     }
  2824 
  2825     function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
  2826         var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
  2827         validateDataBindValuesForRewriting(dataBindKeyValueArray);
  2828         var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray);
  2829 
  2830         // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
  2831         // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
  2832         // extra indirection.
  2833         var applyBindingsToNextSiblingScript =
  2834             "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()})";
  2835         return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
  2836     }
  2837 
  2838     return {
  2839         ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
  2840             if (!templateEngine['isTemplateRewritten'](template, templateDocument))
  2841                 templateEngine['rewriteTemplate'](template, function (htmlString) {
  2842                     return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
  2843                 }, templateDocument);
  2844         },
  2845 
  2846         memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
  2847             return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
  2848                 return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
  2849             }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
  2850                 return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
  2851             });
  2852         },
  2853 
  2854         applyMemoizedBindingsToNextSibling: function (bindings) {
  2855             return ko.memoization.memoize(function (domNode, bindingContext) {
  2856                 if (domNode.nextSibling)
  2857                     ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
  2858             });
  2859         }
  2860     }
  2861 })();
  2862 
  2863 
  2864 // Exported only because it has to be referenced by string lookup from within rewritten template
  2865 ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
  2866 (function() {
  2867     // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
  2868     // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
  2869     //
  2870     // Two are provided by default:
  2871     //  1. ko.templateSources.domElement       - reads/writes the text content of an arbitrary DOM element
  2872     //  2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
  2873     //                                           without reading/writing the actual element text content, since it will be overwritten
  2874     //                                           with the rendered template output.
  2875     // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
  2876     // Template sources need to have the following functions:
  2877     //   text() 			- returns the template text from your storage location
  2878     //   text(value)		- writes the supplied template text to your storage location
  2879     //   data(key)			- reads values stored using data(key, value) - see below
  2880     //   data(key, value)	- associates "value" with this template and the key "key". Is used to store information like "isRewritten".
  2881     //
  2882     // Optionally, template sources can also have the following functions:
  2883     //   nodes()            - returns a DOM element containing the nodes of this template, where available
  2884     //   nodes(value)       - writes the given DOM element to your storage location
  2885     // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
  2886     // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
  2887     //
  2888     // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
  2889     // using and overriding "makeTemplateSource" to return an instance of your custom template source.
  2890 
  2891     ko.templateSources = {};
  2892 
  2893     // ---- ko.templateSources.domElement -----
  2894 
  2895     ko.templateSources.domElement = function(element) {
  2896         this.domElement = element;
  2897     }
  2898 
  2899     ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
  2900         var tagNameLower = ko.utils.tagNameLower(this.domElement),
  2901             elemContentsProperty = tagNameLower === "script" ? "text"
  2902                                  : tagNameLower === "textarea" ? "value"
  2903                                  : "innerHTML";
  2904 
  2905         if (arguments.length == 0) {
  2906             return this.domElement[elemContentsProperty];
  2907         } else {
  2908             var valueToWrite = arguments[0];
  2909             if (elemContentsProperty === "innerHTML")
  2910                 ko.utils.setHtml(this.domElement, valueToWrite);
  2911             else
  2912                 this.domElement[elemContentsProperty] = valueToWrite;
  2913         }
  2914     };
  2915 
  2916     ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
  2917         if (arguments.length === 1) {
  2918             return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
  2919         } else {
  2920             ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
  2921         }
  2922     };
  2923 
  2924     // ---- ko.templateSources.anonymousTemplate -----
  2925     // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
  2926     // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
  2927     // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
  2928 
  2929     var anonymousTemplatesDomDataKey = "__ko_anon_template__";
  2930     ko.templateSources.anonymousTemplate = function(element) {
  2931         this.domElement = element;
  2932     }
  2933     ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
  2934     ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
  2935         if (arguments.length == 0) {
  2936             var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
  2937             if (templateData.textData === undefined && templateData.containerData)
  2938                 templateData.textData = templateData.containerData.innerHTML;
  2939             return templateData.textData;
  2940         } else {
  2941             var valueToWrite = arguments[0];
  2942             ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
  2943         }
  2944     };
  2945     ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
  2946         if (arguments.length == 0) {
  2947             var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
  2948             return templateData.containerData;
  2949         } else {
  2950             var valueToWrite = arguments[0];
  2951             ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
  2952         }
  2953     };
  2954 
  2955     ko.exportSymbol('templateSources', ko.templateSources);
  2956     ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
  2957     ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
  2958 })();
  2959 (function () {
  2960     var _templateEngine;
  2961     ko.setTemplateEngine = function (templateEngine) {
  2962         if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
  2963             throw new Error("templateEngine must inherit from ko.templateEngine");
  2964         _templateEngine = templateEngine;
  2965     }
  2966 
  2967     function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
  2968         var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
  2969         while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
  2970             nextInQueue = ko.virtualElements.nextSibling(node);
  2971             if (node.nodeType === 1 || node.nodeType === 8)
  2972                 action(node);
  2973         }
  2974     }
  2975 
  2976     function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
  2977         // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
  2978         // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
  2979         // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
  2980         // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
  2981         // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
  2982 
  2983         if (continuousNodeArray.length) {
  2984             var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
  2985 
  2986             // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
  2987             // whereas a regular applyBindings won't introduce new memoized nodes
  2988             invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
  2989                 ko.applyBindings(bindingContext, node);
  2990             });
  2991             invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
  2992                 ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
  2993             });
  2994         }
  2995     }
  2996 
  2997     function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
  2998         return nodeOrNodeArray.nodeType ? nodeOrNodeArray
  2999                                         : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
  3000                                         : null;
  3001     }
  3002 
  3003     function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
  3004         options = options || {};
  3005         var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  3006         var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
  3007         var templateEngineToUse = (options['templateEngine'] || _templateEngine);
  3008         ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
  3009         var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
  3010 
  3011         // Loosely check result is an array of DOM nodes
  3012         if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
  3013             throw new Error("Template engine must return an array of DOM nodes");
  3014 
  3015         var haveAddedNodesToParent = false;
  3016         switch (renderMode) {
  3017             case "replaceChildren":
  3018                 ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
  3019                 haveAddedNodesToParent = true;
  3020                 break;
  3021             case "replaceNode":
  3022                 ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
  3023                 haveAddedNodesToParent = true;
  3024                 break;
  3025             case "ignoreTargetNode": break;
  3026             default:
  3027                 throw new Error("Unknown renderMode: " + renderMode);
  3028         }
  3029 
  3030         if (haveAddedNodesToParent) {
  3031             activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
  3032             if (options['afterRender'])
  3033                 ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
  3034         }
  3035 
  3036         return renderedNodesArray;
  3037     }
  3038 
  3039     ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
  3040         options = options || {};
  3041         if ((options['templateEngine'] || _templateEngine) == undefined)
  3042             throw new Error("Set a template engine before calling renderTemplate");
  3043         renderMode = renderMode || "replaceChildren";
  3044 
  3045         if (targetNodeOrNodeArray) {
  3046             var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  3047 
  3048             var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
  3049             var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
  3050 
  3051             return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
  3052                 function () {
  3053                     // Ensure we've got a proper binding context to work with
  3054                     var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
  3055                         ? dataOrBindingContext
  3056                         : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
  3057 
  3058                     // Support selecting template as a function of the data being rendered
  3059                     var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
  3060 
  3061                     var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
  3062                     if (renderMode == "replaceNode") {
  3063                         targetNodeOrNodeArray = renderedNodesArray;
  3064                         firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
  3065                     }
  3066                 },
  3067                 null,
  3068                 { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
  3069             );
  3070         } else {
  3071             // 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
  3072             return ko.memoization.memoize(function (domNode) {
  3073                 ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
  3074             });
  3075         }
  3076     };
  3077 
  3078     ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
  3079         // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
  3080         // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
  3081         var arrayItemContext;
  3082 
  3083         // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
  3084         var executeTemplateForArrayItem = function (arrayValue, index) {
  3085             // Support selecting template as a function of the data being rendered
  3086             arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue), options['as']);
  3087             arrayItemContext['$index'] = index;
  3088             var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
  3089             return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
  3090         }
  3091 
  3092         // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
  3093         var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
  3094             activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
  3095             if (options['afterRender'])
  3096                 options['afterRender'](addedNodesArray, arrayValue);
  3097         };
  3098 
  3099         return ko.dependentObservable(function () {
  3100             var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
  3101             if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
  3102                 unwrappedArray = [unwrappedArray];
  3103 
  3104             // Filter out any entries marked as destroyed
  3105             var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
  3106                 return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
  3107             });
  3108 
  3109             // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
  3110             // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
  3111             ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
  3112 
  3113         }, null, { disposeWhenNodeIsRemoved: targetNode });
  3114     };
  3115 
  3116     var templateComputedDomDataKey = '__ko__templateComputedDomDataKey__';
  3117     function disposeOldComputedAndStoreNewOne(element, newComputed) {
  3118         var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
  3119         if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
  3120             oldComputed.dispose();
  3121         ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
  3122     }
  3123 
  3124     ko.bindingHandlers['template'] = {
  3125         'init': function(element, valueAccessor) {
  3126             // Support anonymous templates
  3127             var bindingValue = ko.utils.unwrapObservable(valueAccessor());
  3128             if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
  3129                 // It's an anonymous template - store the element contents, then clear the element
  3130                 var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
  3131                     container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
  3132                 new ko.templateSources.anonymousTemplate(element)['nodes'](container);
  3133             }
  3134             return { 'controlsDescendantBindings': true };
  3135         },
  3136         'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  3137             var templateName = ko.utils.unwrapObservable(valueAccessor()),
  3138                 options = {},
  3139                 shouldDisplay = true,
  3140                 dataValue,
  3141                 templateComputed = null;
  3142 
  3143             if (typeof templateName != "string") {
  3144                 options = templateName;
  3145                 templateName = options['name'];
  3146 
  3147                 // Support "if"/"ifnot" conditions
  3148                 if ('if' in options)
  3149                     shouldDisplay = ko.utils.unwrapObservable(options['if']);
  3150                 if (shouldDisplay && 'ifnot' in options)
  3151                     shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
  3152 
  3153                 dataValue = ko.utils.unwrapObservable(options['data']);
  3154             }
  3155 
  3156             if ('foreach' in options) {
  3157                 // Render once for each data point (treating data set as empty if shouldDisplay==false)
  3158                 var dataArray = (shouldDisplay && options['foreach']) || [];
  3159                 templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
  3160             } else if (!shouldDisplay) {
  3161                 ko.virtualElements.emptyNode(element);
  3162             } else {
  3163                 // Render once for this single data point (or use the viewModel if no data was provided)
  3164                 var innerBindingContext = ('data' in options) ?
  3165                     bindingContext['createChildContext'](dataValue, options['as']) :  // Given an explitit 'data' value, we create a child binding context for it
  3166                     bindingContext;                                                        // Given no explicit 'data' value, we retain the same binding context
  3167                 templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
  3168             }
  3169 
  3170             // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
  3171             disposeOldComputedAndStoreNewOne(element, templateComputed);
  3172         }
  3173     };
  3174 
  3175     // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
  3176     ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
  3177         var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
  3178 
  3179         if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
  3180             return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
  3181 
  3182         if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
  3183             return null; // Named templates can be rewritten, so return "no error"
  3184         return "This template engine does not support anonymous templates nested within its templates";
  3185     };
  3186 
  3187     ko.virtualElements.allowedBindings['template'] = true;
  3188 })();
  3189 
  3190 ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
  3191 ko.exportSymbol('renderTemplate', ko.renderTemplate);
  3192 
  3193 ko.utils.compareArrays = (function () {
  3194     var statusNotInOld = 'added', statusNotInNew = 'deleted';
  3195 
  3196     // Simple calculation based on Levenshtein distance.
  3197     function compareArrays(oldArray, newArray, dontLimitMoves) {
  3198         oldArray = oldArray || [];
  3199         newArray = newArray || [];
  3200 
  3201         if (oldArray.length <= newArray.length)
  3202             return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, dontLimitMoves);
  3203         else
  3204             return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, dontLimitMoves);
  3205     }
  3206 
  3207     function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, dontLimitMoves) {
  3208         var myMin = Math.min,
  3209             myMax = Math.max,
  3210             editDistanceMatrix = [],
  3211             smlIndex, smlIndexMax = smlArray.length,
  3212             bigIndex, bigIndexMax = bigArray.length,
  3213             compareRange = (bigIndexMax - smlIndexMax) || 1,
  3214             maxDistance = smlIndexMax + bigIndexMax + 1,
  3215             thisRow, lastRow,
  3216             bigIndexMaxForRow, bigIndexMinForRow;
  3217 
  3218         for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
  3219             lastRow = thisRow;
  3220             editDistanceMatrix.push(thisRow = []);
  3221             bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
  3222             bigIndexMinForRow = myMax(0, smlIndex - 1);
  3223             for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
  3224                 if (!bigIndex)
  3225                     thisRow[bigIndex] = smlIndex + 1;
  3226                 else if (!smlIndex)  // Top row - transform empty array into new array via additions
  3227                     thisRow[bigIndex] = bigIndex + 1;
  3228                 else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
  3229                     thisRow[bigIndex] = lastRow[bigIndex - 1];                  // copy value (no edit)
  3230                 else {
  3231                     var northDistance = lastRow[bigIndex] || maxDistance;       // not in big (deletion)
  3232                     var westDistance = thisRow[bigIndex - 1] || maxDistance;    // not in small (addition)
  3233                     thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
  3234                 }
  3235             }
  3236         }
  3237 
  3238         var editScript = [], meMinusOne, notInSml = [], notInBig = [];
  3239         for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
  3240             meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
  3241             if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
  3242                 notInSml.push(editScript[editScript.length] = {     // added
  3243                     'status': statusNotInSml,
  3244                     'value': bigArray[--bigIndex],
  3245                     'index': bigIndex });
  3246             } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
  3247                 notInBig.push(editScript[editScript.length] = {     // deleted
  3248                     'status': statusNotInBig,
  3249                     'value': smlArray[--smlIndex],
  3250                     'index': smlIndex });
  3251             } else {
  3252                 editScript.push({
  3253                     'status': "retained",
  3254                     'value': bigArray[--bigIndex] });
  3255                 --smlIndex;
  3256             }
  3257         }
  3258 
  3259         if (notInSml.length && notInBig.length) {
  3260             // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
  3261             // smlIndexMax keeps the time complexity of this algorithm linear.
  3262             var limitFailedCompares = smlIndexMax * 10, failedCompares,
  3263                 a, d, notInSmlItem, notInBigItem;
  3264             // Go through the items that have been added and deleted and try to find matches between them.
  3265             for (failedCompares = a = 0; (dontLimitMoves || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
  3266                 for (d = 0; notInBigItem = notInBig[d]; d++) {
  3267                     if (notInSmlItem['value'] === notInBigItem['value']) {
  3268                         notInSmlItem['moved'] = notInBigItem['index'];
  3269                         notInBigItem['moved'] = notInSmlItem['index'];
  3270                         notInBig.splice(d,1);       // This item is marked as moved; so remove it from notInBig list
  3271                         failedCompares = d = 0;     // Reset failed compares count because we're checking for consecutive failures
  3272                         break;
  3273                     }
  3274                 }
  3275                 failedCompares += d;
  3276             }
  3277         }
  3278         return editScript.reverse();
  3279     }
  3280 
  3281     return compareArrays;
  3282 })();
  3283 
  3284 ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
  3285 
  3286 (function () {
  3287     // Objective:
  3288     // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
  3289     //   map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
  3290     // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
  3291     //   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
  3292     //   previously mapped - retain those nodes, and just insert/delete other ones
  3293 
  3294     // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
  3295     // You can use this, for example, to activate bindings on those nodes.
  3296 
  3297     function fixUpNodesToBeMovedOrRemoved(contiguousNodeArray) {
  3298         // Before moving, deleting, or replacing a set of nodes that were previously outputted by the "map" function, we have to reconcile
  3299         // them against what is in the DOM right now. It may be that some of the nodes have already been removed from the document,
  3300         // or that new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
  3301         // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
  3302         // So, this function translates the old "map" output array into its best guess of what set of current DOM nodes should be removed.
  3303         //
  3304         // Rules:
  3305         //   [A] Any leading nodes that aren't in the document any more should be ignored
  3306         //       These most likely correspond to memoization nodes that were already removed during binding
  3307         //       See https://github.com/SteveSanderson/knockout/pull/440
  3308         //   [B] We want to output a contiguous series of nodes that are still in the document. So, ignore any nodes that
  3309         //       have already been removed, and include any nodes that have been inserted among the previous collection
  3310 
  3311         // Rule [A]
  3312         while (contiguousNodeArray.length && !ko.utils.domNodeIsAttachedToDocument(contiguousNodeArray[0]))
  3313             contiguousNodeArray.splice(0, 1);
  3314 
  3315         // Rule [B]
  3316         if (contiguousNodeArray.length > 1) {
  3317             // Build up the actual new contiguous node set
  3318             var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
  3319             while (current !== last) {
  3320                 current = current.nextSibling;
  3321                 if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
  3322                     return;
  3323                 newContiguousSet.push(current);
  3324             }
  3325 
  3326             // ... then mutate the input array to match this.
  3327             // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
  3328             Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
  3329         }
  3330         return contiguousNodeArray;
  3331     }
  3332 
  3333     function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
  3334         // Map this array value inside a dependentObservable so we re-map when any dependency changes
  3335         var mappedNodes = [];
  3336         var dependentObservable = ko.dependentObservable(function() {
  3337             var newMappedNodes = mapping(valueToMap, index) || [];
  3338 
  3339             // On subsequent evaluations, just replace the previously-inserted DOM nodes
  3340             if (mappedNodes.length > 0) {
  3341                 ko.utils.replaceDomNodes(fixUpNodesToBeMovedOrRemoved(mappedNodes), newMappedNodes);
  3342                 if (callbackAfterAddingNodes)
  3343                     ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
  3344             }
  3345 
  3346             // Replace the contents of the mappedNodes array, thereby updating the record
  3347             // of which nodes would be deleted if valueToMap was itself later removed
  3348             mappedNodes.splice(0, mappedNodes.length);
  3349             ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
  3350         }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
  3351         return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
  3352     }
  3353 
  3354     var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
  3355 
  3356     ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
  3357         // Compare the provided array against the previous one
  3358         array = array || [];
  3359         options = options || {};
  3360         var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
  3361         var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
  3362         var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
  3363         var editScript = ko.utils.compareArrays(lastArray, array);
  3364 
  3365         // Build the new mapping result
  3366         var newMappingResult = [];
  3367         var lastMappingResultIndex = 0;
  3368         var newMappingResultIndex = 0;
  3369 
  3370         var nodesToDelete = [];
  3371         var itemsToProcess = [];
  3372         var itemsForBeforeRemoveCallbacks = [];
  3373         var itemsForMoveCallbacks = [];
  3374         var itemsForAfterAddCallbacks = [];
  3375         var mapData;
  3376 
  3377         function itemMovedOrRetained(editScriptIndex, oldPosition) {
  3378             mapData = lastMappingResult[oldPosition];
  3379             if (newMappingResultIndex !== oldPosition)
  3380                 itemsForMoveCallbacks[editScriptIndex] = mapData;
  3381             // Since updating the index might change the nodes, do so before calling fixUpNodesToBeMovedOrRemoved
  3382             mapData.indexObservable(newMappingResultIndex++);
  3383             fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes);
  3384             newMappingResult.push(mapData);
  3385             itemsToProcess.push(mapData);
  3386         }
  3387 
  3388         function callCallback(callback, items) {
  3389             if (callback) {
  3390                 for (var i = 0, n = items.length; i < n; i++) {
  3391                     if (items[i]) {
  3392                         ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
  3393                             callback(node, i, items[i].arrayEntry);
  3394                         });
  3395                     }
  3396                 }
  3397             }
  3398         }
  3399 
  3400         for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
  3401             movedIndex = editScriptItem['moved'];
  3402             switch (editScriptItem['status']) {
  3403                 case "deleted":
  3404                     if (movedIndex === undefined) {
  3405                         mapData = lastMappingResult[lastMappingResultIndex];
  3406 
  3407                         // Stop tracking changes to the mapping for these nodes
  3408                         if (mapData.dependentObservable)
  3409                             mapData.dependentObservable.dispose();
  3410 
  3411                         // Queue these nodes for later removal
  3412                         nodesToDelete.push.apply(nodesToDelete, fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes));
  3413                         if (options['beforeRemove']) {
  3414                             itemsForBeforeRemoveCallbacks[i] = mapData;
  3415                             itemsToProcess.push(mapData);
  3416                         }
  3417                     }
  3418                     lastMappingResultIndex++;
  3419                     break;
  3420 
  3421                 case "retained":
  3422                     itemMovedOrRetained(i, lastMappingResultIndex++);
  3423                     break;
  3424 
  3425                 case "added":
  3426                     if (movedIndex !== undefined) {
  3427                         itemMovedOrRetained(i, movedIndex);
  3428                     } else {
  3429                         mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
  3430                         newMappingResult.push(mapData);
  3431                         itemsToProcess.push(mapData);
  3432                         if (!isFirstExecution)
  3433                             itemsForAfterAddCallbacks[i] = mapData;
  3434                     }
  3435                     break;
  3436             }
  3437         }
  3438 
  3439         // Call beforeMove first before any changes have been made to the DOM
  3440         callCallback(options['beforeMove'], itemsForMoveCallbacks);
  3441 
  3442         // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
  3443         ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
  3444 
  3445         // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
  3446         for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
  3447             // Get nodes for newly added items
  3448             if (!mapData.mappedNodes)
  3449                 ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
  3450 
  3451             // Put nodes in the right place if they aren't there already
  3452             for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
  3453                 if (node !== nextNode)
  3454                     ko.virtualElements.insertAfter(domNode, node, lastNode);
  3455             }
  3456 
  3457             // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
  3458             if (!mapData.initialized && callbackAfterAddingNodes) {
  3459                 callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
  3460                 mapData.initialized = true;
  3461             }
  3462         }
  3463 
  3464         // If there's a beforeRemove callback, call it after reordering.
  3465         // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
  3466         // some sort of animation, which is why we first reorder the nodes that will be removed. If the
  3467         // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
  3468         // Perhaps we'll make that change in the future if this scenario becomes more common.
  3469         callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
  3470 
  3471         // Finally call afterMove and afterAdd callbacks
  3472         callCallback(options['afterMove'], itemsForMoveCallbacks);
  3473         callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
  3474 
  3475         // Store a copy of the array items we just considered so we can difference it next time
  3476         ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
  3477     }
  3478 })();
  3479 
  3480 ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
  3481 ko.nativeTemplateEngine = function () {
  3482     this['allowTemplateRewriting'] = false;
  3483 }
  3484 
  3485 ko.nativeTemplateEngine.prototype = new ko.templateEngine();
  3486 ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
  3487     var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
  3488         templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
  3489         templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
  3490 
  3491     if (templateNodes) {
  3492         return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
  3493     } else {
  3494         var templateText = templateSource['text']();
  3495         return ko.utils.parseHtmlFragment(templateText);
  3496     }
  3497 };
  3498 
  3499 ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
  3500 ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
  3501 
  3502 ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
  3503 (function() {
  3504     ko.jqueryTmplTemplateEngine = function () {
  3505         // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
  3506         // doesn't expose a version number, so we have to infer it.
  3507         // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
  3508         // which KO internally refers to as version "2", so older versions are no longer detected.
  3509         var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
  3510             if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
  3511                 return 0;
  3512             // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
  3513             try {
  3514                 if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
  3515                     // Since 1.0.0pre, custom tags should append markup to an array called "__"
  3516                     return 2; // Final version of jquery.tmpl
  3517                 }
  3518             } catch(ex) { /* Apparently not the version we were looking for */ }
  3519 
  3520             return 1; // Any older version that we don't support
  3521         })();
  3522 
  3523         function ensureHasReferencedJQueryTemplates() {
  3524             if (jQueryTmplVersion < 2)
  3525                 throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
  3526         }
  3527 
  3528         function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
  3529             return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
  3530         }
  3531 
  3532         this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
  3533             options = options || {};
  3534             ensureHasReferencedJQueryTemplates();
  3535 
  3536             // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
  3537             var precompiled = templateSource['data']('precompiled');
  3538             if (!precompiled) {
  3539                 var templateText = templateSource['text']() || "";
  3540                 // Wrap in "with($whatever.koBindingContext) { ... }"
  3541                 templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
  3542 
  3543                 precompiled = jQuery['template'](null, templateText);
  3544                 templateSource['data']('precompiled', precompiled);
  3545             }
  3546 
  3547             var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
  3548             var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
  3549 
  3550             var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
  3551             resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
  3552 
  3553             jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
  3554             return resultNodes;
  3555         };
  3556 
  3557         this['createJavaScriptEvaluatorBlock'] = function(script) {
  3558             return "{{ko_code ((function() { return " + script + " })()) }}";
  3559         };
  3560 
  3561         this['addTemplate'] = function(templateName, templateMarkup) {
  3562             document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
  3563         };
  3564 
  3565         if (jQueryTmplVersion > 0) {
  3566             jQuery['tmpl']['tag']['ko_code'] = {
  3567                 open: "__.push($1 || '');"
  3568             };
  3569             jQuery['tmpl']['tag']['ko_with'] = {
  3570                 open: "with($1) {",
  3571                 close: "} "
  3572             };
  3573         }
  3574     };
  3575 
  3576     ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
  3577 
  3578     // Use this one by default *only if jquery.tmpl is referenced*
  3579     var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
  3580     if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
  3581         ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
  3582 
  3583     ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
  3584 })();
  3585 });
  3586 })(window,document,navigator,window["jQuery"]);
  3587 })();