1.1 --- a/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/Knockout.java Sun Jan 20 18:20:18 2013 +0100
1.2 +++ b/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/Knockout.java Sun Jan 20 20:48:37 2013 +0100
1.3 @@ -24,7 +24,7 @@
1.4 *
1.5 * @author Jaroslav Tulach <jtulach@netbeans.org>
1.6 */
1.7 -@ExtraJavaScript(resource = "org/apidesign/bck2brwsr/htmlpage/knockout-min-2.2.0.js")
1.8 +@ExtraJavaScript(resource = "org/apidesign/bck2brwsr/htmlpage/knockout-2.2.1.js")
1.9 public final class Knockout {
1.10
1.11
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/javaquery/api/src/main/resources/org/apidesign/bck2brwsr/htmlpage/knockout-2.2.1.js Sun Jan 20 20:48:37 2013 +0100
2.3 @@ -0,0 +1,3583 @@
2.4 +// Knockout JavaScript library v2.2.1
2.5 +// (c) Steven Sanderson - http://knockoutjs.com/
2.6 +// License: MIT (http://www.opensource.org/licenses/mit-license.php)
2.7 +
2.8 +(function(){
2.9 +var DEBUG=true;
2.10 +(function(window,document,navigator,jQuery,undefined){
2.11 +!function(factory) {
2.12 + // Support three module loading scenarios
2.13 + if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
2.14 + // [1] CommonJS/Node.js
2.15 + var target = module['exports'] || exports; // module.exports is for Node.js
2.16 + factory(target);
2.17 + } else if (typeof define === 'function' && define['amd']) {
2.18 + // [2] AMD anonymous module
2.19 + define(['exports'], factory);
2.20 + } else {
2.21 + // [3] No module loader (plain <script> tag) - put directly in global namespace
2.22 + factory(window['ko'] = {});
2.23 + }
2.24 +}(function(koExports){
2.25 +// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
2.26 +// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
2.27 +var ko = typeof koExports !== 'undefined' ? koExports : {};
2.28 +// Google Closure Compiler helpers (used only to make the minified file smaller)
2.29 +ko.exportSymbol = function(koPath, object) {
2.30 + var tokens = koPath.split(".");
2.31 +
2.32 + // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
2.33 + // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
2.34 + var target = ko;
2.35 +
2.36 + for (var i = 0; i < tokens.length - 1; i++)
2.37 + target = target[tokens[i]];
2.38 + target[tokens[tokens.length - 1]] = object;
2.39 +};
2.40 +ko.exportProperty = function(owner, publicName, object) {
2.41 + owner[publicName] = object;
2.42 +};
2.43 +ko.version = "2.2.1";
2.44 +
2.45 +ko.exportSymbol('version', ko.version);
2.46 +ko.utils = new (function () {
2.47 + var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
2.48 +
2.49 + // 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)
2.50 + var knownEvents = {}, knownEventTypesByEventName = {};
2.51 + var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';
2.52 + knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
2.53 + knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
2.54 + for (var eventType in knownEvents) {
2.55 + var knownEventsForType = knownEvents[eventType];
2.56 + if (knownEventsForType.length) {
2.57 + for (var i = 0, j = knownEventsForType.length; i < j; i++)
2.58 + knownEventTypesByEventName[knownEventsForType[i]] = eventType;
2.59 + }
2.60 + }
2.61 + var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
2.62 +
2.63 + // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
2.64 + // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
2.65 + // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
2.66 + // If there is a future need to detect specific versions of IE10+, we will amend this.
2.67 + var ieVersion = (function() {
2.68 + var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
2.69 +
2.70 + // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
2.71 + while (
2.72 + div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
2.73 + iElems[0]
2.74 + );
2.75 + return version > 4 ? version : undefined;
2.76 + }());
2.77 + var isIe6 = ieVersion === 6,
2.78 + isIe7 = ieVersion === 7;
2.79 +
2.80 + function isClickOnCheckableElement(element, eventType) {
2.81 + if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
2.82 + if (eventType.toLowerCase() != "click") return false;
2.83 + var inputType = element.type;
2.84 + return (inputType == "checkbox") || (inputType == "radio");
2.85 + }
2.86 +
2.87 + return {
2.88 + fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
2.89 +
2.90 + arrayForEach: function (array, action) {
2.91 + for (var i = 0, j = array.length; i < j; i++)
2.92 + action(array[i]);
2.93 + },
2.94 +
2.95 + arrayIndexOf: function (array, item) {
2.96 + if (typeof Array.prototype.indexOf == "function")
2.97 + return Array.prototype.indexOf.call(array, item);
2.98 + for (var i = 0, j = array.length; i < j; i++)
2.99 + if (array[i] === item)
2.100 + return i;
2.101 + return -1;
2.102 + },
2.103 +
2.104 + arrayFirst: function (array, predicate, predicateOwner) {
2.105 + for (var i = 0, j = array.length; i < j; i++)
2.106 + if (predicate.call(predicateOwner, array[i]))
2.107 + return array[i];
2.108 + return null;
2.109 + },
2.110 +
2.111 + arrayRemoveItem: function (array, itemToRemove) {
2.112 + var index = ko.utils.arrayIndexOf(array, itemToRemove);
2.113 + if (index >= 0)
2.114 + array.splice(index, 1);
2.115 + },
2.116 +
2.117 + arrayGetDistinctValues: function (array) {
2.118 + array = array || [];
2.119 + var result = [];
2.120 + for (var i = 0, j = array.length; i < j; i++) {
2.121 + if (ko.utils.arrayIndexOf(result, array[i]) < 0)
2.122 + result.push(array[i]);
2.123 + }
2.124 + return result;
2.125 + },
2.126 +
2.127 + arrayMap: function (array, mapping) {
2.128 + array = array || [];
2.129 + var result = [];
2.130 + for (var i = 0, j = array.length; i < j; i++)
2.131 + result.push(mapping(array[i]));
2.132 + return result;
2.133 + },
2.134 +
2.135 + arrayFilter: function (array, predicate) {
2.136 + array = array || [];
2.137 + var result = [];
2.138 + for (var i = 0, j = array.length; i < j; i++)
2.139 + if (predicate(array[i]))
2.140 + result.push(array[i]);
2.141 + return result;
2.142 + },
2.143 +
2.144 + arrayPushAll: function (array, valuesToPush) {
2.145 + if (valuesToPush instanceof Array)
2.146 + array.push.apply(array, valuesToPush);
2.147 + else
2.148 + for (var i = 0, j = valuesToPush.length; i < j; i++)
2.149 + array.push(valuesToPush[i]);
2.150 + return array;
2.151 + },
2.152 +
2.153 + extend: function (target, source) {
2.154 + if (source) {
2.155 + for(var prop in source) {
2.156 + if(source.hasOwnProperty(prop)) {
2.157 + target[prop] = source[prop];
2.158 + }
2.159 + }
2.160 + }
2.161 + return target;
2.162 + },
2.163 +
2.164 + emptyDomNode: function (domNode) {
2.165 + while (domNode.firstChild) {
2.166 + ko.removeNode(domNode.firstChild);
2.167 + }
2.168 + },
2.169 +
2.170 + moveCleanedNodesToContainerElement: function(nodes) {
2.171 + // Ensure it's a real array, as we're about to reparent the nodes and
2.172 + // we don't want the underlying collection to change while we're doing that.
2.173 + var nodesArray = ko.utils.makeArray(nodes);
2.174 +
2.175 + var container = document.createElement('div');
2.176 + for (var i = 0, j = nodesArray.length; i < j; i++) {
2.177 + container.appendChild(ko.cleanNode(nodesArray[i]));
2.178 + }
2.179 + return container;
2.180 + },
2.181 +
2.182 + cloneNodes: function (nodesArray, shouldCleanNodes) {
2.183 + for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
2.184 + var clonedNode = nodesArray[i].cloneNode(true);
2.185 + newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
2.186 + }
2.187 + return newNodesArray;
2.188 + },
2.189 +
2.190 + setDomNodeChildren: function (domNode, childNodes) {
2.191 + ko.utils.emptyDomNode(domNode);
2.192 + if (childNodes) {
2.193 + for (var i = 0, j = childNodes.length; i < j; i++)
2.194 + domNode.appendChild(childNodes[i]);
2.195 + }
2.196 + },
2.197 +
2.198 + replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
2.199 + var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
2.200 + if (nodesToReplaceArray.length > 0) {
2.201 + var insertionPoint = nodesToReplaceArray[0];
2.202 + var parent = insertionPoint.parentNode;
2.203 + for (var i = 0, j = newNodesArray.length; i < j; i++)
2.204 + parent.insertBefore(newNodesArray[i], insertionPoint);
2.205 + for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
2.206 + ko.removeNode(nodesToReplaceArray[i]);
2.207 + }
2.208 + }
2.209 + },
2.210 +
2.211 + setOptionNodeSelectionState: function (optionNode, isSelected) {
2.212 + // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
2.213 + if (ieVersion < 7)
2.214 + optionNode.setAttribute("selected", isSelected);
2.215 + else
2.216 + optionNode.selected = isSelected;
2.217 + },
2.218 +
2.219 + stringTrim: function (string) {
2.220 + return (string || "").replace(stringTrimRegex, "");
2.221 + },
2.222 +
2.223 + stringTokenize: function (string, delimiter) {
2.224 + var result = [];
2.225 + var tokens = (string || "").split(delimiter);
2.226 + for (var i = 0, j = tokens.length; i < j; i++) {
2.227 + var trimmed = ko.utils.stringTrim(tokens[i]);
2.228 + if (trimmed !== "")
2.229 + result.push(trimmed);
2.230 + }
2.231 + return result;
2.232 + },
2.233 +
2.234 + stringStartsWith: function (string, startsWith) {
2.235 + string = string || "";
2.236 + if (startsWith.length > string.length)
2.237 + return false;
2.238 + return string.substring(0, startsWith.length) === startsWith;
2.239 + },
2.240 +
2.241 + domNodeIsContainedBy: function (node, containedByNode) {
2.242 + if (containedByNode.compareDocumentPosition)
2.243 + return (containedByNode.compareDocumentPosition(node) & 16) == 16;
2.244 + while (node != null) {
2.245 + if (node == containedByNode)
2.246 + return true;
2.247 + node = node.parentNode;
2.248 + }
2.249 + return false;
2.250 + },
2.251 +
2.252 + domNodeIsAttachedToDocument: function (node) {
2.253 + return ko.utils.domNodeIsContainedBy(node, node.ownerDocument);
2.254 + },
2.255 +
2.256 + tagNameLower: function(element) {
2.257 + // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
2.258 + // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
2.259 + // we don't need to do the .toLowerCase() as it will always be lower case anyway.
2.260 + return element && element.tagName && element.tagName.toLowerCase();
2.261 + },
2.262 +
2.263 + registerEventHandler: function (element, eventType, handler) {
2.264 + var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
2.265 + if (!mustUseAttachEvent && typeof jQuery != "undefined") {
2.266 + if (isClickOnCheckableElement(element, eventType)) {
2.267 + // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
2.268 + // it toggles the element checked state *after* the click event handlers run, whereas native
2.269 + // click events toggle the checked state *before* the event handler.
2.270 + // Fix this by intecepting the handler and applying the correct checkedness before it runs.
2.271 + var originalHandler = handler;
2.272 + handler = function(event, eventData) {
2.273 + var jQuerySuppliedCheckedState = this.checked;
2.274 + if (eventData)
2.275 + this.checked = eventData.checkedStateBeforeEvent !== true;
2.276 + originalHandler.call(this, event);
2.277 + this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
2.278 + };
2.279 + }
2.280 + jQuery(element)['bind'](eventType, handler);
2.281 + } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
2.282 + element.addEventListener(eventType, handler, false);
2.283 + else if (typeof element.attachEvent != "undefined")
2.284 + element.attachEvent("on" + eventType, function (event) {
2.285 + handler.call(element, event);
2.286 + });
2.287 + else
2.288 + throw new Error("Browser doesn't support addEventListener or attachEvent");
2.289 + },
2.290 +
2.291 + triggerEvent: function (element, eventType) {
2.292 + if (!(element && element.nodeType))
2.293 + throw new Error("element must be a DOM node when calling triggerEvent");
2.294 +
2.295 + if (typeof jQuery != "undefined") {
2.296 + var eventData = [];
2.297 + if (isClickOnCheckableElement(element, eventType)) {
2.298 + // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
2.299 + eventData.push({ checkedStateBeforeEvent: element.checked });
2.300 + }
2.301 + jQuery(element)['trigger'](eventType, eventData);
2.302 + } else if (typeof document.createEvent == "function") {
2.303 + if (typeof element.dispatchEvent == "function") {
2.304 + var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
2.305 + var event = document.createEvent(eventCategory);
2.306 + event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
2.307 + element.dispatchEvent(event);
2.308 + }
2.309 + else
2.310 + throw new Error("The supplied element doesn't support dispatchEvent");
2.311 + } else if (typeof element.fireEvent != "undefined") {
2.312 + // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
2.313 + // so to make it consistent, we'll do it manually here
2.314 + if (isClickOnCheckableElement(element, eventType))
2.315 + element.checked = element.checked !== true;
2.316 + element.fireEvent("on" + eventType);
2.317 + }
2.318 + else
2.319 + throw new Error("Browser doesn't support triggering events");
2.320 + },
2.321 +
2.322 + unwrapObservable: function (value) {
2.323 + return ko.isObservable(value) ? value() : value;
2.324 + },
2.325 +
2.326 + peekObservable: function (value) {
2.327 + return ko.isObservable(value) ? value.peek() : value;
2.328 + },
2.329 +
2.330 + toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
2.331 + if (classNames) {
2.332 + var cssClassNameRegex = /[\w-]+/g,
2.333 + currentClassNames = node.className.match(cssClassNameRegex) || [];
2.334 + ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
2.335 + var indexOfClass = ko.utils.arrayIndexOf(currentClassNames, className);
2.336 + if (indexOfClass >= 0) {
2.337 + if (!shouldHaveClass)
2.338 + currentClassNames.splice(indexOfClass, 1);
2.339 + } else {
2.340 + if (shouldHaveClass)
2.341 + currentClassNames.push(className);
2.342 + }
2.343 + });
2.344 + node.className = currentClassNames.join(" ");
2.345 + }
2.346 + },
2.347 +
2.348 + setTextContent: function(element, textContent) {
2.349 + var value = ko.utils.unwrapObservable(textContent);
2.350 + if ((value === null) || (value === undefined))
2.351 + value = "";
2.352 +
2.353 + if (element.nodeType === 3) {
2.354 + element.data = value;
2.355 + } else {
2.356 + // We need there to be exactly one child: a text node.
2.357 + // If there are no children, more than one, or if it's not a text node,
2.358 + // we'll clear everything and create a single text node.
2.359 + var innerTextNode = ko.virtualElements.firstChild(element);
2.360 + if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
2.361 + ko.virtualElements.setDomNodeChildren(element, [document.createTextNode(value)]);
2.362 + } else {
2.363 + innerTextNode.data = value;
2.364 + }
2.365 +
2.366 + ko.utils.forceRefresh(element);
2.367 + }
2.368 + },
2.369 +
2.370 + setElementName: function(element, name) {
2.371 + element.name = name;
2.372 +
2.373 + // Workaround IE 6/7 issue
2.374 + // - https://github.com/SteveSanderson/knockout/issues/197
2.375 + // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
2.376 + if (ieVersion <= 7) {
2.377 + try {
2.378 + element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
2.379 + }
2.380 + catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
2.381 + }
2.382 + },
2.383 +
2.384 + forceRefresh: function(node) {
2.385 + // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
2.386 + if (ieVersion >= 9) {
2.387 + // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
2.388 + var elem = node.nodeType == 1 ? node : node.parentNode;
2.389 + if (elem.style)
2.390 + elem.style.zoom = elem.style.zoom;
2.391 + }
2.392 + },
2.393 +
2.394 + ensureSelectElementIsRenderedCorrectly: function(selectElement) {
2.395 + // 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.
2.396 + // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
2.397 + if (ieVersion >= 9) {
2.398 + var originalWidth = selectElement.style.width;
2.399 + selectElement.style.width = 0;
2.400 + selectElement.style.width = originalWidth;
2.401 + }
2.402 + },
2.403 +
2.404 + range: function (min, max) {
2.405 + min = ko.utils.unwrapObservable(min);
2.406 + max = ko.utils.unwrapObservable(max);
2.407 + var result = [];
2.408 + for (var i = min; i <= max; i++)
2.409 + result.push(i);
2.410 + return result;
2.411 + },
2.412 +
2.413 + makeArray: function(arrayLikeObject) {
2.414 + var result = [];
2.415 + for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
2.416 + result.push(arrayLikeObject[i]);
2.417 + };
2.418 + return result;
2.419 + },
2.420 +
2.421 + isIe6 : isIe6,
2.422 + isIe7 : isIe7,
2.423 + ieVersion : ieVersion,
2.424 +
2.425 + getFormFields: function(form, fieldName) {
2.426 + var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
2.427 + var isMatchingField = (typeof fieldName == 'string')
2.428 + ? function(field) { return field.name === fieldName }
2.429 + : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
2.430 + var matches = [];
2.431 + for (var i = fields.length - 1; i >= 0; i--) {
2.432 + if (isMatchingField(fields[i]))
2.433 + matches.push(fields[i]);
2.434 + };
2.435 + return matches;
2.436 + },
2.437 +
2.438 + parseJson: function (jsonString) {
2.439 + if (typeof jsonString == "string") {
2.440 + jsonString = ko.utils.stringTrim(jsonString);
2.441 + if (jsonString) {
2.442 + if (window.JSON && window.JSON.parse) // Use native parsing where available
2.443 + return window.JSON.parse(jsonString);
2.444 + return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
2.445 + }
2.446 + }
2.447 + return null;
2.448 + },
2.449 +
2.450 + stringifyJson: function (data, replacer, space) { // replacer and space are optional
2.451 + if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
2.452 + 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");
2.453 + return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
2.454 + },
2.455 +
2.456 + postJson: function (urlOrForm, data, options) {
2.457 + options = options || {};
2.458 + var params = options['params'] || {};
2.459 + var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
2.460 + var url = urlOrForm;
2.461 +
2.462 + // If we were given a form, use its 'action' URL and pick out any requested field values
2.463 + if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
2.464 + var originalForm = urlOrForm;
2.465 + url = originalForm.action;
2.466 + for (var i = includeFields.length - 1; i >= 0; i--) {
2.467 + var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
2.468 + for (var j = fields.length - 1; j >= 0; j--)
2.469 + params[fields[j].name] = fields[j].value;
2.470 + }
2.471 + }
2.472 +
2.473 + data = ko.utils.unwrapObservable(data);
2.474 + var form = document.createElement("form");
2.475 + form.style.display = "none";
2.476 + form.action = url;
2.477 + form.method = "post";
2.478 + for (var key in data) {
2.479 + var input = document.createElement("input");
2.480 + input.name = key;
2.481 + input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
2.482 + form.appendChild(input);
2.483 + }
2.484 + for (var key in params) {
2.485 + var input = document.createElement("input");
2.486 + input.name = key;
2.487 + input.value = params[key];
2.488 + form.appendChild(input);
2.489 + }
2.490 + document.body.appendChild(form);
2.491 + options['submitter'] ? options['submitter'](form) : form.submit();
2.492 + setTimeout(function () { form.parentNode.removeChild(form); }, 0);
2.493 + }
2.494 + }
2.495 +})();
2.496 +
2.497 +ko.exportSymbol('utils', ko.utils);
2.498 +ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
2.499 +ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
2.500 +ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
2.501 +ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
2.502 +ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
2.503 +ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
2.504 +ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
2.505 +ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
2.506 +ko.exportSymbol('utils.extend', ko.utils.extend);
2.507 +ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
2.508 +ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
2.509 +ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
2.510 +ko.exportSymbol('utils.postJson', ko.utils.postJson);
2.511 +ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
2.512 +ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
2.513 +ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
2.514 +ko.exportSymbol('utils.range', ko.utils.range);
2.515 +ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
2.516 +ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
2.517 +ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
2.518 +
2.519 +if (!Function.prototype['bind']) {
2.520 + // 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)
2.521 + // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
2.522 + Function.prototype['bind'] = function (object) {
2.523 + var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
2.524 + return function () {
2.525 + return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
2.526 + };
2.527 + };
2.528 +}
2.529 +
2.530 +ko.utils.domData = new (function () {
2.531 + var uniqueId = 0;
2.532 + var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
2.533 + var dataStore = {};
2.534 + return {
2.535 + get: function (node, key) {
2.536 + var allDataForNode = ko.utils.domData.getAll(node, false);
2.537 + return allDataForNode === undefined ? undefined : allDataForNode[key];
2.538 + },
2.539 + set: function (node, key, value) {
2.540 + if (value === undefined) {
2.541 + // Make sure we don't actually create a new domData key if we are actually deleting a value
2.542 + if (ko.utils.domData.getAll(node, false) === undefined)
2.543 + return;
2.544 + }
2.545 + var allDataForNode = ko.utils.domData.getAll(node, true);
2.546 + allDataForNode[key] = value;
2.547 + },
2.548 + getAll: function (node, createIfNotFound) {
2.549 + var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
2.550 + var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
2.551 + if (!hasExistingDataStore) {
2.552 + if (!createIfNotFound)
2.553 + return undefined;
2.554 + dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
2.555 + dataStore[dataStoreKey] = {};
2.556 + }
2.557 + return dataStore[dataStoreKey];
2.558 + },
2.559 + clear: function (node) {
2.560 + var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
2.561 + if (dataStoreKey) {
2.562 + delete dataStore[dataStoreKey];
2.563 + node[dataStoreKeyExpandoPropertyName] = null;
2.564 + return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
2.565 + }
2.566 + return false;
2.567 + }
2.568 + }
2.569 +})();
2.570 +
2.571 +ko.exportSymbol('utils.domData', ko.utils.domData);
2.572 +ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
2.573 +
2.574 +ko.utils.domNodeDisposal = new (function () {
2.575 + var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();
2.576 + var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
2.577 + var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
2.578 +
2.579 + function getDisposeCallbacksCollection(node, createIfNotFound) {
2.580 + var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
2.581 + if ((allDisposeCallbacks === undefined) && createIfNotFound) {
2.582 + allDisposeCallbacks = [];
2.583 + ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
2.584 + }
2.585 + return allDisposeCallbacks;
2.586 + }
2.587 + function destroyCallbacksCollection(node) {
2.588 + ko.utils.domData.set(node, domDataKey, undefined);
2.589 + }
2.590 +
2.591 + function cleanSingleNode(node) {
2.592 + // Run all the dispose callbacks
2.593 + var callbacks = getDisposeCallbacksCollection(node, false);
2.594 + if (callbacks) {
2.595 + callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
2.596 + for (var i = 0; i < callbacks.length; i++)
2.597 + callbacks[i](node);
2.598 + }
2.599 +
2.600 + // Also erase the DOM data
2.601 + ko.utils.domData.clear(node);
2.602 +
2.603 + // Special support for jQuery here because it's so commonly used.
2.604 + // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
2.605 + // so notify it to tear down any resources associated with the node & descendants here.
2.606 + if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
2.607 + jQuery['cleanData']([node]);
2.608 +
2.609 + // Also clear any immediate-child comment nodes, as these wouldn't have been found by
2.610 + // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
2.611 + if (cleanableNodeTypesWithDescendants[node.nodeType])
2.612 + cleanImmediateCommentTypeChildren(node);
2.613 + }
2.614 +
2.615 + function cleanImmediateCommentTypeChildren(nodeWithChildren) {
2.616 + var child, nextChild = nodeWithChildren.firstChild;
2.617 + while (child = nextChild) {
2.618 + nextChild = child.nextSibling;
2.619 + if (child.nodeType === 8)
2.620 + cleanSingleNode(child);
2.621 + }
2.622 + }
2.623 +
2.624 + return {
2.625 + addDisposeCallback : function(node, callback) {
2.626 + if (typeof callback != "function")
2.627 + throw new Error("Callback must be a function");
2.628 + getDisposeCallbacksCollection(node, true).push(callback);
2.629 + },
2.630 +
2.631 + removeDisposeCallback : function(node, callback) {
2.632 + var callbacksCollection = getDisposeCallbacksCollection(node, false);
2.633 + if (callbacksCollection) {
2.634 + ko.utils.arrayRemoveItem(callbacksCollection, callback);
2.635 + if (callbacksCollection.length == 0)
2.636 + destroyCallbacksCollection(node);
2.637 + }
2.638 + },
2.639 +
2.640 + cleanNode : function(node) {
2.641 + // First clean this node, where applicable
2.642 + if (cleanableNodeTypes[node.nodeType]) {
2.643 + cleanSingleNode(node);
2.644 +
2.645 + // ... then its descendants, where applicable
2.646 + if (cleanableNodeTypesWithDescendants[node.nodeType]) {
2.647 + // Clone the descendants list in case it changes during iteration
2.648 + var descendants = [];
2.649 + ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
2.650 + for (var i = 0, j = descendants.length; i < j; i++)
2.651 + cleanSingleNode(descendants[i]);
2.652 + }
2.653 + }
2.654 + return node;
2.655 + },
2.656 +
2.657 + removeNode : function(node) {
2.658 + ko.cleanNode(node);
2.659 + if (node.parentNode)
2.660 + node.parentNode.removeChild(node);
2.661 + }
2.662 + }
2.663 +})();
2.664 +ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
2.665 +ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
2.666 +ko.exportSymbol('cleanNode', ko.cleanNode);
2.667 +ko.exportSymbol('removeNode', ko.removeNode);
2.668 +ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
2.669 +ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
2.670 +ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
2.671 +(function () {
2.672 + var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
2.673 +
2.674 + function simpleHtmlParse(html) {
2.675 + // Based on jQuery's "clean" function, but only accounting for table-related elements.
2.676 + // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
2.677 +
2.678 + // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
2.679 + // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
2.680 + // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
2.681 + // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
2.682 +
2.683 + // Trim whitespace, otherwise indexOf won't work as expected
2.684 + var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
2.685 +
2.686 + // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
2.687 + var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
2.688 + !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
2.689 + (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
2.690 + /* anything else */ [0, "", ""];
2.691 +
2.692 + // Go to html and back, then peel off extra wrappers
2.693 + // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
2.694 + var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
2.695 + if (typeof window['innerShiv'] == "function") {
2.696 + div.appendChild(window['innerShiv'](markup));
2.697 + } else {
2.698 + div.innerHTML = markup;
2.699 + }
2.700 +
2.701 + // Move to the right depth
2.702 + while (wrap[0]--)
2.703 + div = div.lastChild;
2.704 +
2.705 + return ko.utils.makeArray(div.lastChild.childNodes);
2.706 + }
2.707 +
2.708 + function jQueryHtmlParse(html) {
2.709 + // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
2.710 + if (jQuery['parseHTML']) {
2.711 + return jQuery['parseHTML'](html);
2.712 + } else {
2.713 + // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
2.714 + var elems = jQuery['clean']([html]);
2.715 +
2.716 + // 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.
2.717 + // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
2.718 + // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
2.719 + if (elems && elems[0]) {
2.720 + // Find the top-most parent element that's a direct child of a document fragment
2.721 + var elem = elems[0];
2.722 + while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
2.723 + elem = elem.parentNode;
2.724 + // ... then detach it
2.725 + if (elem.parentNode)
2.726 + elem.parentNode.removeChild(elem);
2.727 + }
2.728 +
2.729 + return elems;
2.730 + }
2.731 + }
2.732 +
2.733 + ko.utils.parseHtmlFragment = function(html) {
2.734 + return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
2.735 + : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
2.736 + };
2.737 +
2.738 + ko.utils.setHtml = function(node, html) {
2.739 + ko.utils.emptyDomNode(node);
2.740 +
2.741 + // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
2.742 + html = ko.utils.unwrapObservable(html);
2.743 +
2.744 + if ((html !== null) && (html !== undefined)) {
2.745 + if (typeof html != 'string')
2.746 + html = html.toString();
2.747 +
2.748 + // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
2.749 + // for example <tr> elements which are not normally allowed to exist on their own.
2.750 + // If you've referenced jQuery we'll use that rather than duplicating its code.
2.751 + if (typeof jQuery != 'undefined') {
2.752 + jQuery(node)['html'](html);
2.753 + } else {
2.754 + // ... otherwise, use KO's own parsing logic.
2.755 + var parsedNodes = ko.utils.parseHtmlFragment(html);
2.756 + for (var i = 0; i < parsedNodes.length; i++)
2.757 + node.appendChild(parsedNodes[i]);
2.758 + }
2.759 + }
2.760 + };
2.761 +})();
2.762 +
2.763 +ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
2.764 +ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
2.765 +
2.766 +ko.memoization = (function () {
2.767 + var memos = {};
2.768 +
2.769 + function randomMax8HexChars() {
2.770 + return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
2.771 + }
2.772 + function generateRandomId() {
2.773 + return randomMax8HexChars() + randomMax8HexChars();
2.774 + }
2.775 + function findMemoNodes(rootNode, appendToArray) {
2.776 + if (!rootNode)
2.777 + return;
2.778 + if (rootNode.nodeType == 8) {
2.779 + var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
2.780 + if (memoId != null)
2.781 + appendToArray.push({ domNode: rootNode, memoId: memoId });
2.782 + } else if (rootNode.nodeType == 1) {
2.783 + for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
2.784 + findMemoNodes(childNodes[i], appendToArray);
2.785 + }
2.786 + }
2.787 +
2.788 + return {
2.789 + memoize: function (callback) {
2.790 + if (typeof callback != "function")
2.791 + throw new Error("You can only pass a function to ko.memoization.memoize()");
2.792 + var memoId = generateRandomId();
2.793 + memos[memoId] = callback;
2.794 + return "<!--[ko_memo:" + memoId + "]-->";
2.795 + },
2.796 +
2.797 + unmemoize: function (memoId, callbackParams) {
2.798 + var callback = memos[memoId];
2.799 + if (callback === undefined)
2.800 + throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
2.801 + try {
2.802 + callback.apply(null, callbackParams || []);
2.803 + return true;
2.804 + }
2.805 + finally { delete memos[memoId]; }
2.806 + },
2.807 +
2.808 + unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
2.809 + var memos = [];
2.810 + findMemoNodes(domNode, memos);
2.811 + for (var i = 0, j = memos.length; i < j; i++) {
2.812 + var node = memos[i].domNode;
2.813 + var combinedParams = [node];
2.814 + if (extraCallbackParamsArray)
2.815 + ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
2.816 + ko.memoization.unmemoize(memos[i].memoId, combinedParams);
2.817 + node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
2.818 + if (node.parentNode)
2.819 + 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)
2.820 + }
2.821 + },
2.822 +
2.823 + parseMemoText: function (memoText) {
2.824 + var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
2.825 + return match ? match[1] : null;
2.826 + }
2.827 + };
2.828 +})();
2.829 +
2.830 +ko.exportSymbol('memoization', ko.memoization);
2.831 +ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
2.832 +ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
2.833 +ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
2.834 +ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
2.835 +ko.extenders = {
2.836 + 'throttle': function(target, timeout) {
2.837 + // Throttling means two things:
2.838 +
2.839 + // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
2.840 + // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
2.841 + target['throttleEvaluation'] = timeout;
2.842 +
2.843 + // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
2.844 + // so the target cannot change value synchronously or faster than a certain rate
2.845 + var writeTimeoutInstance = null;
2.846 + return ko.dependentObservable({
2.847 + 'read': target,
2.848 + 'write': function(value) {
2.849 + clearTimeout(writeTimeoutInstance);
2.850 + writeTimeoutInstance = setTimeout(function() {
2.851 + target(value);
2.852 + }, timeout);
2.853 + }
2.854 + });
2.855 + },
2.856 +
2.857 + 'notify': function(target, notifyWhen) {
2.858 + target["equalityComparer"] = notifyWhen == "always"
2.859 + ? function() { return false } // Treat all values as not equal
2.860 + : ko.observable["fn"]["equalityComparer"];
2.861 + return target;
2.862 + }
2.863 +};
2.864 +
2.865 +function applyExtenders(requestedExtenders) {
2.866 + var target = this;
2.867 + if (requestedExtenders) {
2.868 + for (var key in requestedExtenders) {
2.869 + var extenderHandler = ko.extenders[key];
2.870 + if (typeof extenderHandler == 'function') {
2.871 + target = extenderHandler(target, requestedExtenders[key]);
2.872 + }
2.873 + }
2.874 + }
2.875 + return target;
2.876 +}
2.877 +
2.878 +ko.exportSymbol('extenders', ko.extenders);
2.879 +
2.880 +ko.subscription = function (target, callback, disposeCallback) {
2.881 + this.target = target;
2.882 + this.callback = callback;
2.883 + this.disposeCallback = disposeCallback;
2.884 + ko.exportProperty(this, 'dispose', this.dispose);
2.885 +};
2.886 +ko.subscription.prototype.dispose = function () {
2.887 + this.isDisposed = true;
2.888 + this.disposeCallback();
2.889 +};
2.890 +
2.891 +ko.subscribable = function () {
2.892 + this._subscriptions = {};
2.893 +
2.894 + ko.utils.extend(this, ko.subscribable['fn']);
2.895 + ko.exportProperty(this, 'subscribe', this.subscribe);
2.896 + ko.exportProperty(this, 'extend', this.extend);
2.897 + ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
2.898 +}
2.899 +
2.900 +var defaultEvent = "change";
2.901 +
2.902 +ko.subscribable['fn'] = {
2.903 + subscribe: function (callback, callbackTarget, event) {
2.904 + event = event || defaultEvent;
2.905 + var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
2.906 +
2.907 + var subscription = new ko.subscription(this, boundCallback, function () {
2.908 + ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
2.909 + }.bind(this));
2.910 +
2.911 + if (!this._subscriptions[event])
2.912 + this._subscriptions[event] = [];
2.913 + this._subscriptions[event].push(subscription);
2.914 + return subscription;
2.915 + },
2.916 +
2.917 + "notifySubscribers": function (valueToNotify, event) {
2.918 + event = event || defaultEvent;
2.919 + if (this._subscriptions[event]) {
2.920 + ko.dependencyDetection.ignore(function() {
2.921 + ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
2.922 + // In case a subscription was disposed during the arrayForEach cycle, check
2.923 + // for isDisposed on each subscription before invoking its callback
2.924 + if (subscription && (subscription.isDisposed !== true))
2.925 + subscription.callback(valueToNotify);
2.926 + });
2.927 + }, this);
2.928 + }
2.929 + },
2.930 +
2.931 + getSubscriptionsCount: function () {
2.932 + var total = 0;
2.933 + for (var eventName in this._subscriptions) {
2.934 + if (this._subscriptions.hasOwnProperty(eventName))
2.935 + total += this._subscriptions[eventName].length;
2.936 + }
2.937 + return total;
2.938 + },
2.939 +
2.940 + extend: applyExtenders
2.941 +};
2.942 +
2.943 +
2.944 +ko.isSubscribable = function (instance) {
2.945 + return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
2.946 +};
2.947 +
2.948 +ko.exportSymbol('subscribable', ko.subscribable);
2.949 +ko.exportSymbol('isSubscribable', ko.isSubscribable);
2.950 +
2.951 +ko.dependencyDetection = (function () {
2.952 + var _frames = [];
2.953 +
2.954 + return {
2.955 + begin: function (callback) {
2.956 + _frames.push({ callback: callback, distinctDependencies:[] });
2.957 + },
2.958 +
2.959 + end: function () {
2.960 + _frames.pop();
2.961 + },
2.962 +
2.963 + registerDependency: function (subscribable) {
2.964 + if (!ko.isSubscribable(subscribable))
2.965 + throw new Error("Only subscribable things can act as dependencies");
2.966 + if (_frames.length > 0) {
2.967 + var topFrame = _frames[_frames.length - 1];
2.968 + if (!topFrame || ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
2.969 + return;
2.970 + topFrame.distinctDependencies.push(subscribable);
2.971 + topFrame.callback(subscribable);
2.972 + }
2.973 + },
2.974 +
2.975 + ignore: function(callback, callbackTarget, callbackArgs) {
2.976 + try {
2.977 + _frames.push(null);
2.978 + return callback.apply(callbackTarget, callbackArgs || []);
2.979 + } finally {
2.980 + _frames.pop();
2.981 + }
2.982 + }
2.983 + };
2.984 +})();
2.985 +var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };
2.986 +
2.987 +ko.observable = function (initialValue) {
2.988 + var _latestValue = initialValue;
2.989 +
2.990 + function observable() {
2.991 + if (arguments.length > 0) {
2.992 + // Write
2.993 +
2.994 + // Ignore writes if the value hasn't changed
2.995 + if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
2.996 + observable.valueWillMutate();
2.997 + _latestValue = arguments[0];
2.998 + if (DEBUG) observable._latestValue = _latestValue;
2.999 + observable.valueHasMutated();
2.1000 + }
2.1001 + return this; // Permits chained assignments
2.1002 + }
2.1003 + else {
2.1004 + // Read
2.1005 + ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
2.1006 + return _latestValue;
2.1007 + }
2.1008 + }
2.1009 + if (DEBUG) observable._latestValue = _latestValue;
2.1010 + ko.subscribable.call(observable);
2.1011 + observable.peek = function() { return _latestValue };
2.1012 + observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
2.1013 + observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
2.1014 + ko.utils.extend(observable, ko.observable['fn']);
2.1015 +
2.1016 + ko.exportProperty(observable, 'peek', observable.peek);
2.1017 + ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
2.1018 + ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
2.1019 +
2.1020 + return observable;
2.1021 +}
2.1022 +
2.1023 +ko.observable['fn'] = {
2.1024 + "equalityComparer": function valuesArePrimitiveAndEqual(a, b) {
2.1025 + var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
2.1026 + return oldValueIsPrimitive ? (a === b) : false;
2.1027 + }
2.1028 +};
2.1029 +
2.1030 +var protoProperty = ko.observable.protoProperty = "__ko_proto__";
2.1031 +ko.observable['fn'][protoProperty] = ko.observable;
2.1032 +
2.1033 +ko.hasPrototype = function(instance, prototype) {
2.1034 + if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
2.1035 + if (instance[protoProperty] === prototype) return true;
2.1036 + return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
2.1037 +};
2.1038 +
2.1039 +ko.isObservable = function (instance) {
2.1040 + return ko.hasPrototype(instance, ko.observable);
2.1041 +}
2.1042 +ko.isWriteableObservable = function (instance) {
2.1043 + // Observable
2.1044 + if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
2.1045 + return true;
2.1046 + // Writeable dependent observable
2.1047 + if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
2.1048 + return true;
2.1049 + // Anything else
2.1050 + return false;
2.1051 +}
2.1052 +
2.1053 +
2.1054 +ko.exportSymbol('observable', ko.observable);
2.1055 +ko.exportSymbol('isObservable', ko.isObservable);
2.1056 +ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
2.1057 +ko.observableArray = function (initialValues) {
2.1058 + if (arguments.length == 0) {
2.1059 + // Zero-parameter constructor initializes to empty array
2.1060 + initialValues = [];
2.1061 + }
2.1062 + if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
2.1063 + throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
2.1064 +
2.1065 + var result = ko.observable(initialValues);
2.1066 + ko.utils.extend(result, ko.observableArray['fn']);
2.1067 + return result;
2.1068 +}
2.1069 +
2.1070 +ko.observableArray['fn'] = {
2.1071 + 'remove': function (valueOrPredicate) {
2.1072 + var underlyingArray = this.peek();
2.1073 + var removedValues = [];
2.1074 + var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
2.1075 + for (var i = 0; i < underlyingArray.length; i++) {
2.1076 + var value = underlyingArray[i];
2.1077 + if (predicate(value)) {
2.1078 + if (removedValues.length === 0) {
2.1079 + this.valueWillMutate();
2.1080 + }
2.1081 + removedValues.push(value);
2.1082 + underlyingArray.splice(i, 1);
2.1083 + i--;
2.1084 + }
2.1085 + }
2.1086 + if (removedValues.length) {
2.1087 + this.valueHasMutated();
2.1088 + }
2.1089 + return removedValues;
2.1090 + },
2.1091 +
2.1092 + 'removeAll': function (arrayOfValues) {
2.1093 + // If you passed zero args, we remove everything
2.1094 + if (arrayOfValues === undefined) {
2.1095 + var underlyingArray = this.peek();
2.1096 + var allValues = underlyingArray.slice(0);
2.1097 + this.valueWillMutate();
2.1098 + underlyingArray.splice(0, underlyingArray.length);
2.1099 + this.valueHasMutated();
2.1100 + return allValues;
2.1101 + }
2.1102 + // If you passed an arg, we interpret it as an array of entries to remove
2.1103 + if (!arrayOfValues)
2.1104 + return [];
2.1105 + return this['remove'](function (value) {
2.1106 + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
2.1107 + });
2.1108 + },
2.1109 +
2.1110 + 'destroy': function (valueOrPredicate) {
2.1111 + var underlyingArray = this.peek();
2.1112 + var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
2.1113 + this.valueWillMutate();
2.1114 + for (var i = underlyingArray.length - 1; i >= 0; i--) {
2.1115 + var value = underlyingArray[i];
2.1116 + if (predicate(value))
2.1117 + underlyingArray[i]["_destroy"] = true;
2.1118 + }
2.1119 + this.valueHasMutated();
2.1120 + },
2.1121 +
2.1122 + 'destroyAll': function (arrayOfValues) {
2.1123 + // If you passed zero args, we destroy everything
2.1124 + if (arrayOfValues === undefined)
2.1125 + return this['destroy'](function() { return true });
2.1126 +
2.1127 + // If you passed an arg, we interpret it as an array of entries to destroy
2.1128 + if (!arrayOfValues)
2.1129 + return [];
2.1130 + return this['destroy'](function (value) {
2.1131 + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
2.1132 + });
2.1133 + },
2.1134 +
2.1135 + 'indexOf': function (item) {
2.1136 + var underlyingArray = this();
2.1137 + return ko.utils.arrayIndexOf(underlyingArray, item);
2.1138 + },
2.1139 +
2.1140 + 'replace': function(oldItem, newItem) {
2.1141 + var index = this['indexOf'](oldItem);
2.1142 + if (index >= 0) {
2.1143 + this.valueWillMutate();
2.1144 + this.peek()[index] = newItem;
2.1145 + this.valueHasMutated();
2.1146 + }
2.1147 + }
2.1148 +}
2.1149 +
2.1150 +// Populate ko.observableArray.fn with read/write functions from native arrays
2.1151 +// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
2.1152 +// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
2.1153 +ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
2.1154 + ko.observableArray['fn'][methodName] = function () {
2.1155 + // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
2.1156 + // (for consistency with mutating regular observables)
2.1157 + var underlyingArray = this.peek();
2.1158 + this.valueWillMutate();
2.1159 + var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
2.1160 + this.valueHasMutated();
2.1161 + return methodCallResult;
2.1162 + };
2.1163 +});
2.1164 +
2.1165 +// Populate ko.observableArray.fn with read-only functions from native arrays
2.1166 +ko.utils.arrayForEach(["slice"], function (methodName) {
2.1167 + ko.observableArray['fn'][methodName] = function () {
2.1168 + var underlyingArray = this();
2.1169 + return underlyingArray[methodName].apply(underlyingArray, arguments);
2.1170 + };
2.1171 +});
2.1172 +
2.1173 +ko.exportSymbol('observableArray', ko.observableArray);
2.1174 +ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
2.1175 + var _latestValue,
2.1176 + _hasBeenEvaluated = false,
2.1177 + _isBeingEvaluated = false,
2.1178 + readFunction = evaluatorFunctionOrOptions;
2.1179 +
2.1180 + if (readFunction && typeof readFunction == "object") {
2.1181 + // Single-parameter syntax - everything is on this "options" param
2.1182 + options = readFunction;
2.1183 + readFunction = options["read"];
2.1184 + } else {
2.1185 + // Multi-parameter syntax - construct the options according to the params passed
2.1186 + options = options || {};
2.1187 + if (!readFunction)
2.1188 + readFunction = options["read"];
2.1189 + }
2.1190 + if (typeof readFunction != "function")
2.1191 + throw new Error("Pass a function that returns the value of the ko.computed");
2.1192 +
2.1193 + function addSubscriptionToDependency(subscribable) {
2.1194 + _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync));
2.1195 + }
2.1196 +
2.1197 + function disposeAllSubscriptionsToDependencies() {
2.1198 + ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
2.1199 + subscription.dispose();
2.1200 + });
2.1201 + _subscriptionsToDependencies = [];
2.1202 + }
2.1203 +
2.1204 + function evaluatePossiblyAsync() {
2.1205 + var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
2.1206 + if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
2.1207 + clearTimeout(evaluationTimeoutInstance);
2.1208 + evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
2.1209 + } else
2.1210 + evaluateImmediate();
2.1211 + }
2.1212 +
2.1213 + function evaluateImmediate() {
2.1214 + if (_isBeingEvaluated) {
2.1215 + // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
2.1216 + // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
2.1217 + // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
2.1218 + // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
2.1219 + return;
2.1220 + }
2.1221 +
2.1222 + // Don't dispose on first evaluation, because the "disposeWhen" callback might
2.1223 + // e.g., dispose when the associated DOM element isn't in the doc, and it's not
2.1224 + // going to be in the doc until *after* the first evaluation
2.1225 + if (_hasBeenEvaluated && disposeWhen()) {
2.1226 + dispose();
2.1227 + return;
2.1228 + }
2.1229 +
2.1230 + _isBeingEvaluated = true;
2.1231 + try {
2.1232 + // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
2.1233 + // Then, during evaluation, we cross off any that are in fact still being used.
2.1234 + var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
2.1235 +
2.1236 + ko.dependencyDetection.begin(function(subscribable) {
2.1237 + var inOld;
2.1238 + if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
2.1239 + disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
2.1240 + else
2.1241 + addSubscriptionToDependency(subscribable); // Brand new subscription - add it
2.1242 + });
2.1243 +
2.1244 + var newValue = readFunction.call(evaluatorFunctionTarget);
2.1245 +
2.1246 + // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
2.1247 + for (var i = disposalCandidates.length - 1; i >= 0; i--) {
2.1248 + if (disposalCandidates[i])
2.1249 + _subscriptionsToDependencies.splice(i, 1)[0].dispose();
2.1250 + }
2.1251 + _hasBeenEvaluated = true;
2.1252 +
2.1253 + dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
2.1254 + _latestValue = newValue;
2.1255 + if (DEBUG) dependentObservable._latestValue = _latestValue;
2.1256 + } finally {
2.1257 + ko.dependencyDetection.end();
2.1258 + }
2.1259 +
2.1260 + dependentObservable["notifySubscribers"](_latestValue);
2.1261 + _isBeingEvaluated = false;
2.1262 + if (!_subscriptionsToDependencies.length)
2.1263 + dispose();
2.1264 + }
2.1265 +
2.1266 + function dependentObservable() {
2.1267 + if (arguments.length > 0) {
2.1268 + if (typeof writeFunction === "function") {
2.1269 + // Writing a value
2.1270 + writeFunction.apply(evaluatorFunctionTarget, arguments);
2.1271 + } else {
2.1272 + 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.");
2.1273 + }
2.1274 + return this; // Permits chained assignments
2.1275 + } else {
2.1276 + // Reading the value
2.1277 + if (!_hasBeenEvaluated)
2.1278 + evaluateImmediate();
2.1279 + ko.dependencyDetection.registerDependency(dependentObservable);
2.1280 + return _latestValue;
2.1281 + }
2.1282 + }
2.1283 +
2.1284 + function peek() {
2.1285 + if (!_hasBeenEvaluated)
2.1286 + evaluateImmediate();
2.1287 + return _latestValue;
2.1288 + }
2.1289 +
2.1290 + function isActive() {
2.1291 + return !_hasBeenEvaluated || _subscriptionsToDependencies.length > 0;
2.1292 + }
2.1293 +
2.1294 + // By here, "options" is always non-null
2.1295 + var writeFunction = options["write"],
2.1296 + disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
2.1297 + disposeWhen = options["disposeWhen"] || options.disposeWhen || function() { return false; },
2.1298 + dispose = disposeAllSubscriptionsToDependencies,
2.1299 + _subscriptionsToDependencies = [],
2.1300 + evaluationTimeoutInstance = null;
2.1301 +
2.1302 + if (!evaluatorFunctionTarget)
2.1303 + evaluatorFunctionTarget = options["owner"];
2.1304 +
2.1305 + dependentObservable.peek = peek;
2.1306 + dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
2.1307 + dependentObservable.hasWriteFunction = typeof options["write"] === "function";
2.1308 + dependentObservable.dispose = function () { dispose(); };
2.1309 + dependentObservable.isActive = isActive;
2.1310 +
2.1311 + ko.subscribable.call(dependentObservable);
2.1312 + ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
2.1313 +
2.1314 + ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
2.1315 + ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
2.1316 + ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
2.1317 + ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
2.1318 +
2.1319 + // Evaluate, unless deferEvaluation is true
2.1320 + if (options['deferEvaluation'] !== true)
2.1321 + evaluateImmediate();
2.1322 +
2.1323 + // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values.
2.1324 + // But skip if isActive is false (there will never be any dependencies to dispose).
2.1325 + // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
2.1326 + // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
2.1327 + if (disposeWhenNodeIsRemoved && isActive()) {
2.1328 + dispose = function() {
2.1329 + ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
2.1330 + disposeAllSubscriptionsToDependencies();
2.1331 + };
2.1332 + ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
2.1333 + var existingDisposeWhenFunction = disposeWhen;
2.1334 + disposeWhen = function () {
2.1335 + return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
2.1336 + }
2.1337 + }
2.1338 +
2.1339 + return dependentObservable;
2.1340 +};
2.1341 +
2.1342 +ko.isComputed = function(instance) {
2.1343 + return ko.hasPrototype(instance, ko.dependentObservable);
2.1344 +};
2.1345 +
2.1346 +var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
2.1347 +ko.dependentObservable[protoProp] = ko.observable;
2.1348 +
2.1349 +ko.dependentObservable['fn'] = {};
2.1350 +ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
2.1351 +
2.1352 +ko.exportSymbol('dependentObservable', ko.dependentObservable);
2.1353 +ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
2.1354 +ko.exportSymbol('isComputed', ko.isComputed);
2.1355 +
2.1356 +(function() {
2.1357 + var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
2.1358 +
2.1359 + ko.toJS = function(rootObject) {
2.1360 + if (arguments.length == 0)
2.1361 + throw new Error("When calling ko.toJS, pass the object you want to convert.");
2.1362 +
2.1363 + // We just unwrap everything at every level in the object graph
2.1364 + return mapJsObjectGraph(rootObject, function(valueToMap) {
2.1365 + // Loop because an observable's value might in turn be another observable wrapper
2.1366 + for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
2.1367 + valueToMap = valueToMap();
2.1368 + return valueToMap;
2.1369 + });
2.1370 + };
2.1371 +
2.1372 + ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
2.1373 + var plainJavaScriptObject = ko.toJS(rootObject);
2.1374 + return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
2.1375 + };
2.1376 +
2.1377 + function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
2.1378 + visitedObjects = visitedObjects || new objectLookup();
2.1379 +
2.1380 + rootObject = mapInputCallback(rootObject);
2.1381 + var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
2.1382 + if (!canHaveProperties)
2.1383 + return rootObject;
2.1384 +
2.1385 + var outputProperties = rootObject instanceof Array ? [] : {};
2.1386 + visitedObjects.save(rootObject, outputProperties);
2.1387 +
2.1388 + visitPropertiesOrArrayEntries(rootObject, function(indexer) {
2.1389 + var propertyValue = mapInputCallback(rootObject[indexer]);
2.1390 +
2.1391 + switch (typeof propertyValue) {
2.1392 + case "boolean":
2.1393 + case "number":
2.1394 + case "string":
2.1395 + case "function":
2.1396 + outputProperties[indexer] = propertyValue;
2.1397 + break;
2.1398 + case "object":
2.1399 + case "undefined":
2.1400 + var previouslyMappedValue = visitedObjects.get(propertyValue);
2.1401 + outputProperties[indexer] = (previouslyMappedValue !== undefined)
2.1402 + ? previouslyMappedValue
2.1403 + : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
2.1404 + break;
2.1405 + }
2.1406 + });
2.1407 +
2.1408 + return outputProperties;
2.1409 + }
2.1410 +
2.1411 + function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
2.1412 + if (rootObject instanceof Array) {
2.1413 + for (var i = 0; i < rootObject.length; i++)
2.1414 + visitorCallback(i);
2.1415 +
2.1416 + // For arrays, also respect toJSON property for custom mappings (fixes #278)
2.1417 + if (typeof rootObject['toJSON'] == 'function')
2.1418 + visitorCallback('toJSON');
2.1419 + } else {
2.1420 + for (var propertyName in rootObject)
2.1421 + visitorCallback(propertyName);
2.1422 + }
2.1423 + };
2.1424 +
2.1425 + function objectLookup() {
2.1426 + var keys = [];
2.1427 + var values = [];
2.1428 + this.save = function(key, value) {
2.1429 + var existingIndex = ko.utils.arrayIndexOf(keys, key);
2.1430 + if (existingIndex >= 0)
2.1431 + values[existingIndex] = value;
2.1432 + else {
2.1433 + keys.push(key);
2.1434 + values.push(value);
2.1435 + }
2.1436 + };
2.1437 + this.get = function(key) {
2.1438 + var existingIndex = ko.utils.arrayIndexOf(keys, key);
2.1439 + return (existingIndex >= 0) ? values[existingIndex] : undefined;
2.1440 + };
2.1441 + };
2.1442 +})();
2.1443 +
2.1444 +ko.exportSymbol('toJS', ko.toJS);
2.1445 +ko.exportSymbol('toJSON', ko.toJSON);
2.1446 +(function () {
2.1447 + var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
2.1448 +
2.1449 + // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
2.1450 + // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
2.1451 + // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
2.1452 + ko.selectExtensions = {
2.1453 + readValue : function(element) {
2.1454 + switch (ko.utils.tagNameLower(element)) {
2.1455 + case 'option':
2.1456 + if (element[hasDomDataExpandoProperty] === true)
2.1457 + return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
2.1458 + return ko.utils.ieVersion <= 7
2.1459 + ? (element.getAttributeNode('value').specified ? element.value : element.text)
2.1460 + : element.value;
2.1461 + case 'select':
2.1462 + return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
2.1463 + default:
2.1464 + return element.value;
2.1465 + }
2.1466 + },
2.1467 +
2.1468 + writeValue: function(element, value) {
2.1469 + switch (ko.utils.tagNameLower(element)) {
2.1470 + case 'option':
2.1471 + switch(typeof value) {
2.1472 + case "string":
2.1473 + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
2.1474 + if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
2.1475 + delete element[hasDomDataExpandoProperty];
2.1476 + }
2.1477 + element.value = value;
2.1478 + break;
2.1479 + default:
2.1480 + // Store arbitrary object using DomData
2.1481 + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
2.1482 + element[hasDomDataExpandoProperty] = true;
2.1483 +
2.1484 + // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
2.1485 + element.value = typeof value === "number" ? value : "";
2.1486 + break;
2.1487 + }
2.1488 + break;
2.1489 + case 'select':
2.1490 + for (var i = element.options.length - 1; i >= 0; i--) {
2.1491 + if (ko.selectExtensions.readValue(element.options[i]) == value) {
2.1492 + element.selectedIndex = i;
2.1493 + break;
2.1494 + }
2.1495 + }
2.1496 + break;
2.1497 + default:
2.1498 + if ((value === null) || (value === undefined))
2.1499 + value = "";
2.1500 + element.value = value;
2.1501 + break;
2.1502 + }
2.1503 + }
2.1504 + };
2.1505 +})();
2.1506 +
2.1507 +ko.exportSymbol('selectExtensions', ko.selectExtensions);
2.1508 +ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
2.1509 +ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
2.1510 +ko.expressionRewriting = (function () {
2.1511 + var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
2.1512 + var javaScriptReservedWords = ["true", "false"];
2.1513 +
2.1514 + // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
2.1515 + // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
2.1516 + var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
2.1517 +
2.1518 + function restoreTokens(string, tokens) {
2.1519 + var prevValue = null;
2.1520 + while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
2.1521 + prevValue = string;
2.1522 + string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
2.1523 + return tokens[tokenIndex];
2.1524 + });
2.1525 + }
2.1526 + return string;
2.1527 + }
2.1528 +
2.1529 + function getWriteableValue(expression) {
2.1530 + if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
2.1531 + return false;
2.1532 + var match = expression.match(javaScriptAssignmentTarget);
2.1533 + return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
2.1534 + }
2.1535 +
2.1536 + function ensureQuoted(key) {
2.1537 + var trimmedKey = ko.utils.stringTrim(key);
2.1538 + switch (trimmedKey.length && trimmedKey.charAt(0)) {
2.1539 + case "'":
2.1540 + case '"':
2.1541 + return key;
2.1542 + default:
2.1543 + return "'" + trimmedKey + "'";
2.1544 + }
2.1545 + }
2.1546 +
2.1547 + return {
2.1548 + bindingRewriteValidators: [],
2.1549 +
2.1550 + parseObjectLiteral: function(objectLiteralString) {
2.1551 + // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
2.1552 + // that is sufficient just to split an object literal string into a set of top-level key-value pairs
2.1553 +
2.1554 + var str = ko.utils.stringTrim(objectLiteralString);
2.1555 + if (str.length < 3)
2.1556 + return [];
2.1557 + if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
2.1558 + str = str.substring(1, str.length - 1);
2.1559 +
2.1560 + // Pull out any string literals and regex literals
2.1561 + var tokens = [];
2.1562 + var tokenStart = null, tokenEndChar;
2.1563 + for (var position = 0; position < str.length; position++) {
2.1564 + var c = str.charAt(position);
2.1565 + if (tokenStart === null) {
2.1566 + switch (c) {
2.1567 + case '"':
2.1568 + case "'":
2.1569 + case "/":
2.1570 + tokenStart = position;
2.1571 + tokenEndChar = c;
2.1572 + break;
2.1573 + }
2.1574 + } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
2.1575 + var token = str.substring(tokenStart, position + 1);
2.1576 + tokens.push(token);
2.1577 + var replacement = "@ko_token_" + (tokens.length - 1) + "@";
2.1578 + str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
2.1579 + position -= (token.length - replacement.length);
2.1580 + tokenStart = null;
2.1581 + }
2.1582 + }
2.1583 +
2.1584 + // Next pull out balanced paren, brace, and bracket blocks
2.1585 + tokenStart = null;
2.1586 + tokenEndChar = null;
2.1587 + var tokenDepth = 0, tokenStartChar = null;
2.1588 + for (var position = 0; position < str.length; position++) {
2.1589 + var c = str.charAt(position);
2.1590 + if (tokenStart === null) {
2.1591 + switch (c) {
2.1592 + case "{": tokenStart = position; tokenStartChar = c;
2.1593 + tokenEndChar = "}";
2.1594 + break;
2.1595 + case "(": tokenStart = position; tokenStartChar = c;
2.1596 + tokenEndChar = ")";
2.1597 + break;
2.1598 + case "[": tokenStart = position; tokenStartChar = c;
2.1599 + tokenEndChar = "]";
2.1600 + break;
2.1601 + }
2.1602 + }
2.1603 +
2.1604 + if (c === tokenStartChar)
2.1605 + tokenDepth++;
2.1606 + else if (c === tokenEndChar) {
2.1607 + tokenDepth--;
2.1608 + if (tokenDepth === 0) {
2.1609 + var token = str.substring(tokenStart, position + 1);
2.1610 + tokens.push(token);
2.1611 + var replacement = "@ko_token_" + (tokens.length - 1) + "@";
2.1612 + str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
2.1613 + position -= (token.length - replacement.length);
2.1614 + tokenStart = null;
2.1615 + }
2.1616 + }
2.1617 + }
2.1618 +
2.1619 + // Now we can safely split on commas to get the key/value pairs
2.1620 + var result = [];
2.1621 + var keyValuePairs = str.split(",");
2.1622 + for (var i = 0, j = keyValuePairs.length; i < j; i++) {
2.1623 + var pair = keyValuePairs[i];
2.1624 + var colonPos = pair.indexOf(":");
2.1625 + if ((colonPos > 0) && (colonPos < pair.length - 1)) {
2.1626 + var key = pair.substring(0, colonPos);
2.1627 + var value = pair.substring(colonPos + 1);
2.1628 + result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
2.1629 + } else {
2.1630 + result.push({ 'unknown': restoreTokens(pair, tokens) });
2.1631 + }
2.1632 + }
2.1633 + return result;
2.1634 + },
2.1635 +
2.1636 + preProcessBindings: function (objectLiteralStringOrKeyValueArray) {
2.1637 + var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
2.1638 + ? ko.expressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
2.1639 + : objectLiteralStringOrKeyValueArray;
2.1640 + var resultStrings = [], propertyAccessorResultStrings = [];
2.1641 +
2.1642 + var keyValueEntry;
2.1643 + for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
2.1644 + if (resultStrings.length > 0)
2.1645 + resultStrings.push(",");
2.1646 +
2.1647 + if (keyValueEntry['key']) {
2.1648 + var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
2.1649 + resultStrings.push(quotedKey);
2.1650 + resultStrings.push(":");
2.1651 + resultStrings.push(val);
2.1652 +
2.1653 + if (val = getWriteableValue(ko.utils.stringTrim(val))) {
2.1654 + if (propertyAccessorResultStrings.length > 0)
2.1655 + propertyAccessorResultStrings.push(", ");
2.1656 + propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
2.1657 + }
2.1658 + } else if (keyValueEntry['unknown']) {
2.1659 + resultStrings.push(keyValueEntry['unknown']);
2.1660 + }
2.1661 + }
2.1662 +
2.1663 + var combinedResult = resultStrings.join("");
2.1664 + if (propertyAccessorResultStrings.length > 0) {
2.1665 + var allPropertyAccessors = propertyAccessorResultStrings.join("");
2.1666 + combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
2.1667 + }
2.1668 +
2.1669 + return combinedResult;
2.1670 + },
2.1671 +
2.1672 + keyValueArrayContainsKey: function(keyValueArray, key) {
2.1673 + for (var i = 0; i < keyValueArray.length; i++)
2.1674 + if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
2.1675 + return true;
2.1676 + return false;
2.1677 + },
2.1678 +
2.1679 + // Internal, private KO utility for updating model properties from within bindings
2.1680 + // property: If the property being updated is (or might be) an observable, pass it here
2.1681 + // If it turns out to be a writable observable, it will be written to directly
2.1682 + // allBindingsAccessor: All bindings in the current execution context.
2.1683 + // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
2.1684 + // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
2.1685 + // value: The value to be written
2.1686 + // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
2.1687 + // it is !== existing value on that writable observable
2.1688 + writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
2.1689 + if (!property || !ko.isWriteableObservable(property)) {
2.1690 + var propWriters = allBindingsAccessor()['_ko_property_writers'];
2.1691 + if (propWriters && propWriters[key])
2.1692 + propWriters[key](value);
2.1693 + } else if (!checkIfDifferent || property.peek() !== value) {
2.1694 + property(value);
2.1695 + }
2.1696 + }
2.1697 + };
2.1698 +})();
2.1699 +
2.1700 +ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
2.1701 +ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
2.1702 +ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
2.1703 +ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
2.1704 +
2.1705 +// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
2.1706 +// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
2.1707 +ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
2.1708 +ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);(function() {
2.1709 + // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
2.1710 + // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
2.1711 + // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
2.1712 + // of that virtual hierarchy
2.1713 + //
2.1714 + // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
2.1715 + // without having to scatter special cases all over the binding and templating code.
2.1716 +
2.1717 + // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
2.1718 + // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
2.1719 + // So, use node.text where available, and node.nodeValue elsewhere
2.1720 + var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
2.1721 +
2.1722 + var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*-->$/ : /^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/;
2.1723 + var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
2.1724 + var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
2.1725 +
2.1726 + function isStartComment(node) {
2.1727 + return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
2.1728 + }
2.1729 +
2.1730 + function isEndComment(node) {
2.1731 + return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
2.1732 + }
2.1733 +
2.1734 + function getVirtualChildren(startComment, allowUnbalanced) {
2.1735 + var currentNode = startComment;
2.1736 + var depth = 1;
2.1737 + var children = [];
2.1738 + while (currentNode = currentNode.nextSibling) {
2.1739 + if (isEndComment(currentNode)) {
2.1740 + depth--;
2.1741 + if (depth === 0)
2.1742 + return children;
2.1743 + }
2.1744 +
2.1745 + children.push(currentNode);
2.1746 +
2.1747 + if (isStartComment(currentNode))
2.1748 + depth++;
2.1749 + }
2.1750 + if (!allowUnbalanced)
2.1751 + throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
2.1752 + return null;
2.1753 + }
2.1754 +
2.1755 + function getMatchingEndComment(startComment, allowUnbalanced) {
2.1756 + var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
2.1757 + if (allVirtualChildren) {
2.1758 + if (allVirtualChildren.length > 0)
2.1759 + return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
2.1760 + return startComment.nextSibling;
2.1761 + } else
2.1762 + return null; // Must have no matching end comment, and allowUnbalanced is true
2.1763 + }
2.1764 +
2.1765 + function getUnbalancedChildTags(node) {
2.1766 + // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
2.1767 + // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
2.1768 + var childNode = node.firstChild, captureRemaining = null;
2.1769 + if (childNode) {
2.1770 + do {
2.1771 + if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
2.1772 + captureRemaining.push(childNode);
2.1773 + else if (isStartComment(childNode)) {
2.1774 + var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
2.1775 + if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
2.1776 + childNode = matchingEndComment;
2.1777 + else
2.1778 + captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
2.1779 + } else if (isEndComment(childNode)) {
2.1780 + captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
2.1781 + }
2.1782 + } while (childNode = childNode.nextSibling);
2.1783 + }
2.1784 + return captureRemaining;
2.1785 + }
2.1786 +
2.1787 + ko.virtualElements = {
2.1788 + allowedBindings: {},
2.1789 +
2.1790 + childNodes: function(node) {
2.1791 + return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
2.1792 + },
2.1793 +
2.1794 + emptyNode: function(node) {
2.1795 + if (!isStartComment(node))
2.1796 + ko.utils.emptyDomNode(node);
2.1797 + else {
2.1798 + var virtualChildren = ko.virtualElements.childNodes(node);
2.1799 + for (var i = 0, j = virtualChildren.length; i < j; i++)
2.1800 + ko.removeNode(virtualChildren[i]);
2.1801 + }
2.1802 + },
2.1803 +
2.1804 + setDomNodeChildren: function(node, childNodes) {
2.1805 + if (!isStartComment(node))
2.1806 + ko.utils.setDomNodeChildren(node, childNodes);
2.1807 + else {
2.1808 + ko.virtualElements.emptyNode(node);
2.1809 + var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
2.1810 + for (var i = 0, j = childNodes.length; i < j; i++)
2.1811 + endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
2.1812 + }
2.1813 + },
2.1814 +
2.1815 + prepend: function(containerNode, nodeToPrepend) {
2.1816 + if (!isStartComment(containerNode)) {
2.1817 + if (containerNode.firstChild)
2.1818 + containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
2.1819 + else
2.1820 + containerNode.appendChild(nodeToPrepend);
2.1821 + } else {
2.1822 + // Start comments must always have a parent and at least one following sibling (the end comment)
2.1823 + containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
2.1824 + }
2.1825 + },
2.1826 +
2.1827 + insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
2.1828 + if (!insertAfterNode) {
2.1829 + ko.virtualElements.prepend(containerNode, nodeToInsert);
2.1830 + } else if (!isStartComment(containerNode)) {
2.1831 + // Insert after insertion point
2.1832 + if (insertAfterNode.nextSibling)
2.1833 + containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
2.1834 + else
2.1835 + containerNode.appendChild(nodeToInsert);
2.1836 + } else {
2.1837 + // Children of start comments must always have a parent and at least one following sibling (the end comment)
2.1838 + containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
2.1839 + }
2.1840 + },
2.1841 +
2.1842 + firstChild: function(node) {
2.1843 + if (!isStartComment(node))
2.1844 + return node.firstChild;
2.1845 + if (!node.nextSibling || isEndComment(node.nextSibling))
2.1846 + return null;
2.1847 + return node.nextSibling;
2.1848 + },
2.1849 +
2.1850 + nextSibling: function(node) {
2.1851 + if (isStartComment(node))
2.1852 + node = getMatchingEndComment(node);
2.1853 + if (node.nextSibling && isEndComment(node.nextSibling))
2.1854 + return null;
2.1855 + return node.nextSibling;
2.1856 + },
2.1857 +
2.1858 + virtualNodeBindingValue: function(node) {
2.1859 + var regexMatch = isStartComment(node);
2.1860 + return regexMatch ? regexMatch[1] : null;
2.1861 + },
2.1862 +
2.1863 + normaliseVirtualElementDomStructure: function(elementVerified) {
2.1864 + // Workaround for https://github.com/SteveSanderson/knockout/issues/155
2.1865 + // (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
2.1866 + // that are direct descendants of <ul> into the preceding <li>)
2.1867 + if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
2.1868 + return;
2.1869 +
2.1870 + // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
2.1871 + // must be intended to appear *after* that child, so move them there.
2.1872 + var childNode = elementVerified.firstChild;
2.1873 + if (childNode) {
2.1874 + do {
2.1875 + if (childNode.nodeType === 1) {
2.1876 + var unbalancedTags = getUnbalancedChildTags(childNode);
2.1877 + if (unbalancedTags) {
2.1878 + // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
2.1879 + var nodeToInsertBefore = childNode.nextSibling;
2.1880 + for (var i = 0; i < unbalancedTags.length; i++) {
2.1881 + if (nodeToInsertBefore)
2.1882 + elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
2.1883 + else
2.1884 + elementVerified.appendChild(unbalancedTags[i]);
2.1885 + }
2.1886 + }
2.1887 + }
2.1888 + } while (childNode = childNode.nextSibling);
2.1889 + }
2.1890 + }
2.1891 + };
2.1892 +})();
2.1893 +ko.exportSymbol('virtualElements', ko.virtualElements);
2.1894 +ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
2.1895 +ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
2.1896 +//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
2.1897 +ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
2.1898 +//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
2.1899 +ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
2.1900 +ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
2.1901 +(function() {
2.1902 + var defaultBindingAttributeName = "data-bind";
2.1903 +
2.1904 + ko.bindingProvider = function() {
2.1905 + this.bindingCache = {};
2.1906 + };
2.1907 +
2.1908 + ko.utils.extend(ko.bindingProvider.prototype, {
2.1909 + 'nodeHasBindings': function(node) {
2.1910 + switch (node.nodeType) {
2.1911 + case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
2.1912 + case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
2.1913 + default: return false;
2.1914 + }
2.1915 + },
2.1916 +
2.1917 + 'getBindings': function(node, bindingContext) {
2.1918 + var bindingsString = this['getBindingsString'](node, bindingContext);
2.1919 + return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
2.1920 + },
2.1921 +
2.1922 + // The following function is only used internally by this default provider.
2.1923 + // It's not part of the interface definition for a general binding provider.
2.1924 + 'getBindingsString': function(node, bindingContext) {
2.1925 + switch (node.nodeType) {
2.1926 + case 1: return node.getAttribute(defaultBindingAttributeName); // Element
2.1927 + case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
2.1928 + default: return null;
2.1929 + }
2.1930 + },
2.1931 +
2.1932 + // The following function is only used internally by this default provider.
2.1933 + // It's not part of the interface definition for a general binding provider.
2.1934 + 'parseBindingsString': function(bindingsString, bindingContext, node) {
2.1935 + try {
2.1936 + var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
2.1937 + return bindingFunction(bindingContext, node);
2.1938 + } catch (ex) {
2.1939 + throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
2.1940 + }
2.1941 + }
2.1942 + });
2.1943 +
2.1944 + ko.bindingProvider['instance'] = new ko.bindingProvider();
2.1945 +
2.1946 + function createBindingsStringEvaluatorViaCache(bindingsString, cache) {
2.1947 + var cacheKey = bindingsString;
2.1948 + return cache[cacheKey]
2.1949 + || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString));
2.1950 + }
2.1951 +
2.1952 + function createBindingsStringEvaluator(bindingsString) {
2.1953 + // Build the source for a function that evaluates "expression"
2.1954 + // For each scope variable, add an extra level of "with" nesting
2.1955 + // Example result: with(sc1) { with(sc0) { return (expression) } }
2.1956 + var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString),
2.1957 + functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
2.1958 + return new Function("$context", "$element", functionBody);
2.1959 + }
2.1960 +})();
2.1961 +
2.1962 +ko.exportSymbol('bindingProvider', ko.bindingProvider);
2.1963 +(function () {
2.1964 + ko.bindingHandlers = {};
2.1965 +
2.1966 + ko.bindingContext = function(dataItem, parentBindingContext, dataItemAlias) {
2.1967 + if (parentBindingContext) {
2.1968 + ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
2.1969 + this['$parentContext'] = parentBindingContext;
2.1970 + this['$parent'] = parentBindingContext['$data'];
2.1971 + this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
2.1972 + this['$parents'].unshift(this['$parent']);
2.1973 + } else {
2.1974 + this['$parents'] = [];
2.1975 + this['$root'] = dataItem;
2.1976 + // Export 'ko' in the binding context so it will be available in bindings and templates
2.1977 + // even if 'ko' isn't exported as a global, such as when using an AMD loader.
2.1978 + // See https://github.com/SteveSanderson/knockout/issues/490
2.1979 + this['ko'] = ko;
2.1980 + }
2.1981 + this['$data'] = dataItem;
2.1982 + if (dataItemAlias)
2.1983 + this[dataItemAlias] = dataItem;
2.1984 + }
2.1985 + ko.bindingContext.prototype['createChildContext'] = function (dataItem, dataItemAlias) {
2.1986 + return new ko.bindingContext(dataItem, this, dataItemAlias);
2.1987 + };
2.1988 + ko.bindingContext.prototype['extend'] = function(properties) {
2.1989 + var clone = ko.utils.extend(new ko.bindingContext(), this);
2.1990 + return ko.utils.extend(clone, properties);
2.1991 + };
2.1992 +
2.1993 + function validateThatBindingIsAllowedForVirtualElements(bindingName) {
2.1994 + var validator = ko.virtualElements.allowedBindings[bindingName];
2.1995 + if (!validator)
2.1996 + throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
2.1997 + }
2.1998 +
2.1999 + function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
2.2000 + var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
2.2001 + while (currentChild = nextInQueue) {
2.2002 + // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
2.2003 + nextInQueue = ko.virtualElements.nextSibling(currentChild);
2.2004 + applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
2.2005 + }
2.2006 + }
2.2007 +
2.2008 + function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
2.2009 + var shouldBindDescendants = true;
2.2010 +
2.2011 + // Perf optimisation: Apply bindings only if...
2.2012 + // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
2.2013 + // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
2.2014 + // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
2.2015 + var isElement = (nodeVerified.nodeType === 1);
2.2016 + if (isElement) // Workaround IE <= 8 HTML parsing weirdness
2.2017 + ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
2.2018 +
2.2019 + var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
2.2020 + || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
2.2021 + if (shouldApplyBindings)
2.2022 + shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
2.2023 +
2.2024 + if (shouldBindDescendants) {
2.2025 + // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
2.2026 + // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
2.2027 + // hence bindingContextsMayDifferFromDomParentElement is false
2.2028 + // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
2.2029 + // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
2.2030 + // hence bindingContextsMayDifferFromDomParentElement is true
2.2031 + applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
2.2032 + }
2.2033 + }
2.2034 +
2.2035 + function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
2.2036 + // Need to be sure that inits are only run once, and updates never run until all the inits have been run
2.2037 + var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
2.2038 +
2.2039 + // Each time the dependentObservable is evaluated (after data changes),
2.2040 + // the binding attribute is reparsed so that it can pick out the correct
2.2041 + // model properties in the context of the changed data.
2.2042 + // DOM event callbacks need to be able to access this changed data,
2.2043 + // so we need a single parsedBindings variable (shared by all callbacks
2.2044 + // associated with this node's bindings) that all the closures can access.
2.2045 + var parsedBindings;
2.2046 + function makeValueAccessor(bindingKey) {
2.2047 + return function () { return parsedBindings[bindingKey] }
2.2048 + }
2.2049 + function parsedBindingsAccessor() {
2.2050 + return parsedBindings;
2.2051 + }
2.2052 +
2.2053 + var bindingHandlerThatControlsDescendantBindings;
2.2054 + ko.dependentObservable(
2.2055 + function () {
2.2056 + // Ensure we have a nonnull binding context to work with
2.2057 + var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
2.2058 + ? viewModelOrBindingContext
2.2059 + : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
2.2060 + var viewModel = bindingContextInstance['$data'];
2.2061 +
2.2062 + // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
2.2063 + // we can easily recover it just by scanning up the node's ancestors in the DOM
2.2064 + // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
2.2065 + if (bindingContextMayDifferFromDomParentElement)
2.2066 + ko.storedBindingContextForNode(node, bindingContextInstance);
2.2067 +
2.2068 + // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
2.2069 + var evaluatedBindings = (typeof bindings == "function") ? bindings(bindingContextInstance, node) : bindings;
2.2070 + parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
2.2071 +
2.2072 + if (parsedBindings) {
2.2073 + // First run all the inits, so bindings can register for notification on changes
2.2074 + if (initPhase === 0) {
2.2075 + initPhase = 1;
2.2076 + for (var bindingKey in parsedBindings) {
2.2077 + var binding = ko.bindingHandlers[bindingKey];
2.2078 + if (binding && node.nodeType === 8)
2.2079 + validateThatBindingIsAllowedForVirtualElements(bindingKey);
2.2080 +
2.2081 + if (binding && typeof binding["init"] == "function") {
2.2082 + var handlerInitFn = binding["init"];
2.2083 + var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
2.2084 +
2.2085 + // If this binding handler claims to control descendant bindings, make a note of this
2.2086 + if (initResult && initResult['controlsDescendantBindings']) {
2.2087 + if (bindingHandlerThatControlsDescendantBindings !== undefined)
2.2088 + 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.");
2.2089 + bindingHandlerThatControlsDescendantBindings = bindingKey;
2.2090 + }
2.2091 + }
2.2092 + }
2.2093 + initPhase = 2;
2.2094 + }
2.2095 +
2.2096 + // ... then run all the updates, which might trigger changes even on the first evaluation
2.2097 + if (initPhase === 2) {
2.2098 + for (var bindingKey in parsedBindings) {
2.2099 + var binding = ko.bindingHandlers[bindingKey];
2.2100 + if (binding && typeof binding["update"] == "function") {
2.2101 + var handlerUpdateFn = binding["update"];
2.2102 + handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
2.2103 + }
2.2104 + }
2.2105 + }
2.2106 + }
2.2107 + },
2.2108 + null,
2.2109 + { disposeWhenNodeIsRemoved : node }
2.2110 + );
2.2111 +
2.2112 + return {
2.2113 + shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
2.2114 + };
2.2115 + };
2.2116 +
2.2117 + var storedBindingContextDomDataKey = "__ko_bindingContext__";
2.2118 + ko.storedBindingContextForNode = function (node, bindingContext) {
2.2119 + if (arguments.length == 2)
2.2120 + ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
2.2121 + else
2.2122 + return ko.utils.domData.get(node, storedBindingContextDomDataKey);
2.2123 + }
2.2124 +
2.2125 + ko.applyBindingsToNode = function (node, bindings, viewModel) {
2.2126 + if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
2.2127 + ko.virtualElements.normaliseVirtualElementDomStructure(node);
2.2128 + return applyBindingsToNodeInternal(node, bindings, viewModel, true);
2.2129 + };
2.2130 +
2.2131 + ko.applyBindingsToDescendants = function(viewModel, rootNode) {
2.2132 + if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
2.2133 + applyBindingsToDescendantsInternal(viewModel, rootNode, true);
2.2134 + };
2.2135 +
2.2136 + ko.applyBindings = function (viewModel, rootNode) {
2.2137 + if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
2.2138 + throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
2.2139 + rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
2.2140 +
2.2141 + applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
2.2142 + };
2.2143 +
2.2144 + // Retrieving binding context from arbitrary nodes
2.2145 + ko.contextFor = function(node) {
2.2146 + // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
2.2147 + switch (node.nodeType) {
2.2148 + case 1:
2.2149 + case 8:
2.2150 + var context = ko.storedBindingContextForNode(node);
2.2151 + if (context) return context;
2.2152 + if (node.parentNode) return ko.contextFor(node.parentNode);
2.2153 + break;
2.2154 + }
2.2155 + return undefined;
2.2156 + };
2.2157 + ko.dataFor = function(node) {
2.2158 + var context = ko.contextFor(node);
2.2159 + return context ? context['$data'] : undefined;
2.2160 + };
2.2161 +
2.2162 + ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
2.2163 + ko.exportSymbol('applyBindings', ko.applyBindings);
2.2164 + ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
2.2165 + ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
2.2166 + ko.exportSymbol('contextFor', ko.contextFor);
2.2167 + ko.exportSymbol('dataFor', ko.dataFor);
2.2168 +})();
2.2169 +var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
2.2170 +ko.bindingHandlers['attr'] = {
2.2171 + 'update': function(element, valueAccessor, allBindingsAccessor) {
2.2172 + var value = ko.utils.unwrapObservable(valueAccessor()) || {};
2.2173 + for (var attrName in value) {
2.2174 + if (typeof attrName == "string") {
2.2175 + var attrValue = ko.utils.unwrapObservable(value[attrName]);
2.2176 +
2.2177 + // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
2.2178 + // when someProp is a "no value"-like value (strictly null, false, or undefined)
2.2179 + // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
2.2180 + var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
2.2181 + if (toRemove)
2.2182 + element.removeAttribute(attrName);
2.2183 +
2.2184 + // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
2.2185 + // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
2.2186 + // but instead of figuring out the mode, we'll just set the attribute through the Javascript
2.2187 + // property for IE <= 8.
2.2188 + if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
2.2189 + attrName = attrHtmlToJavascriptMap[attrName];
2.2190 + if (toRemove)
2.2191 + element.removeAttribute(attrName);
2.2192 + else
2.2193 + element[attrName] = attrValue;
2.2194 + } else if (!toRemove) {
2.2195 + element.setAttribute(attrName, attrValue.toString());
2.2196 + }
2.2197 +
2.2198 + // Treat "name" specially - although you can think of it as an attribute, it also needs
2.2199 + // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
2.2200 + // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
2.2201 + // entirely, and there's no strong reason to allow for such casing in HTML.
2.2202 + if (attrName === "name") {
2.2203 + ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
2.2204 + }
2.2205 + }
2.2206 + }
2.2207 + }
2.2208 +};
2.2209 +ko.bindingHandlers['checked'] = {
2.2210 + 'init': function (element, valueAccessor, allBindingsAccessor) {
2.2211 + var updateHandler = function() {
2.2212 + var valueToWrite;
2.2213 + if (element.type == "checkbox") {
2.2214 + valueToWrite = element.checked;
2.2215 + } else if ((element.type == "radio") && (element.checked)) {
2.2216 + valueToWrite = element.value;
2.2217 + } else {
2.2218 + return; // "checked" binding only responds to checkboxes and selected radio buttons
2.2219 + }
2.2220 +
2.2221 + var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
2.2222 + if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
2.2223 + // For checkboxes bound to an array, we add/remove the checkbox value to that array
2.2224 + // This works for both observable and non-observable arrays
2.2225 + var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
2.2226 + if (element.checked && (existingEntryIndex < 0))
2.2227 + modelValue.push(element.value);
2.2228 + else if ((!element.checked) && (existingEntryIndex >= 0))
2.2229 + modelValue.splice(existingEntryIndex, 1);
2.2230 + } else {
2.2231 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
2.2232 + }
2.2233 + };
2.2234 + ko.utils.registerEventHandler(element, "click", updateHandler);
2.2235 +
2.2236 + // IE 6 won't allow radio buttons to be selected unless they have a name
2.2237 + if ((element.type == "radio") && !element.name)
2.2238 + ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
2.2239 + },
2.2240 + 'update': function (element, valueAccessor) {
2.2241 + var value = ko.utils.unwrapObservable(valueAccessor());
2.2242 +
2.2243 + if (element.type == "checkbox") {
2.2244 + if (value instanceof Array) {
2.2245 + // When bound to an array, the checkbox being checked represents its value being present in that array
2.2246 + element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
2.2247 + } else {
2.2248 + // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
2.2249 + element.checked = value;
2.2250 + }
2.2251 + } else if (element.type == "radio") {
2.2252 + element.checked = (element.value == value);
2.2253 + }
2.2254 + }
2.2255 +};
2.2256 +var classesWrittenByBindingKey = '__ko__cssValue';
2.2257 +ko.bindingHandlers['css'] = {
2.2258 + 'update': function (element, valueAccessor) {
2.2259 + var value = ko.utils.unwrapObservable(valueAccessor());
2.2260 + if (typeof value == "object") {
2.2261 + for (var className in value) {
2.2262 + var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
2.2263 + ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
2.2264 + }
2.2265 + } else {
2.2266 + value = String(value || ''); // Make sure we don't try to store or set a non-string value
2.2267 + ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
2.2268 + element[classesWrittenByBindingKey] = value;
2.2269 + ko.utils.toggleDomNodeCssClass(element, value, true);
2.2270 + }
2.2271 + }
2.2272 +};
2.2273 +ko.bindingHandlers['enable'] = {
2.2274 + 'update': function (element, valueAccessor) {
2.2275 + var value = ko.utils.unwrapObservable(valueAccessor());
2.2276 + if (value && element.disabled)
2.2277 + element.removeAttribute("disabled");
2.2278 + else if ((!value) && (!element.disabled))
2.2279 + element.disabled = true;
2.2280 + }
2.2281 +};
2.2282 +
2.2283 +ko.bindingHandlers['disable'] = {
2.2284 + 'update': function (element, valueAccessor) {
2.2285 + ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
2.2286 + }
2.2287 +};
2.2288 +// For certain common events (currently just 'click'), allow a simplified data-binding syntax
2.2289 +// e.g. click:handler instead of the usual full-length event:{click:handler}
2.2290 +function makeEventHandlerShortcut(eventName) {
2.2291 + ko.bindingHandlers[eventName] = {
2.2292 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
2.2293 + var newValueAccessor = function () {
2.2294 + var result = {};
2.2295 + result[eventName] = valueAccessor();
2.2296 + return result;
2.2297 + };
2.2298 + return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
2.2299 + }
2.2300 + }
2.2301 +}
2.2302 +
2.2303 +ko.bindingHandlers['event'] = {
2.2304 + 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
2.2305 + var eventsToHandle = valueAccessor() || {};
2.2306 + for(var eventNameOutsideClosure in eventsToHandle) {
2.2307 + (function() {
2.2308 + var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
2.2309 + if (typeof eventName == "string") {
2.2310 + ko.utils.registerEventHandler(element, eventName, function (event) {
2.2311 + var handlerReturnValue;
2.2312 + var handlerFunction = valueAccessor()[eventName];
2.2313 + if (!handlerFunction)
2.2314 + return;
2.2315 + var allBindings = allBindingsAccessor();
2.2316 +
2.2317 + try {
2.2318 + // Take all the event args, and prefix with the viewmodel
2.2319 + var argsForHandler = ko.utils.makeArray(arguments);
2.2320 + argsForHandler.unshift(viewModel);
2.2321 + handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
2.2322 + } finally {
2.2323 + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
2.2324 + if (event.preventDefault)
2.2325 + event.preventDefault();
2.2326 + else
2.2327 + event.returnValue = false;
2.2328 + }
2.2329 + }
2.2330 +
2.2331 + var bubble = allBindings[eventName + 'Bubble'] !== false;
2.2332 + if (!bubble) {
2.2333 + event.cancelBubble = true;
2.2334 + if (event.stopPropagation)
2.2335 + event.stopPropagation();
2.2336 + }
2.2337 + });
2.2338 + }
2.2339 + })();
2.2340 + }
2.2341 + }
2.2342 +};
2.2343 +// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
2.2344 +// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
2.2345 +ko.bindingHandlers['foreach'] = {
2.2346 + makeTemplateValueAccessor: function(valueAccessor) {
2.2347 + return function() {
2.2348 + var modelValue = valueAccessor(),
2.2349 + unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
2.2350 +
2.2351 + // If unwrappedValue is the array, pass in the wrapped value on its own
2.2352 + // The value will be unwrapped and tracked within the template binding
2.2353 + // (See https://github.com/SteveSanderson/knockout/issues/523)
2.2354 + if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
2.2355 + return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
2.2356 +
2.2357 + // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
2.2358 + ko.utils.unwrapObservable(modelValue);
2.2359 + return {
2.2360 + 'foreach': unwrappedValue['data'],
2.2361 + 'as': unwrappedValue['as'],
2.2362 + 'includeDestroyed': unwrappedValue['includeDestroyed'],
2.2363 + 'afterAdd': unwrappedValue['afterAdd'],
2.2364 + 'beforeRemove': unwrappedValue['beforeRemove'],
2.2365 + 'afterRender': unwrappedValue['afterRender'],
2.2366 + 'beforeMove': unwrappedValue['beforeMove'],
2.2367 + 'afterMove': unwrappedValue['afterMove'],
2.2368 + 'templateEngine': ko.nativeTemplateEngine.instance
2.2369 + };
2.2370 + };
2.2371 + },
2.2372 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.2373 + return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
2.2374 + },
2.2375 + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.2376 + return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
2.2377 + }
2.2378 +};
2.2379 +ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
2.2380 +ko.virtualElements.allowedBindings['foreach'] = true;
2.2381 +var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
2.2382 +ko.bindingHandlers['hasfocus'] = {
2.2383 + 'init': function(element, valueAccessor, allBindingsAccessor) {
2.2384 + var handleElementFocusChange = function(isFocused) {
2.2385 + // Where possible, ignore which event was raised and determine focus state using activeElement,
2.2386 + // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
2.2387 + // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
2.2388 + // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
2.2389 + // from calling 'blur()' on the element when it loses focus.
2.2390 + // Discussion at https://github.com/SteveSanderson/knockout/pull/352
2.2391 + element[hasfocusUpdatingProperty] = true;
2.2392 + var ownerDoc = element.ownerDocument;
2.2393 + if ("activeElement" in ownerDoc) {
2.2394 + isFocused = (ownerDoc.activeElement === element);
2.2395 + }
2.2396 + var modelValue = valueAccessor();
2.2397 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true);
2.2398 + element[hasfocusUpdatingProperty] = false;
2.2399 + };
2.2400 + var handleElementFocusIn = handleElementFocusChange.bind(null, true);
2.2401 + var handleElementFocusOut = handleElementFocusChange.bind(null, false);
2.2402 +
2.2403 + ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
2.2404 + ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
2.2405 + ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
2.2406 + ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
2.2407 + },
2.2408 + 'update': function(element, valueAccessor) {
2.2409 + var value = ko.utils.unwrapObservable(valueAccessor());
2.2410 + if (!element[hasfocusUpdatingProperty]) {
2.2411 + value ? element.focus() : element.blur();
2.2412 + ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
2.2413 + }
2.2414 + }
2.2415 +};
2.2416 +ko.bindingHandlers['html'] = {
2.2417 + 'init': function() {
2.2418 + // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
2.2419 + return { 'controlsDescendantBindings': true };
2.2420 + },
2.2421 + 'update': function (element, valueAccessor) {
2.2422 + // setHtml will unwrap the value if needed
2.2423 + ko.utils.setHtml(element, valueAccessor());
2.2424 + }
2.2425 +};
2.2426 +var withIfDomDataKey = '__ko_withIfBindingData';
2.2427 +// Makes a binding like with or if
2.2428 +function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
2.2429 + ko.bindingHandlers[bindingKey] = {
2.2430 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.2431 + ko.utils.domData.set(element, withIfDomDataKey, {});
2.2432 + return { 'controlsDescendantBindings': true };
2.2433 + },
2.2434 + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.2435 + var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
2.2436 + dataValue = ko.utils.unwrapObservable(valueAccessor()),
2.2437 + shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
2.2438 + isFirstRender = !withIfData.savedNodes,
2.2439 + needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
2.2440 +
2.2441 + if (needsRefresh) {
2.2442 + if (isFirstRender) {
2.2443 + withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
2.2444 + }
2.2445 +
2.2446 + if (shouldDisplay) {
2.2447 + if (!isFirstRender) {
2.2448 + ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
2.2449 + }
2.2450 + ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
2.2451 + } else {
2.2452 + ko.virtualElements.emptyNode(element);
2.2453 + }
2.2454 +
2.2455 + withIfData.didDisplayOnLastUpdate = shouldDisplay;
2.2456 + }
2.2457 + }
2.2458 + };
2.2459 + ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
2.2460 + ko.virtualElements.allowedBindings[bindingKey] = true;
2.2461 +}
2.2462 +
2.2463 +// Construct the actual binding handlers
2.2464 +makeWithIfBinding('if');
2.2465 +makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
2.2466 +makeWithIfBinding('with', true /* isWith */, false /* isNot */,
2.2467 + function(bindingContext, dataValue) {
2.2468 + return bindingContext['createChildContext'](dataValue);
2.2469 + }
2.2470 +);
2.2471 +function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
2.2472 + if (preferModelValue) {
2.2473 + if (modelValue !== ko.selectExtensions.readValue(element))
2.2474 + ko.selectExtensions.writeValue(element, modelValue);
2.2475 + }
2.2476 +
2.2477 + // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
2.2478 + // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
2.2479 + // change the model value to match the dropdown.
2.2480 + if (modelValue !== ko.selectExtensions.readValue(element))
2.2481 + ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
2.2482 +};
2.2483 +
2.2484 +ko.bindingHandlers['options'] = {
2.2485 + 'update': function (element, valueAccessor, allBindingsAccessor) {
2.2486 + if (ko.utils.tagNameLower(element) !== "select")
2.2487 + throw new Error("options binding applies only to SELECT elements");
2.2488 +
2.2489 + var selectWasPreviouslyEmpty = element.length == 0;
2.2490 + var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
2.2491 + return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
2.2492 + }), function (node) {
2.2493 + return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
2.2494 + });
2.2495 + var previousScrollTop = element.scrollTop;
2.2496 +
2.2497 + var value = ko.utils.unwrapObservable(valueAccessor());
2.2498 + var selectedValue = element.value;
2.2499 +
2.2500 + // Remove all existing <option>s.
2.2501 + // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
2.2502 + while (element.length > 0) {
2.2503 + ko.cleanNode(element.options[0]);
2.2504 + element.remove(0);
2.2505 + }
2.2506 +
2.2507 + if (value) {
2.2508 + var allBindings = allBindingsAccessor(),
2.2509 + includeDestroyed = allBindings['optionsIncludeDestroyed'];
2.2510 +
2.2511 + if (typeof value.length != "number")
2.2512 + value = [value];
2.2513 + if (allBindings['optionsCaption']) {
2.2514 + var option = document.createElement("option");
2.2515 + ko.utils.setHtml(option, allBindings['optionsCaption']);
2.2516 + ko.selectExtensions.writeValue(option, undefined);
2.2517 + element.appendChild(option);
2.2518 + }
2.2519 +
2.2520 + for (var i = 0, j = value.length; i < j; i++) {
2.2521 + // Skip destroyed items
2.2522 + var arrayEntry = value[i];
2.2523 + if (arrayEntry && arrayEntry['_destroy'] && !includeDestroyed)
2.2524 + continue;
2.2525 +
2.2526 + var option = document.createElement("option");
2.2527 +
2.2528 + function applyToObject(object, predicate, defaultValue) {
2.2529 + var predicateType = typeof predicate;
2.2530 + if (predicateType == "function") // Given a function; run it against the data value
2.2531 + return predicate(object);
2.2532 + else if (predicateType == "string") // Given a string; treat it as a property name on the data value
2.2533 + return object[predicate];
2.2534 + else // Given no optionsText arg; use the data value itself
2.2535 + return defaultValue;
2.2536 + }
2.2537 +
2.2538 + // Apply a value to the option element
2.2539 + var optionValue = applyToObject(arrayEntry, allBindings['optionsValue'], arrayEntry);
2.2540 + ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
2.2541 +
2.2542 + // Apply some text to the option element
2.2543 + var optionText = applyToObject(arrayEntry, allBindings['optionsText'], optionValue);
2.2544 + ko.utils.setTextContent(option, optionText);
2.2545 +
2.2546 + element.appendChild(option);
2.2547 + }
2.2548 +
2.2549 + // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
2.2550 + // That's why we first added them without selection. Now it's time to set the selection.
2.2551 + var newOptions = element.getElementsByTagName("option");
2.2552 + var countSelectionsRetained = 0;
2.2553 + for (var i = 0, j = newOptions.length; i < j; i++) {
2.2554 + if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
2.2555 + ko.utils.setOptionNodeSelectionState(newOptions[i], true);
2.2556 + countSelectionsRetained++;
2.2557 + }
2.2558 + }
2.2559 +
2.2560 + element.scrollTop = previousScrollTop;
2.2561 +
2.2562 + if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
2.2563 + // Ensure consistency between model value and selected option.
2.2564 + // If the dropdown is being populated for the first time here (or was otherwise previously empty),
2.2565 + // the dropdown selection state is meaningless, so we preserve the model value.
2.2566 + ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.peekObservable(allBindings['value']), /* preferModelValue */ true);
2.2567 + }
2.2568 +
2.2569 + // Workaround for IE9 bug
2.2570 + ko.utils.ensureSelectElementIsRenderedCorrectly(element);
2.2571 + }
2.2572 + }
2.2573 +};
2.2574 +ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
2.2575 +ko.bindingHandlers['selectedOptions'] = {
2.2576 + 'init': function (element, valueAccessor, allBindingsAccessor) {
2.2577 + ko.utils.registerEventHandler(element, "change", function () {
2.2578 + var value = valueAccessor(), valueToWrite = [];
2.2579 + ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
2.2580 + if (node.selected)
2.2581 + valueToWrite.push(ko.selectExtensions.readValue(node));
2.2582 + });
2.2583 + ko.expressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
2.2584 + });
2.2585 + },
2.2586 + 'update': function (element, valueAccessor) {
2.2587 + if (ko.utils.tagNameLower(element) != "select")
2.2588 + throw new Error("values binding applies only to SELECT elements");
2.2589 +
2.2590 + var newValue = ko.utils.unwrapObservable(valueAccessor());
2.2591 + if (newValue && typeof newValue.length == "number") {
2.2592 + ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
2.2593 + var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
2.2594 + ko.utils.setOptionNodeSelectionState(node, isSelected);
2.2595 + });
2.2596 + }
2.2597 + }
2.2598 +};
2.2599 +ko.bindingHandlers['style'] = {
2.2600 + 'update': function (element, valueAccessor) {
2.2601 + var value = ko.utils.unwrapObservable(valueAccessor() || {});
2.2602 + for (var styleName in value) {
2.2603 + if (typeof styleName == "string") {
2.2604 + var styleValue = ko.utils.unwrapObservable(value[styleName]);
2.2605 + element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
2.2606 + }
2.2607 + }
2.2608 + }
2.2609 +};
2.2610 +ko.bindingHandlers['submit'] = {
2.2611 + 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
2.2612 + if (typeof valueAccessor() != "function")
2.2613 + throw new Error("The value for a submit binding must be a function");
2.2614 + ko.utils.registerEventHandler(element, "submit", function (event) {
2.2615 + var handlerReturnValue;
2.2616 + var value = valueAccessor();
2.2617 + try { handlerReturnValue = value.call(viewModel, element); }
2.2618 + finally {
2.2619 + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
2.2620 + if (event.preventDefault)
2.2621 + event.preventDefault();
2.2622 + else
2.2623 + event.returnValue = false;
2.2624 + }
2.2625 + }
2.2626 + });
2.2627 + }
2.2628 +};
2.2629 +ko.bindingHandlers['text'] = {
2.2630 + 'update': function (element, valueAccessor) {
2.2631 + ko.utils.setTextContent(element, valueAccessor());
2.2632 + }
2.2633 +};
2.2634 +ko.virtualElements.allowedBindings['text'] = true;
2.2635 +ko.bindingHandlers['uniqueName'] = {
2.2636 + 'init': function (element, valueAccessor) {
2.2637 + if (valueAccessor()) {
2.2638 + var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
2.2639 + ko.utils.setElementName(element, name);
2.2640 + }
2.2641 + }
2.2642 +};
2.2643 +ko.bindingHandlers['uniqueName'].currentIndex = 0;
2.2644 +ko.bindingHandlers['value'] = {
2.2645 + 'init': function (element, valueAccessor, allBindingsAccessor) {
2.2646 + // Always catch "change" event; possibly other events too if asked
2.2647 + var eventsToCatch = ["change"];
2.2648 + var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
2.2649 + var propertyChangedFired = false;
2.2650 + if (requestedEventsToCatch) {
2.2651 + if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
2.2652 + requestedEventsToCatch = [requestedEventsToCatch];
2.2653 + ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
2.2654 + eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
2.2655 + }
2.2656 +
2.2657 + var valueUpdateHandler = function() {
2.2658 + propertyChangedFired = false;
2.2659 + var modelValue = valueAccessor();
2.2660 + var elementValue = ko.selectExtensions.readValue(element);
2.2661 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
2.2662 + }
2.2663 +
2.2664 + // Workaround for https://github.com/SteveSanderson/knockout/issues/122
2.2665 + // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
2.2666 + var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
2.2667 + && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
2.2668 + if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
2.2669 + ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
2.2670 + ko.utils.registerEventHandler(element, "blur", function() {
2.2671 + if (propertyChangedFired) {
2.2672 + valueUpdateHandler();
2.2673 + }
2.2674 + });
2.2675 + }
2.2676 +
2.2677 + ko.utils.arrayForEach(eventsToCatch, function(eventName) {
2.2678 + // The syntax "after<eventname>" means "run the handler asynchronously after the event"
2.2679 + // This is useful, for example, to catch "keydown" events after the browser has updated the control
2.2680 + // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
2.2681 + var handler = valueUpdateHandler;
2.2682 + if (ko.utils.stringStartsWith(eventName, "after")) {
2.2683 + handler = function() { setTimeout(valueUpdateHandler, 0) };
2.2684 + eventName = eventName.substring("after".length);
2.2685 + }
2.2686 + ko.utils.registerEventHandler(element, eventName, handler);
2.2687 + });
2.2688 + },
2.2689 + 'update': function (element, valueAccessor) {
2.2690 + var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
2.2691 + var newValue = ko.utils.unwrapObservable(valueAccessor());
2.2692 + var elementValue = ko.selectExtensions.readValue(element);
2.2693 + var valueHasChanged = (newValue != elementValue);
2.2694 +
2.2695 + // 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).
2.2696 + // 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.
2.2697 + if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
2.2698 + valueHasChanged = true;
2.2699 +
2.2700 + if (valueHasChanged) {
2.2701 + var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
2.2702 + applyValueAction();
2.2703 +
2.2704 + // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
2.2705 + // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
2.2706 + // to apply the value as well.
2.2707 + var alsoApplyAsynchronously = valueIsSelectOption;
2.2708 + if (alsoApplyAsynchronously)
2.2709 + setTimeout(applyValueAction, 0);
2.2710 + }
2.2711 +
2.2712 + // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
2.2713 + // because you're not allowed to have a model value that disagrees with a visible UI selection.
2.2714 + if (valueIsSelectOption && (element.length > 0))
2.2715 + ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
2.2716 + }
2.2717 +};
2.2718 +ko.bindingHandlers['visible'] = {
2.2719 + 'update': function (element, valueAccessor) {
2.2720 + var value = ko.utils.unwrapObservable(valueAccessor());
2.2721 + var isCurrentlyVisible = !(element.style.display == "none");
2.2722 + if (value && !isCurrentlyVisible)
2.2723 + element.style.display = "";
2.2724 + else if ((!value) && isCurrentlyVisible)
2.2725 + element.style.display = "none";
2.2726 + }
2.2727 +};
2.2728 +// 'click' is just a shorthand for the usual full-length event:{click:handler}
2.2729 +makeEventHandlerShortcut('click');
2.2730 +// If you want to make a custom template engine,
2.2731 +//
2.2732 +// [1] Inherit from this class (like ko.nativeTemplateEngine does)
2.2733 +// [2] Override 'renderTemplateSource', supplying a function with this signature:
2.2734 +//
2.2735 +// function (templateSource, bindingContext, options) {
2.2736 +// // - templateSource.text() is the text of the template you should render
2.2737 +// // - bindingContext.$data is the data you should pass into the template
2.2738 +// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
2.2739 +// // and bindingContext.$root available in the template too
2.2740 +// // - options gives you access to any other properties set on "data-bind: { template: options }"
2.2741 +// //
2.2742 +// // Return value: an array of DOM nodes
2.2743 +// }
2.2744 +//
2.2745 +// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
2.2746 +//
2.2747 +// function (script) {
2.2748 +// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
2.2749 +// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
2.2750 +// }
2.2751 +//
2.2752 +// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
2.2753 +// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
2.2754 +// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
2.2755 +
2.2756 +ko.templateEngine = function () { };
2.2757 +
2.2758 +ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
2.2759 + throw new Error("Override renderTemplateSource");
2.2760 +};
2.2761 +
2.2762 +ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
2.2763 + throw new Error("Override createJavaScriptEvaluatorBlock");
2.2764 +};
2.2765 +
2.2766 +ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
2.2767 + // Named template
2.2768 + if (typeof template == "string") {
2.2769 + templateDocument = templateDocument || document;
2.2770 + var elem = templateDocument.getElementById(template);
2.2771 + if (!elem)
2.2772 + throw new Error("Cannot find template with ID " + template);
2.2773 + return new ko.templateSources.domElement(elem);
2.2774 + } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
2.2775 + // Anonymous template
2.2776 + return new ko.templateSources.anonymousTemplate(template);
2.2777 + } else
2.2778 + throw new Error("Unknown template type: " + template);
2.2779 +};
2.2780 +
2.2781 +ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
2.2782 + var templateSource = this['makeTemplateSource'](template, templateDocument);
2.2783 + return this['renderTemplateSource'](templateSource, bindingContext, options);
2.2784 +};
2.2785 +
2.2786 +ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
2.2787 + // Skip rewriting if requested
2.2788 + if (this['allowTemplateRewriting'] === false)
2.2789 + return true;
2.2790 + return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
2.2791 +};
2.2792 +
2.2793 +ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
2.2794 + var templateSource = this['makeTemplateSource'](template, templateDocument);
2.2795 + var rewritten = rewriterCallback(templateSource['text']());
2.2796 + templateSource['text'](rewritten);
2.2797 + templateSource['data']("isRewritten", true);
2.2798 +};
2.2799 +
2.2800 +ko.exportSymbol('templateEngine', ko.templateEngine);
2.2801 +
2.2802 +ko.templateRewriting = (function () {
2.2803 + var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
2.2804 + var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
2.2805 +
2.2806 + function validateDataBindValuesForRewriting(keyValueArray) {
2.2807 + var allValidators = ko.expressionRewriting.bindingRewriteValidators;
2.2808 + for (var i = 0; i < keyValueArray.length; i++) {
2.2809 + var key = keyValueArray[i]['key'];
2.2810 + if (allValidators.hasOwnProperty(key)) {
2.2811 + var validator = allValidators[key];
2.2812 +
2.2813 + if (typeof validator === "function") {
2.2814 + var possibleErrorMessage = validator(keyValueArray[i]['value']);
2.2815 + if (possibleErrorMessage)
2.2816 + throw new Error(possibleErrorMessage);
2.2817 + } else if (!validator) {
2.2818 + throw new Error("This template engine does not support the '" + key + "' binding within its templates");
2.2819 + }
2.2820 + }
2.2821 + }
2.2822 + }
2.2823 +
2.2824 + function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
2.2825 + var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
2.2826 + validateDataBindValuesForRewriting(dataBindKeyValueArray);
2.2827 + var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray);
2.2828 +
2.2829 + // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
2.2830 + // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
2.2831 + // extra indirection.
2.2832 + var applyBindingsToNextSiblingScript =
2.2833 + "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()})";
2.2834 + return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
2.2835 + }
2.2836 +
2.2837 + return {
2.2838 + ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
2.2839 + if (!templateEngine['isTemplateRewritten'](template, templateDocument))
2.2840 + templateEngine['rewriteTemplate'](template, function (htmlString) {
2.2841 + return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
2.2842 + }, templateDocument);
2.2843 + },
2.2844 +
2.2845 + memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
2.2846 + return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
2.2847 + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
2.2848 + }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
2.2849 + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
2.2850 + });
2.2851 + },
2.2852 +
2.2853 + applyMemoizedBindingsToNextSibling: function (bindings) {
2.2854 + return ko.memoization.memoize(function (domNode, bindingContext) {
2.2855 + if (domNode.nextSibling)
2.2856 + ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
2.2857 + });
2.2858 + }
2.2859 + }
2.2860 +})();
2.2861 +
2.2862 +
2.2863 +// Exported only because it has to be referenced by string lookup from within rewritten template
2.2864 +ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
2.2865 +(function() {
2.2866 + // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
2.2867 + // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
2.2868 + //
2.2869 + // Two are provided by default:
2.2870 + // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
2.2871 + // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
2.2872 + // without reading/writing the actual element text content, since it will be overwritten
2.2873 + // with the rendered template output.
2.2874 + // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
2.2875 + // Template sources need to have the following functions:
2.2876 + // text() - returns the template text from your storage location
2.2877 + // text(value) - writes the supplied template text to your storage location
2.2878 + // data(key) - reads values stored using data(key, value) - see below
2.2879 + // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
2.2880 + //
2.2881 + // Optionally, template sources can also have the following functions:
2.2882 + // nodes() - returns a DOM element containing the nodes of this template, where available
2.2883 + // nodes(value) - writes the given DOM element to your storage location
2.2884 + // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
2.2885 + // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
2.2886 + //
2.2887 + // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
2.2888 + // using and overriding "makeTemplateSource" to return an instance of your custom template source.
2.2889 +
2.2890 + ko.templateSources = {};
2.2891 +
2.2892 + // ---- ko.templateSources.domElement -----
2.2893 +
2.2894 + ko.templateSources.domElement = function(element) {
2.2895 + this.domElement = element;
2.2896 + }
2.2897 +
2.2898 + ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
2.2899 + var tagNameLower = ko.utils.tagNameLower(this.domElement),
2.2900 + elemContentsProperty = tagNameLower === "script" ? "text"
2.2901 + : tagNameLower === "textarea" ? "value"
2.2902 + : "innerHTML";
2.2903 +
2.2904 + if (arguments.length == 0) {
2.2905 + return this.domElement[elemContentsProperty];
2.2906 + } else {
2.2907 + var valueToWrite = arguments[0];
2.2908 + if (elemContentsProperty === "innerHTML")
2.2909 + ko.utils.setHtml(this.domElement, valueToWrite);
2.2910 + else
2.2911 + this.domElement[elemContentsProperty] = valueToWrite;
2.2912 + }
2.2913 + };
2.2914 +
2.2915 + ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
2.2916 + if (arguments.length === 1) {
2.2917 + return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
2.2918 + } else {
2.2919 + ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
2.2920 + }
2.2921 + };
2.2922 +
2.2923 + // ---- ko.templateSources.anonymousTemplate -----
2.2924 + // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
2.2925 + // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
2.2926 + // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
2.2927 +
2.2928 + var anonymousTemplatesDomDataKey = "__ko_anon_template__";
2.2929 + ko.templateSources.anonymousTemplate = function(element) {
2.2930 + this.domElement = element;
2.2931 + }
2.2932 + ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
2.2933 + ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
2.2934 + if (arguments.length == 0) {
2.2935 + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
2.2936 + if (templateData.textData === undefined && templateData.containerData)
2.2937 + templateData.textData = templateData.containerData.innerHTML;
2.2938 + return templateData.textData;
2.2939 + } else {
2.2940 + var valueToWrite = arguments[0];
2.2941 + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
2.2942 + }
2.2943 + };
2.2944 + ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
2.2945 + if (arguments.length == 0) {
2.2946 + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
2.2947 + return templateData.containerData;
2.2948 + } else {
2.2949 + var valueToWrite = arguments[0];
2.2950 + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
2.2951 + }
2.2952 + };
2.2953 +
2.2954 + ko.exportSymbol('templateSources', ko.templateSources);
2.2955 + ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
2.2956 + ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
2.2957 +})();
2.2958 +(function () {
2.2959 + var _templateEngine;
2.2960 + ko.setTemplateEngine = function (templateEngine) {
2.2961 + if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
2.2962 + throw new Error("templateEngine must inherit from ko.templateEngine");
2.2963 + _templateEngine = templateEngine;
2.2964 + }
2.2965 +
2.2966 + function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
2.2967 + var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
2.2968 + while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
2.2969 + nextInQueue = ko.virtualElements.nextSibling(node);
2.2970 + if (node.nodeType === 1 || node.nodeType === 8)
2.2971 + action(node);
2.2972 + }
2.2973 + }
2.2974 +
2.2975 + function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
2.2976 + // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
2.2977 + // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
2.2978 + // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
2.2979 + // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
2.2980 + // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
2.2981 +
2.2982 + if (continuousNodeArray.length) {
2.2983 + var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
2.2984 +
2.2985 + // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
2.2986 + // whereas a regular applyBindings won't introduce new memoized nodes
2.2987 + invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
2.2988 + ko.applyBindings(bindingContext, node);
2.2989 + });
2.2990 + invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
2.2991 + ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
2.2992 + });
2.2993 + }
2.2994 + }
2.2995 +
2.2996 + function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
2.2997 + return nodeOrNodeArray.nodeType ? nodeOrNodeArray
2.2998 + : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
2.2999 + : null;
2.3000 + }
2.3001 +
2.3002 + function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
2.3003 + options = options || {};
2.3004 + var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
2.3005 + var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
2.3006 + var templateEngineToUse = (options['templateEngine'] || _templateEngine);
2.3007 + ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
2.3008 + var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
2.3009 +
2.3010 + // Loosely check result is an array of DOM nodes
2.3011 + if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
2.3012 + throw new Error("Template engine must return an array of DOM nodes");
2.3013 +
2.3014 + var haveAddedNodesToParent = false;
2.3015 + switch (renderMode) {
2.3016 + case "replaceChildren":
2.3017 + ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
2.3018 + haveAddedNodesToParent = true;
2.3019 + break;
2.3020 + case "replaceNode":
2.3021 + ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
2.3022 + haveAddedNodesToParent = true;
2.3023 + break;
2.3024 + case "ignoreTargetNode": break;
2.3025 + default:
2.3026 + throw new Error("Unknown renderMode: " + renderMode);
2.3027 + }
2.3028 +
2.3029 + if (haveAddedNodesToParent) {
2.3030 + activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
2.3031 + if (options['afterRender'])
2.3032 + ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
2.3033 + }
2.3034 +
2.3035 + return renderedNodesArray;
2.3036 + }
2.3037 +
2.3038 + ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
2.3039 + options = options || {};
2.3040 + if ((options['templateEngine'] || _templateEngine) == undefined)
2.3041 + throw new Error("Set a template engine before calling renderTemplate");
2.3042 + renderMode = renderMode || "replaceChildren";
2.3043 +
2.3044 + if (targetNodeOrNodeArray) {
2.3045 + var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
2.3046 +
2.3047 + var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
2.3048 + var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
2.3049 +
2.3050 + return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
2.3051 + function () {
2.3052 + // Ensure we've got a proper binding context to work with
2.3053 + var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
2.3054 + ? dataOrBindingContext
2.3055 + : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
2.3056 +
2.3057 + // Support selecting template as a function of the data being rendered
2.3058 + var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
2.3059 +
2.3060 + var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
2.3061 + if (renderMode == "replaceNode") {
2.3062 + targetNodeOrNodeArray = renderedNodesArray;
2.3063 + firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
2.3064 + }
2.3065 + },
2.3066 + null,
2.3067 + { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
2.3068 + );
2.3069 + } else {
2.3070 + // 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
2.3071 + return ko.memoization.memoize(function (domNode) {
2.3072 + ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
2.3073 + });
2.3074 + }
2.3075 + };
2.3076 +
2.3077 + ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
2.3078 + // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
2.3079 + // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
2.3080 + var arrayItemContext;
2.3081 +
2.3082 + // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
2.3083 + var executeTemplateForArrayItem = function (arrayValue, index) {
2.3084 + // Support selecting template as a function of the data being rendered
2.3085 + arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue), options['as']);
2.3086 + arrayItemContext['$index'] = index;
2.3087 + var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
2.3088 + return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
2.3089 + }
2.3090 +
2.3091 + // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
2.3092 + var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
2.3093 + activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
2.3094 + if (options['afterRender'])
2.3095 + options['afterRender'](addedNodesArray, arrayValue);
2.3096 + };
2.3097 +
2.3098 + return ko.dependentObservable(function () {
2.3099 + var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
2.3100 + if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
2.3101 + unwrappedArray = [unwrappedArray];
2.3102 +
2.3103 + // Filter out any entries marked as destroyed
2.3104 + var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
2.3105 + return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
2.3106 + });
2.3107 +
2.3108 + // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
2.3109 + // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
2.3110 + ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
2.3111 +
2.3112 + }, null, { disposeWhenNodeIsRemoved: targetNode });
2.3113 + };
2.3114 +
2.3115 + var templateComputedDomDataKey = '__ko__templateComputedDomDataKey__';
2.3116 + function disposeOldComputedAndStoreNewOne(element, newComputed) {
2.3117 + var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
2.3118 + if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
2.3119 + oldComputed.dispose();
2.3120 + ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
2.3121 + }
2.3122 +
2.3123 + ko.bindingHandlers['template'] = {
2.3124 + 'init': function(element, valueAccessor) {
2.3125 + // Support anonymous templates
2.3126 + var bindingValue = ko.utils.unwrapObservable(valueAccessor());
2.3127 + if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
2.3128 + // It's an anonymous template - store the element contents, then clear the element
2.3129 + var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
2.3130 + container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
2.3131 + new ko.templateSources.anonymousTemplate(element)['nodes'](container);
2.3132 + }
2.3133 + return { 'controlsDescendantBindings': true };
2.3134 + },
2.3135 + 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.3136 + var templateName = ko.utils.unwrapObservable(valueAccessor()),
2.3137 + options = {},
2.3138 + shouldDisplay = true,
2.3139 + dataValue,
2.3140 + templateComputed = null;
2.3141 +
2.3142 + if (typeof templateName != "string") {
2.3143 + options = templateName;
2.3144 + templateName = options['name'];
2.3145 +
2.3146 + // Support "if"/"ifnot" conditions
2.3147 + if ('if' in options)
2.3148 + shouldDisplay = ko.utils.unwrapObservable(options['if']);
2.3149 + if (shouldDisplay && 'ifnot' in options)
2.3150 + shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
2.3151 +
2.3152 + dataValue = ko.utils.unwrapObservable(options['data']);
2.3153 + }
2.3154 +
2.3155 + if ('foreach' in options) {
2.3156 + // Render once for each data point (treating data set as empty if shouldDisplay==false)
2.3157 + var dataArray = (shouldDisplay && options['foreach']) || [];
2.3158 + templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
2.3159 + } else if (!shouldDisplay) {
2.3160 + ko.virtualElements.emptyNode(element);
2.3161 + } else {
2.3162 + // Render once for this single data point (or use the viewModel if no data was provided)
2.3163 + var innerBindingContext = ('data' in options) ?
2.3164 + bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
2.3165 + bindingContext; // Given no explicit 'data' value, we retain the same binding context
2.3166 + templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
2.3167 + }
2.3168 +
2.3169 + // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
2.3170 + disposeOldComputedAndStoreNewOne(element, templateComputed);
2.3171 + }
2.3172 + };
2.3173 +
2.3174 + // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
2.3175 + ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
2.3176 + var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
2.3177 +
2.3178 + if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
2.3179 + return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
2.3180 +
2.3181 + if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
2.3182 + return null; // Named templates can be rewritten, so return "no error"
2.3183 + return "This template engine does not support anonymous templates nested within its templates";
2.3184 + };
2.3185 +
2.3186 + ko.virtualElements.allowedBindings['template'] = true;
2.3187 +})();
2.3188 +
2.3189 +ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
2.3190 +ko.exportSymbol('renderTemplate', ko.renderTemplate);
2.3191 +
2.3192 +ko.utils.compareArrays = (function () {
2.3193 + var statusNotInOld = 'added', statusNotInNew = 'deleted';
2.3194 +
2.3195 + // Simple calculation based on Levenshtein distance.
2.3196 + function compareArrays(oldArray, newArray, dontLimitMoves) {
2.3197 + oldArray = oldArray || [];
2.3198 + newArray = newArray || [];
2.3199 +
2.3200 + if (oldArray.length <= newArray.length)
2.3201 + return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, dontLimitMoves);
2.3202 + else
2.3203 + return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, dontLimitMoves);
2.3204 + }
2.3205 +
2.3206 + function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, dontLimitMoves) {
2.3207 + var myMin = Math.min,
2.3208 + myMax = Math.max,
2.3209 + editDistanceMatrix = [],
2.3210 + smlIndex, smlIndexMax = smlArray.length,
2.3211 + bigIndex, bigIndexMax = bigArray.length,
2.3212 + compareRange = (bigIndexMax - smlIndexMax) || 1,
2.3213 + maxDistance = smlIndexMax + bigIndexMax + 1,
2.3214 + thisRow, lastRow,
2.3215 + bigIndexMaxForRow, bigIndexMinForRow;
2.3216 +
2.3217 + for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
2.3218 + lastRow = thisRow;
2.3219 + editDistanceMatrix.push(thisRow = []);
2.3220 + bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
2.3221 + bigIndexMinForRow = myMax(0, smlIndex - 1);
2.3222 + for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
2.3223 + if (!bigIndex)
2.3224 + thisRow[bigIndex] = smlIndex + 1;
2.3225 + else if (!smlIndex) // Top row - transform empty array into new array via additions
2.3226 + thisRow[bigIndex] = bigIndex + 1;
2.3227 + else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
2.3228 + thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
2.3229 + else {
2.3230 + var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
2.3231 + var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
2.3232 + thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
2.3233 + }
2.3234 + }
2.3235 + }
2.3236 +
2.3237 + var editScript = [], meMinusOne, notInSml = [], notInBig = [];
2.3238 + for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
2.3239 + meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
2.3240 + if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
2.3241 + notInSml.push(editScript[editScript.length] = { // added
2.3242 + 'status': statusNotInSml,
2.3243 + 'value': bigArray[--bigIndex],
2.3244 + 'index': bigIndex });
2.3245 + } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
2.3246 + notInBig.push(editScript[editScript.length] = { // deleted
2.3247 + 'status': statusNotInBig,
2.3248 + 'value': smlArray[--smlIndex],
2.3249 + 'index': smlIndex });
2.3250 + } else {
2.3251 + editScript.push({
2.3252 + 'status': "retained",
2.3253 + 'value': bigArray[--bigIndex] });
2.3254 + --smlIndex;
2.3255 + }
2.3256 + }
2.3257 +
2.3258 + if (notInSml.length && notInBig.length) {
2.3259 + // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
2.3260 + // smlIndexMax keeps the time complexity of this algorithm linear.
2.3261 + var limitFailedCompares = smlIndexMax * 10, failedCompares,
2.3262 + a, d, notInSmlItem, notInBigItem;
2.3263 + // Go through the items that have been added and deleted and try to find matches between them.
2.3264 + for (failedCompares = a = 0; (dontLimitMoves || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
2.3265 + for (d = 0; notInBigItem = notInBig[d]; d++) {
2.3266 + if (notInSmlItem['value'] === notInBigItem['value']) {
2.3267 + notInSmlItem['moved'] = notInBigItem['index'];
2.3268 + notInBigItem['moved'] = notInSmlItem['index'];
2.3269 + notInBig.splice(d,1); // This item is marked as moved; so remove it from notInBig list
2.3270 + failedCompares = d = 0; // Reset failed compares count because we're checking for consecutive failures
2.3271 + break;
2.3272 + }
2.3273 + }
2.3274 + failedCompares += d;
2.3275 + }
2.3276 + }
2.3277 + return editScript.reverse();
2.3278 + }
2.3279 +
2.3280 + return compareArrays;
2.3281 +})();
2.3282 +
2.3283 +ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
2.3284 +
2.3285 +(function () {
2.3286 + // Objective:
2.3287 + // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
2.3288 + // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
2.3289 + // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
2.3290 + // 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
2.3291 + // previously mapped - retain those nodes, and just insert/delete other ones
2.3292 +
2.3293 + // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
2.3294 + // You can use this, for example, to activate bindings on those nodes.
2.3295 +
2.3296 + function fixUpNodesToBeMovedOrRemoved(contiguousNodeArray) {
2.3297 + // Before moving, deleting, or replacing a set of nodes that were previously outputted by the "map" function, we have to reconcile
2.3298 + // them against what is in the DOM right now. It may be that some of the nodes have already been removed from the document,
2.3299 + // or that new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
2.3300 + // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
2.3301 + // So, this function translates the old "map" output array into its best guess of what set of current DOM nodes should be removed.
2.3302 + //
2.3303 + // Rules:
2.3304 + // [A] Any leading nodes that aren't in the document any more should be ignored
2.3305 + // These most likely correspond to memoization nodes that were already removed during binding
2.3306 + // See https://github.com/SteveSanderson/knockout/pull/440
2.3307 + // [B] We want to output a contiguous series of nodes that are still in the document. So, ignore any nodes that
2.3308 + // have already been removed, and include any nodes that have been inserted among the previous collection
2.3309 +
2.3310 + // Rule [A]
2.3311 + while (contiguousNodeArray.length && !ko.utils.domNodeIsAttachedToDocument(contiguousNodeArray[0]))
2.3312 + contiguousNodeArray.splice(0, 1);
2.3313 +
2.3314 + // Rule [B]
2.3315 + if (contiguousNodeArray.length > 1) {
2.3316 + // Build up the actual new contiguous node set
2.3317 + var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
2.3318 + while (current !== last) {
2.3319 + current = current.nextSibling;
2.3320 + if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
2.3321 + return;
2.3322 + newContiguousSet.push(current);
2.3323 + }
2.3324 +
2.3325 + // ... then mutate the input array to match this.
2.3326 + // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
2.3327 + Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
2.3328 + }
2.3329 + return contiguousNodeArray;
2.3330 + }
2.3331 +
2.3332 + function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
2.3333 + // Map this array value inside a dependentObservable so we re-map when any dependency changes
2.3334 + var mappedNodes = [];
2.3335 + var dependentObservable = ko.dependentObservable(function() {
2.3336 + var newMappedNodes = mapping(valueToMap, index) || [];
2.3337 +
2.3338 + // On subsequent evaluations, just replace the previously-inserted DOM nodes
2.3339 + if (mappedNodes.length > 0) {
2.3340 + ko.utils.replaceDomNodes(fixUpNodesToBeMovedOrRemoved(mappedNodes), newMappedNodes);
2.3341 + if (callbackAfterAddingNodes)
2.3342 + ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
2.3343 + }
2.3344 +
2.3345 + // Replace the contents of the mappedNodes array, thereby updating the record
2.3346 + // of which nodes would be deleted if valueToMap was itself later removed
2.3347 + mappedNodes.splice(0, mappedNodes.length);
2.3348 + ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
2.3349 + }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
2.3350 + return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
2.3351 + }
2.3352 +
2.3353 + var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
2.3354 +
2.3355 + ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
2.3356 + // Compare the provided array against the previous one
2.3357 + array = array || [];
2.3358 + options = options || {};
2.3359 + var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
2.3360 + var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
2.3361 + var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
2.3362 + var editScript = ko.utils.compareArrays(lastArray, array);
2.3363 +
2.3364 + // Build the new mapping result
2.3365 + var newMappingResult = [];
2.3366 + var lastMappingResultIndex = 0;
2.3367 + var newMappingResultIndex = 0;
2.3368 +
2.3369 + var nodesToDelete = [];
2.3370 + var itemsToProcess = [];
2.3371 + var itemsForBeforeRemoveCallbacks = [];
2.3372 + var itemsForMoveCallbacks = [];
2.3373 + var itemsForAfterAddCallbacks = [];
2.3374 + var mapData;
2.3375 +
2.3376 + function itemMovedOrRetained(editScriptIndex, oldPosition) {
2.3377 + mapData = lastMappingResult[oldPosition];
2.3378 + if (newMappingResultIndex !== oldPosition)
2.3379 + itemsForMoveCallbacks[editScriptIndex] = mapData;
2.3380 + // Since updating the index might change the nodes, do so before calling fixUpNodesToBeMovedOrRemoved
2.3381 + mapData.indexObservable(newMappingResultIndex++);
2.3382 + fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes);
2.3383 + newMappingResult.push(mapData);
2.3384 + itemsToProcess.push(mapData);
2.3385 + }
2.3386 +
2.3387 + function callCallback(callback, items) {
2.3388 + if (callback) {
2.3389 + for (var i = 0, n = items.length; i < n; i++) {
2.3390 + if (items[i]) {
2.3391 + ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
2.3392 + callback(node, i, items[i].arrayEntry);
2.3393 + });
2.3394 + }
2.3395 + }
2.3396 + }
2.3397 + }
2.3398 +
2.3399 + for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
2.3400 + movedIndex = editScriptItem['moved'];
2.3401 + switch (editScriptItem['status']) {
2.3402 + case "deleted":
2.3403 + if (movedIndex === undefined) {
2.3404 + mapData = lastMappingResult[lastMappingResultIndex];
2.3405 +
2.3406 + // Stop tracking changes to the mapping for these nodes
2.3407 + if (mapData.dependentObservable)
2.3408 + mapData.dependentObservable.dispose();
2.3409 +
2.3410 + // Queue these nodes for later removal
2.3411 + nodesToDelete.push.apply(nodesToDelete, fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes));
2.3412 + if (options['beforeRemove']) {
2.3413 + itemsForBeforeRemoveCallbacks[i] = mapData;
2.3414 + itemsToProcess.push(mapData);
2.3415 + }
2.3416 + }
2.3417 + lastMappingResultIndex++;
2.3418 + break;
2.3419 +
2.3420 + case "retained":
2.3421 + itemMovedOrRetained(i, lastMappingResultIndex++);
2.3422 + break;
2.3423 +
2.3424 + case "added":
2.3425 + if (movedIndex !== undefined) {
2.3426 + itemMovedOrRetained(i, movedIndex);
2.3427 + } else {
2.3428 + mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
2.3429 + newMappingResult.push(mapData);
2.3430 + itemsToProcess.push(mapData);
2.3431 + if (!isFirstExecution)
2.3432 + itemsForAfterAddCallbacks[i] = mapData;
2.3433 + }
2.3434 + break;
2.3435 + }
2.3436 + }
2.3437 +
2.3438 + // Call beforeMove first before any changes have been made to the DOM
2.3439 + callCallback(options['beforeMove'], itemsForMoveCallbacks);
2.3440 +
2.3441 + // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
2.3442 + ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
2.3443 +
2.3444 + // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
2.3445 + for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
2.3446 + // Get nodes for newly added items
2.3447 + if (!mapData.mappedNodes)
2.3448 + ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
2.3449 +
2.3450 + // Put nodes in the right place if they aren't there already
2.3451 + for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
2.3452 + if (node !== nextNode)
2.3453 + ko.virtualElements.insertAfter(domNode, node, lastNode);
2.3454 + }
2.3455 +
2.3456 + // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
2.3457 + if (!mapData.initialized && callbackAfterAddingNodes) {
2.3458 + callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
2.3459 + mapData.initialized = true;
2.3460 + }
2.3461 + }
2.3462 +
2.3463 + // If there's a beforeRemove callback, call it after reordering.
2.3464 + // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
2.3465 + // some sort of animation, which is why we first reorder the nodes that will be removed. If the
2.3466 + // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
2.3467 + // Perhaps we'll make that change in the future if this scenario becomes more common.
2.3468 + callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
2.3469 +
2.3470 + // Finally call afterMove and afterAdd callbacks
2.3471 + callCallback(options['afterMove'], itemsForMoveCallbacks);
2.3472 + callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
2.3473 +
2.3474 + // Store a copy of the array items we just considered so we can difference it next time
2.3475 + ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
2.3476 + }
2.3477 +})();
2.3478 +
2.3479 +ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
2.3480 +ko.nativeTemplateEngine = function () {
2.3481 + this['allowTemplateRewriting'] = false;
2.3482 +}
2.3483 +
2.3484 +ko.nativeTemplateEngine.prototype = new ko.templateEngine();
2.3485 +ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
2.3486 + var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
2.3487 + templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
2.3488 + templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
2.3489 +
2.3490 + if (templateNodes) {
2.3491 + return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
2.3492 + } else {
2.3493 + var templateText = templateSource['text']();
2.3494 + return ko.utils.parseHtmlFragment(templateText);
2.3495 + }
2.3496 +};
2.3497 +
2.3498 +ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
2.3499 +ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
2.3500 +
2.3501 +ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
2.3502 +(function() {
2.3503 + ko.jqueryTmplTemplateEngine = function () {
2.3504 + // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
2.3505 + // doesn't expose a version number, so we have to infer it.
2.3506 + // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
2.3507 + // which KO internally refers to as version "2", so older versions are no longer detected.
2.3508 + var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
2.3509 + if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
2.3510 + return 0;
2.3511 + // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
2.3512 + try {
2.3513 + if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
2.3514 + // Since 1.0.0pre, custom tags should append markup to an array called "__"
2.3515 + return 2; // Final version of jquery.tmpl
2.3516 + }
2.3517 + } catch(ex) { /* Apparently not the version we were looking for */ }
2.3518 +
2.3519 + return 1; // Any older version that we don't support
2.3520 + })();
2.3521 +
2.3522 + function ensureHasReferencedJQueryTemplates() {
2.3523 + if (jQueryTmplVersion < 2)
2.3524 + throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
2.3525 + }
2.3526 +
2.3527 + function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
2.3528 + return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
2.3529 + }
2.3530 +
2.3531 + this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
2.3532 + options = options || {};
2.3533 + ensureHasReferencedJQueryTemplates();
2.3534 +
2.3535 + // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
2.3536 + var precompiled = templateSource['data']('precompiled');
2.3537 + if (!precompiled) {
2.3538 + var templateText = templateSource['text']() || "";
2.3539 + // Wrap in "with($whatever.koBindingContext) { ... }"
2.3540 + templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
2.3541 +
2.3542 + precompiled = jQuery['template'](null, templateText);
2.3543 + templateSource['data']('precompiled', precompiled);
2.3544 + }
2.3545 +
2.3546 + var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
2.3547 + var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
2.3548 +
2.3549 + var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
2.3550 + resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
2.3551 +
2.3552 + jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
2.3553 + return resultNodes;
2.3554 + };
2.3555 +
2.3556 + this['createJavaScriptEvaluatorBlock'] = function(script) {
2.3557 + return "{{ko_code ((function() { return " + script + " })()) }}";
2.3558 + };
2.3559 +
2.3560 + this['addTemplate'] = function(templateName, templateMarkup) {
2.3561 + document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
2.3562 + };
2.3563 +
2.3564 + if (jQueryTmplVersion > 0) {
2.3565 + jQuery['tmpl']['tag']['ko_code'] = {
2.3566 + open: "__.push($1 || '');"
2.3567 + };
2.3568 + jQuery['tmpl']['tag']['ko_with'] = {
2.3569 + open: "with($1) {",
2.3570 + close: "} "
2.3571 + };
2.3572 + }
2.3573 + };
2.3574 +
2.3575 + ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
2.3576 +
2.3577 + // Use this one by default *only if jquery.tmpl is referenced*
2.3578 + var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
2.3579 + if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
2.3580 + ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
2.3581 +
2.3582 + ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
2.3583 +})();
2.3584 +});
2.3585 +})(window,document,navigator,window["jQuery"]);
2.3586 +})();
2.3587 \ No newline at end of file
3.1 --- a/javaquery/api/src/main/resources/org/apidesign/bck2brwsr/htmlpage/knockout-min-2.2.0.js Sun Jan 20 18:20:18 2013 +0100
3.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
3.3 @@ -1,85 +0,0 @@
3.4 -// Knockout JavaScript library v2.2.0
3.5 -// (c) Steven Sanderson - http://knockoutjs.com/
3.6 -// License: MIT (http://www.opensource.org/licenses/mit-license.php)
3.7 -
3.8 -(function() {function i(v){throw v;}var l=!0,n=null,q=!1;function t(v){return function(){return v}};var w=window,x=document,fa=navigator,E=window.jQuery,H=void 0;
3.9 -function K(v){function ga(a,d,c,e,f){var g=[],a=b.j(function(){var a=d(c,f)||[];0<g.length&&(b.a.Xa(L(g),a),e&&b.r.K(e,n,[c,a,f]));g.splice(0,g.length);b.a.P(g,a)},n,{W:a,Ja:function(){return 0==g.length||!b.a.X(g[0])}});return{M:g,j:a.oa()?a:H}}function L(a){for(;a.length&&!b.a.X(a[0]);)a.splice(0,1);if(1<a.length){for(var d=a[0],c=a[a.length-1],e=[d];d!==c;){d=d.nextSibling;if(!d)return;e.push(d)}Array.prototype.splice.apply(a,[0,a.length].concat(e))}return a}function R(a,b,c,e,f){var g=Math.min,
3.10 -h=Math.max,j=[],k,m=a.length,p,r=b.length,u=r-m||1,F=m+r+1,I,z,y;for(k=0;k<=m;k++){z=I;j.push(I=[]);y=g(r,k+u);for(p=h(0,k-1);p<=y;p++)I[p]=p?k?a[k-1]===b[p-1]?z[p-1]:g(z[p]||F,I[p-1]||F)+1:p+1:k+1}g=[];h=[];u=[];k=m;for(p=r;k||p;)r=j[k][p]-1,p&&r===j[k][p-1]?h.push(g[g.length]={status:c,value:b[--p],index:p}):k&&r===j[k-1][p]?u.push(g[g.length]={status:e,value:a[--k],index:k}):(g.push({status:"retained",value:b[--p]}),--k);if(h.length&&u.length)for(var a=10*m,s,b=c=0;(f||b<a)&&(s=h[c]);c++){for(e=
3.11 -0;j=u[e];e++)if(s.value===j.value){s.moved=j.index;j.moved=s.index;u.splice(e,1);b=e=0;break}b+=e}return g.reverse()}function S(a,d,c,e,f){var f=f||{},g=a&&M(a),g=g&&g.ownerDocument,h=f.templateEngine||N;b.ya.ub(c,h,g);c=h.renderTemplate(c,e,f,g);("number"!=typeof c.length||0<c.length&&"number"!=typeof c[0].nodeType)&&i(Error("Template engine must return an array of DOM nodes"));g=q;switch(d){case "replaceChildren":b.e.N(a,c);g=l;break;case "replaceNode":b.a.Xa(a,c);g=l;break;case "ignoreTargetNode":break;
3.12 -default:i(Error("Unknown renderMode: "+d))}g&&(T(c,e),f.afterRender&&b.r.K(f.afterRender,n,[c,e.$data]));return c}function M(a){return a.nodeType?a:0<a.length?a[0]:n}function T(a,d){if(a.length){var c=a[0],e=a[a.length-1];U(c,e,function(a){b.Ca(d,a)});U(c,e,function(a){b.s.hb(a,[d])})}}function U(a,d,c){for(var e,d=b.e.nextSibling(d);a&&(e=a)!==d;)a=b.e.nextSibling(e),(1===e.nodeType||8===e.nodeType)&&c(e)}function V(a,d,c){for(var a=b.g.aa(a),e=b.g.Q,f=0;f<a.length;f++){var g=a[f].key;if(e.hasOwnProperty(g)){var h=
3.13 -e[g];"function"===typeof h?(g=h(a[f].value))&&i(Error(g)):h||i(Error("This template engine does not support the '"+g+"' binding within its templates"))}}a="ko.__tr_ambtns(function($context,$element){return(function(){return{ "+b.g.ba(a)+" } })()})";return c.createJavaScriptEvaluatorBlock(a)+d}function W(a,d,c,e){function f(a){return function(){return j[a]}}function g(){return j}var h=0,j,k;b.j(function(){var m=c&&c instanceof b.z?c:new b.z(b.a.d(c)),p=m.$data;e&&b.cb(a,m);if(j=("function"==typeof d?
3.14 -d(m,a):d)||b.J.instance.getBindings(a,m)){if(0===h){h=1;for(var r in j){var u=b.c[r];u&&8===a.nodeType&&!b.e.I[r]&&i(Error("The binding '"+r+"' cannot be used with virtual elements"));if(u&&"function"==typeof u.init&&(u=(0,u.init)(a,f(r),g,p,m))&&u.controlsDescendantBindings)k!==H&&i(Error("Multiple bindings ("+k+" and "+r+") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.")),k=r}h=2}if(2===h)for(r in j)(u=b.c[r])&&"function"==
3.15 -typeof u.update&&(0,u.update)(a,f(r),g,p,m)}},n,{W:a});return{Mb:k===H}}function X(a,d,c){var e=l,f=1===d.nodeType;f&&b.e.Sa(d);if(f&&c||b.J.instance.nodeHasBindings(d))e=W(d,n,a,c).Mb;e&&Y(a,d,!f)}function Y(a,d,c){for(var e=b.e.firstChild(d);d=e;)e=b.e.nextSibling(d),X(a,d,c)}function Z(a,b){var c=$(a,b);return c?0<c.length?c[c.length-1].nextSibling:a.nextSibling:n}function $(a,b){for(var c=a,e=1,f=[];c=c.nextSibling;){if(G(c)&&(e--,0===e))return f;f.push(c);A(c)&&e++}b||i(Error("Cannot find closing comment tag to match: "+
3.16 -a.nodeValue));return n}function G(a){return 8==a.nodeType&&(J?a.text:a.nodeValue).match(ha)}function A(a){return 8==a.nodeType&&(J?a.text:a.nodeValue).match(ia)}function O(a,b){for(var c=n;a!=c;)c=a,a=a.replace(ja,function(a,c){return b[c]});return a}function ka(){var a=[],d=[];this.save=function(c,e){var f=b.a.i(a,c);0<=f?d[f]=e:(a.push(c),d.push(e))};this.get=function(c){c=b.a.i(a,c);return 0<=c?d[c]:H}}function aa(a,b,c){function e(e){var g=b(a[e]);switch(typeof g){case "boolean":case "number":case "string":case "function":f[e]=
3.17 -g;break;case "object":case "undefined":var h=c.get(g);f[e]=h!==H?h:aa(g,b,c)}}c=c||new ka;a=b(a);if(!("object"==typeof a&&a!==n&&a!==H&&!(a instanceof Date)))return a;var f=a instanceof Array?[]:{};c.save(a,f);var g=a;if(g instanceof Array){for(var h=0;h<g.length;h++)e(h);"function"==typeof g.toJSON&&e("toJSON")}else for(h in g)e(h);return f}function ba(a,d){if(a)if(8==a.nodeType){var c=b.s.Ta(a.nodeValue);c!=n&&d.push({rb:a,Eb:c})}else if(1==a.nodeType)for(var c=0,e=a.childNodes,f=e.length;c<f;c++)ba(e[c],
3.18 -d)}function P(a,d,c,e){b.c[a]={init:function(a){b.a.f.set(a,ca,{});return{controlsDescendantBindings:l}},update:function(a,g,h,j,k){var h=b.a.f.get(a,ca),g=b.a.d(g()),j=!c!==!g,m=!h.Ya;if(m||d||j!==h.pb)m&&(h.Ya=b.a.Ha(b.e.childNodes(a),l)),j?(m||b.e.N(a,b.a.Ha(h.Ya)),b.Da(e?e(k,g):k,a)):b.e.Y(a),h.pb=j}};b.g.Q[a]=q;b.e.I[a]=l}function da(a,d,c){c&&d!==b.k.q(a)&&b.k.T(a,d);d!==b.k.q(a)&&b.r.K(b.a.Aa,n,[a,"change"])}var b="undefined"!==typeof v?v:{};b.b=function(a,d){for(var c=a.split("."),e=b,f=0;f<
3.19 -c.length-1;f++)e=e[c[f]];e[c[c.length-1]]=d};b.p=function(a,b,c){a[b]=c};b.version="2.2.0";b.b("version",b.version);b.a=new function(){function a(a,d){if("input"!==b.a.u(a)||!a.type||"click"!=d.toLowerCase())return q;var c=a.type;return"checkbox"==c||"radio"==c}var d=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,c={},e={};c[/Firefox\/2/i.test(fa.userAgent)?"KeyboardEvent":"UIEvents"]=["keyup","keydown","keypress"];c.MouseEvents="click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave".split(" ");
3.20 -for(var f in c){var g=c[f];if(g.length)for(var h=0,j=g.length;h<j;h++)e[g[h]]=f}var k={propertychange:l},m,c=3;f=x.createElement("div");for(g=f.getElementsByTagName("i");f.innerHTML="<\!--[if gt IE "+ ++c+"]><i></i><![endif]--\>",g[0];);m=4<c?c:H;return{Ma:["authenticity_token",/^__RequestVerificationToken(_.*)?$/],o:function(a,b){for(var d=0,c=a.length;d<c;d++)b(a[d])},i:function(a,b){if("function"==typeof Array.prototype.indexOf)return Array.prototype.indexOf.call(a,b);for(var d=0,c=a.length;d<
3.21 -c;d++)if(a[d]===b)return d;return-1},kb:function(a,b,d){for(var c=0,e=a.length;c<e;c++)if(b.call(d,a[c]))return a[c];return n},ga:function(a,d){var c=b.a.i(a,d);0<=c&&a.splice(c,1)},Fa:function(a){for(var a=a||[],d=[],c=0,e=a.length;c<e;c++)0>b.a.i(d,a[c])&&d.push(a[c]);return d},V:function(a,b){for(var a=a||[],d=[],c=0,e=a.length;c<e;c++)d.push(b(a[c]));return d},fa:function(a,b){for(var a=a||[],d=[],c=0,e=a.length;c<e;c++)b(a[c])&&d.push(a[c]);return d},P:function(a,b){if(b instanceof Array)a.push.apply(a,
3.22 -b);else for(var d=0,c=b.length;d<c;d++)a.push(b[d]);return a},extend:function(a,b){if(b)for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);return a},ka:function(a){for(;a.firstChild;)b.removeNode(a.firstChild)},Gb:function(a){for(var a=b.a.L(a),d=x.createElement("div"),c=0,e=a.length;c<e;c++)d.appendChild(b.A(a[c]));return d},Ha:function(a,d){for(var c=0,e=a.length,g=[];c<e;c++){var f=a[c].cloneNode(l);g.push(d?b.A(f):f)}return g},N:function(a,d){b.a.ka(a);if(d)for(var c=0,e=d.length;c<e;c++)a.appendChild(d[c])},
3.23 -Xa:function(a,d){var c=a.nodeType?[a]:a;if(0<c.length){for(var e=c[0],g=e.parentNode,f=0,h=d.length;f<h;f++)g.insertBefore(d[f],e);f=0;for(h=c.length;f<h;f++)b.removeNode(c[f])}},ab:function(a,b){7>m?a.setAttribute("selected",b):a.selected=b},D:function(a){return(a||"").replace(d,"")},Qb:function(a,d){for(var c=[],e=(a||"").split(d),f=0,g=e.length;f<g;f++){var h=b.a.D(e[f]);""!==h&&c.push(h)}return c},Nb:function(a,b){a=a||"";return b.length>a.length?q:a.substring(0,b.length)===b},sb:function(a,b){if(b.compareDocumentPosition)return 16==
3.24 -(b.compareDocumentPosition(a)&16);for(;a!=n;){if(a==b)return l;a=a.parentNode}return q},X:function(a){return b.a.sb(a,a.ownerDocument)},u:function(a){return a&&a.tagName&&a.tagName.toLowerCase()},n:function(b,d,c){var e=m&&k[d];if(!e&&"undefined"!=typeof E){if(a(b,d))var f=c,c=function(a,b){var d=this.checked;b&&(this.checked=b.mb!==l);f.call(this,a);this.checked=d};E(b).bind(d,c)}else!e&&"function"==typeof b.addEventListener?b.addEventListener(d,c,q):"undefined"!=typeof b.attachEvent?b.attachEvent("on"+
3.25 -d,function(a){c.call(b,a)}):i(Error("Browser doesn't support addEventListener or attachEvent"))},Aa:function(b,d){(!b||!b.nodeType)&&i(Error("element must be a DOM node when calling triggerEvent"));if("undefined"!=typeof E){var c=[];a(b,d)&&c.push({mb:b.checked});E(b).trigger(d,c)}else"function"==typeof x.createEvent?"function"==typeof b.dispatchEvent?(c=x.createEvent(e[d]||"HTMLEvents"),c.initEvent(d,l,l,w,0,0,0,0,0,q,q,q,q,0,b),b.dispatchEvent(c)):i(Error("The supplied element doesn't support dispatchEvent")):
3.26 -"undefined"!=typeof b.fireEvent?(a(b,d)&&(b.checked=b.checked!==l),b.fireEvent("on"+d)):i(Error("Browser doesn't support triggering events"))},d:function(a){return b.$(a)?a():a},ta:function(a){return b.$(a)?a.t():a},da:function(a,d,c){if(d){var e=/[\w-]+/g,f=a.className.match(e)||[];b.a.o(d.match(e),function(a){var d=b.a.i(f,a);0<=d?c||f.splice(d,1):c&&f.push(a)});a.className=f.join(" ")}},bb:function(a,d){var c=b.a.d(d);if(c===n||c===H)c="";if(3===a.nodeType)a.data=c;else{var e=b.e.firstChild(a);
3.27 -!e||3!=e.nodeType||b.e.nextSibling(e)?b.e.N(a,[x.createTextNode(c)]):e.data=c;b.a.vb(a)}},$a:function(a,b){a.name=b;if(7>=m)try{a.mergeAttributes(x.createElement("<input name='"+a.name+"'/>"),q)}catch(d){}},vb:function(a){9<=m&&(a=1==a.nodeType?a:a.parentNode,a.style&&(a.style.zoom=a.style.zoom))},tb:function(a){if(9<=m){var b=a.style.width;a.style.width=0;a.style.width=b}},Kb:function(a,d){for(var a=b.a.d(a),d=b.a.d(d),c=[],e=a;e<=d;e++)c.push(e);return c},L:function(a){for(var b=[],d=0,c=a.length;d<
3.28 -c;d++)b.push(a[d]);return b},Ob:6===m,Pb:7===m,Z:m,Na:function(a,d){for(var c=b.a.L(a.getElementsByTagName("input")).concat(b.a.L(a.getElementsByTagName("textarea"))),e="string"==typeof d?function(a){return a.name===d}:function(a){return d.test(a.name)},f=[],g=c.length-1;0<=g;g--)e(c[g])&&f.push(c[g]);return f},Hb:function(a){return"string"==typeof a&&(a=b.a.D(a))?w.JSON&&w.JSON.parse?w.JSON.parse(a):(new Function("return "+a))():n},wa:function(a,d,c){("undefined"==typeof JSON||"undefined"==typeof JSON.stringify)&&
3.29 -i(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"));return JSON.stringify(b.a.d(a),d,c)},Ib:function(a,d,c){var c=c||{},e=c.params||{},f=c.includeFields||this.Ma,g=a;if("object"==typeof a&&"form"===b.a.u(a))for(var g=a.action,h=f.length-1;0<=h;h--)for(var j=b.a.Na(a,f[h]),k=j.length-1;0<=k;k--)e[j[k].name]=j[k].value;var d=b.a.d(d),m=x.createElement("form");
3.30 -m.style.display="none";m.action=g;m.method="post";for(var v in d)a=x.createElement("input"),a.name=v,a.value=b.a.wa(b.a.d(d[v])),m.appendChild(a);for(v in e)a=x.createElement("input"),a.name=v,a.value=e[v],m.appendChild(a);x.body.appendChild(m);c.submitter?c.submitter(m):m.submit();setTimeout(function(){m.parentNode.removeChild(m)},0)}}};b.b("utils",b.a);b.b("utils.arrayForEach",b.a.o);b.b("utils.arrayFirst",b.a.kb);b.b("utils.arrayFilter",b.a.fa);b.b("utils.arrayGetDistinctValues",b.a.Fa);b.b("utils.arrayIndexOf",
3.31 -b.a.i);b.b("utils.arrayMap",b.a.V);b.b("utils.arrayPushAll",b.a.P);b.b("utils.arrayRemoveItem",b.a.ga);b.b("utils.extend",b.a.extend);b.b("utils.fieldsIncludedWithJsonPost",b.a.Ma);b.b("utils.getFormFields",b.a.Na);b.b("utils.peekObservable",b.a.ta);b.b("utils.postJson",b.a.Ib);b.b("utils.parseJson",b.a.Hb);b.b("utils.registerEventHandler",b.a.n);b.b("utils.stringifyJson",b.a.wa);b.b("utils.range",b.a.Kb);b.b("utils.toggleDomNodeCssClass",b.a.da);b.b("utils.triggerEvent",b.a.Aa);b.b("utils.unwrapObservable",
3.32 -b.a.d);Function.prototype.bind||(Function.prototype.bind=function(a){var b=this,c=Array.prototype.slice.call(arguments),a=c.shift();return function(){return b.apply(a,c.concat(Array.prototype.slice.call(arguments)))}});b.a.f=new function(){var a=0,d="__ko__"+(new Date).getTime(),c={};return{get:function(a,d){var c=b.a.f.getAll(a,q);return c===H?H:c[d]},set:function(a,d,c){c===H&&b.a.f.getAll(a,q)===H||(b.a.f.getAll(a,l)[d]=c)},getAll:function(b,f){var g=b[d];if(!g||!("null"!==g&&c[g])){if(!f)return H;
3.33 -g=b[d]="ko"+a++;c[g]={}}return c[g]},clear:function(a){var b=a[d];return b?(delete c[b],a[d]=n,l):q}}};b.b("utils.domData",b.a.f);b.b("utils.domData.clear",b.a.f.clear);b.a.F=new function(){function a(a,d){var e=b.a.f.get(a,c);e===H&&d&&(e=[],b.a.f.set(a,c,e));return e}function d(c){var e=a(c,q);if(e)for(var e=e.slice(0),j=0;j<e.length;j++)e[j](c);b.a.f.clear(c);"function"==typeof E&&"function"==typeof E.cleanData&&E.cleanData([c]);if(f[c.nodeType])for(e=c.firstChild;c=e;)e=c.nextSibling,8===c.nodeType&&
3.34 -d(c)}var c="__ko_domNodeDisposal__"+(new Date).getTime(),e={1:l,8:l,9:l},f={1:l,9:l};return{Ba:function(b,d){"function"!=typeof d&&i(Error("Callback must be a function"));a(b,l).push(d)},Wa:function(d,e){var f=a(d,q);f&&(b.a.ga(f,e),0==f.length&&b.a.f.set(d,c,H))},A:function(a){if(e[a.nodeType]&&(d(a),f[a.nodeType])){var c=[];b.a.P(c,a.getElementsByTagName("*"));for(var j=0,k=c.length;j<k;j++)d(c[j])}return a},removeNode:function(a){b.A(a);a.parentNode&&a.parentNode.removeChild(a)}}};b.A=b.a.F.A;
3.35 -b.removeNode=b.a.F.removeNode;b.b("cleanNode",b.A);b.b("removeNode",b.removeNode);b.b("utils.domNodeDisposal",b.a.F);b.b("utils.domNodeDisposal.addDisposeCallback",b.a.F.Ba);b.b("utils.domNodeDisposal.removeDisposeCallback",b.a.F.Wa);b.a.sa=function(a){var d;if("undefined"!=typeof E){if((d=E.clean([a]))&&d[0]){for(a=d[0];a.parentNode&&11!==a.parentNode.nodeType;)a=a.parentNode;a.parentNode&&a.parentNode.removeChild(a)}}else{var c=b.a.D(a).toLowerCase();d=x.createElement("div");c=c.match(/^<(thead|tbody|tfoot)/)&&
3.36 -[1,"<table>","</table>"]||!c.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!c.indexOf("<td")||!c.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||[0,"",""];a="ignored<div>"+c[1]+a+c[2]+"</div>";for("function"==typeof w.innerShiv?d.appendChild(w.innerShiv(a)):d.innerHTML=a;c[0]--;)d=d.lastChild;d=b.a.L(d.lastChild.childNodes)}return d};b.a.ca=function(a,d){b.a.ka(a);d=b.a.d(d);if(d!==n&&d!==H)if("string"!=typeof d&&(d=d.toString()),"undefined"!=typeof E)E(a).html(d);else for(var c=
3.37 -b.a.sa(d),e=0;e<c.length;e++)a.appendChild(c[e])};b.b("utils.parseHtmlFragment",b.a.sa);b.b("utils.setHtml",b.a.ca);var Q={};b.s={qa:function(a){"function"!=typeof a&&i(Error("You can only pass a function to ko.memoization.memoize()"));var b=(4294967296*(1+Math.random())|0).toString(16).substring(1)+(4294967296*(1+Math.random())|0).toString(16).substring(1);Q[b]=a;return"<\!--[ko_memo:"+b+"]--\>"},gb:function(a,b){var c=Q[a];c===H&&i(Error("Couldn't find any memo with ID "+a+". Perhaps it's already been unmemoized."));
3.38 -try{return c.apply(n,b||[]),l}finally{delete Q[a]}},hb:function(a,d){var c=[];ba(a,c);for(var e=0,f=c.length;e<f;e++){var g=c[e].rb,h=[g];d&&b.a.P(h,d);b.s.gb(c[e].Eb,h);g.nodeValue="";g.parentNode&&g.parentNode.removeChild(g)}},Ta:function(a){return(a=a.match(/^\[ko_memo\:(.*?)\]$/))?a[1]:n}};b.b("memoization",b.s);b.b("memoization.memoize",b.s.qa);b.b("memoization.unmemoize",b.s.gb);b.b("memoization.parseMemoText",b.s.Ta);b.b("memoization.unmemoizeDomNodeAndDescendants",b.s.hb);b.La={throttle:function(a,
3.39 -d){a.throttleEvaluation=d;var c=n;return b.j({read:a,write:function(b){clearTimeout(c);c=setTimeout(function(){a(b)},d)}})},notify:function(a,d){a.equalityComparer="always"==d?t(q):b.m.fn.equalityComparer;return a}};b.b("extenders",b.La);b.eb=function(a,d,c){this.target=a;this.ha=d;this.qb=c;b.p(this,"dispose",this.B)};b.eb.prototype.B=function(){this.Bb=l;this.qb()};b.S=function(){this.w={};b.a.extend(this,b.S.fn);b.p(this,"subscribe",this.xa);b.p(this,"extend",this.extend);b.p(this,"getSubscriptionsCount",
3.40 -this.xb)};b.S.fn={xa:function(a,d,c){var c=c||"change",a=d?a.bind(d):a,e=new b.eb(this,a,function(){b.a.ga(this.w[c],e)}.bind(this));this.w[c]||(this.w[c]=[]);this.w[c].push(e);return e},notifySubscribers:function(a,d){d=d||"change";this.w[d]&&b.r.K(function(){b.a.o(this.w[d].slice(0),function(b){b&&b.Bb!==l&&b.ha(a)})},this)},xb:function(){var a=0,b;for(b in this.w)this.w.hasOwnProperty(b)&&(a+=this.w[b].length);return a},extend:function(a){var d=this;if(a)for(var c in a){var e=b.La[c];"function"==
3.41 -typeof e&&(d=e(d,a[c]))}return d}};b.Pa=function(a){return"function"==typeof a.xa&&"function"==typeof a.notifySubscribers};b.b("subscribable",b.S);b.b("isSubscribable",b.Pa);var B=[];b.r={lb:function(a){B.push({ha:a,Ka:[]})},end:function(){B.pop()},Va:function(a){b.Pa(a)||i(Error("Only subscribable things can act as dependencies"));if(0<B.length){var d=B[B.length-1];d&&!(0<=b.a.i(d.Ka,a))&&(d.Ka.push(a),d.ha(a))}},K:function(a,b,c){try{return B.push(n),a.apply(b,c||[])}finally{B.pop()}}};var la={undefined:l,
3.42 -"boolean":l,number:l,string:l};b.m=function(a){function d(){if(0<arguments.length){if(!d.equalityComparer||!d.equalityComparer(c,arguments[0]))d.H(),c=arguments[0],d.G();return this}b.r.Va(d);return c}var c=a;b.S.call(d);d.t=function(){return c};d.G=function(){d.notifySubscribers(c)};d.H=function(){d.notifySubscribers(c,"beforeChange")};b.a.extend(d,b.m.fn);b.p(d,"peek",d.t);b.p(d,"valueHasMutated",d.G);b.p(d,"valueWillMutate",d.H);return d};b.m.fn={equalityComparer:function(a,b){return a===n||typeof a in
3.43 -la?a===b:q}};var D=b.m.Jb="__ko_proto__";b.m.fn[D]=b.m;b.la=function(a,d){return a===n||a===H||a[D]===H?q:a[D]===d?l:b.la(a[D],d)};b.$=function(a){return b.la(a,b.m)};b.Qa=function(a){return"function"==typeof a&&a[D]===b.m||"function"==typeof a&&a[D]===b.j&&a.yb?l:q};b.b("observable",b.m);b.b("isObservable",b.$);b.b("isWriteableObservable",b.Qa);b.R=function(a){0==arguments.length&&(a=[]);a!==n&&(a!==H&&!("length"in a))&&i(Error("The argument passed when initializing an observable array must be an array, or null, or undefined."));
3.44 -var d=b.m(a);b.a.extend(d,b.R.fn);return d};b.R.fn={remove:function(a){for(var b=this.t(),c=[],e="function"==typeof a?a:function(b){return b===a},f=0;f<b.length;f++){var g=b[f];e(g)&&(0===c.length&&this.H(),c.push(g),b.splice(f,1),f--)}c.length&&this.G();return c},removeAll:function(a){if(a===H){var d=this.t(),c=d.slice(0);this.H();d.splice(0,d.length);this.G();return c}return!a?[]:this.remove(function(d){return 0<=b.a.i(a,d)})},destroy:function(a){var b=this.t(),c="function"==typeof a?a:function(b){return b===
3.45 -a};this.H();for(var e=b.length-1;0<=e;e--)c(b[e])&&(b[e]._destroy=l);this.G()},destroyAll:function(a){return a===H?this.destroy(t(l)):!a?[]:this.destroy(function(d){return 0<=b.a.i(a,d)})},indexOf:function(a){var d=this();return b.a.i(d,a)},replace:function(a,b){var c=this.indexOf(a);0<=c&&(this.H(),this.t()[c]=b,this.G())}};b.a.o("pop push reverse shift sort splice unshift".split(" "),function(a){b.R.fn[a]=function(){var b=this.t();this.H();b=b[a].apply(b,arguments);this.G();return b}});b.a.o(["slice"],
3.46 -function(a){b.R.fn[a]=function(){var b=this();return b[a].apply(b,arguments)}});b.b("observableArray",b.R);b.j=function(a,d,c){function e(){b.a.o(y,function(a){a.B()});y=[]}function f(){var a=h.throttleEvaluation;a&&0<=a?(clearTimeout(s),s=setTimeout(g,a)):g()}function g(){if(!p)if(m&&v())z();else{p=l;try{var a=b.a.V(y,function(a){return a.target});b.r.lb(function(c){var d;0<=(d=b.a.i(a,c))?a[d]=H:y.push(c.xa(f))});for(var c=r.call(d),e=a.length-1;0<=e;e--)a[e]&&y.splice(e,1)[0].B();m=l;h.notifySubscribers(k,
3.47 -"beforeChange");k=c}finally{b.r.end()}h.notifySubscribers(k);p=q;y.length||z()}}function h(){if(0<arguments.length)return"function"===typeof u?u.apply(d,arguments):i(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.")),this;m||g();b.r.Va(h);return k}function j(){return!m||0<y.length}var k,m=q,p=q,r=a;r&&"object"==typeof r?(c=r,r=c.read):(c=c||{},r||(r=c.read));"function"!=typeof r&&i(Error("Pass a function that returns the value of the ko.computed"));
3.48 -var u=c.write,F=c.disposeWhenNodeIsRemoved||c.W||n,v=c.disposeWhen||c.Ja||t(q),z=e,y=[],s=n;d||(d=c.owner);h.t=function(){m||g();return k};h.wb=function(){return y.length};h.yb="function"===typeof c.write;h.B=function(){z()};h.oa=j;b.S.call(h);b.a.extend(h,b.j.fn);b.p(h,"peek",h.t);b.p(h,"dispose",h.B);b.p(h,"isActive",h.oa);b.p(h,"getDependenciesCount",h.wb);c.deferEvaluation!==l&&g();if(F&&j()){z=function(){b.a.F.Wa(F,arguments.callee);e()};b.a.F.Ba(F,z);var C=v,v=function(){return!b.a.X(F)||C()}}return h};
3.49 -b.Ab=function(a){return b.la(a,b.j)};v=b.m.Jb;b.j[v]=b.m;b.j.fn={};b.j.fn[v]=b.j;b.b("dependentObservable",b.j);b.b("computed",b.j);b.b("isComputed",b.Ab);b.fb=function(a){0==arguments.length&&i(Error("When calling ko.toJS, pass the object you want to convert."));return aa(a,function(a){for(var c=0;b.$(a)&&10>c;c++)a=a();return a})};b.toJSON=function(a,d,c){a=b.fb(a);return b.a.wa(a,d,c)};b.b("toJS",b.fb);b.b("toJSON",b.toJSON);b.k={q:function(a){switch(b.a.u(a)){case "option":return a.__ko__hasDomDataOptionValue__===
3.50 -l?b.a.f.get(a,b.c.options.ra):7>=b.a.Z?a.getAttributeNode("value").specified?a.value:a.text:a.value;case "select":return 0<=a.selectedIndex?b.k.q(a.options[a.selectedIndex]):H;default:return a.value}},T:function(a,d){switch(b.a.u(a)){case "option":switch(typeof d){case "string":b.a.f.set(a,b.c.options.ra,H);"__ko__hasDomDataOptionValue__"in a&&delete a.__ko__hasDomDataOptionValue__;a.value=d;break;default:b.a.f.set(a,b.c.options.ra,d),a.__ko__hasDomDataOptionValue__=l,a.value="number"===typeof d?
3.51 -d:""}break;case "select":for(var c=a.options.length-1;0<=c;c--)if(b.k.q(a.options[c])==d){a.selectedIndex=c;break}break;default:if(d===n||d===H)d="";a.value=d}}};b.b("selectExtensions",b.k);b.b("selectExtensions.readValue",b.k.q);b.b("selectExtensions.writeValue",b.k.T);var ja=/\@ko_token_(\d+)\@/g,ma=["true","false"],na=/^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;b.g={Q:[],aa:function(a){var d=b.a.D(a);if(3>d.length)return[];"{"===d.charAt(0)&&(d=d.substring(1,d.length-1));for(var a=[],
3.52 -c=n,e,f=0;f<d.length;f++){var g=d.charAt(f);if(c===n)switch(g){case '"':case "'":case "/":c=f,e=g}else if(g==e&&"\\"!==d.charAt(f-1)){g=d.substring(c,f+1);a.push(g);var h="@ko_token_"+(a.length-1)+"@",d=d.substring(0,c)+h+d.substring(f+1),f=f-(g.length-h.length),c=n}}e=c=n;for(var j=0,k=n,f=0;f<d.length;f++){g=d.charAt(f);if(c===n)switch(g){case "{":c=f;k=g;e="}";break;case "(":c=f;k=g;e=")";break;case "[":c=f,k=g,e="]"}g===k?j++:g===e&&(j--,0===j&&(g=d.substring(c,f+1),a.push(g),h="@ko_token_"+(a.length-
3.53 -1)+"@",d=d.substring(0,c)+h+d.substring(f+1),f-=g.length-h.length,c=n))}e=[];d=d.split(",");c=0;for(f=d.length;c<f;c++)j=d[c],k=j.indexOf(":"),0<k&&k<j.length-1?(g=j.substring(k+1),e.push({key:O(j.substring(0,k),a),value:O(g,a)})):e.push({unknown:O(j,a)});return e},ba:function(a){for(var d="string"===typeof a?b.g.aa(a):a,c=[],a=[],e,f=0;e=d[f];f++)if(0<c.length&&c.push(","),e.key){var g;a:{g=e.key;var h=b.a.D(g);switch(h.length&&h.charAt(0)){case "'":case '"':break a;default:g="'"+h+"'"}}e=e.value;
3.54 -c.push(g);c.push(":");c.push(e);e=b.a.D(e);0<=b.a.i(ma,b.a.D(e).toLowerCase())?e=q:(h=e.match(na),e=h===n?q:h[1]?"Object("+h[1]+")"+h[2]:e);e&&(0<a.length&&a.push(", "),a.push(g+" : function(__ko_value) { "+e+" = __ko_value; }"))}else e.unknown&&c.push(e.unknown);d=c.join("");0<a.length&&(d=d+", '_ko_property_writers' : { "+a.join("")+" } ");return d},Db:function(a,d){for(var c=0;c<a.length;c++)if(b.a.D(a[c].key)==d)return l;return q},ea:function(a,d,c,e,f){if(!a||!b.Qa(a)){if((a=d()._ko_property_writers)&&
3.55 -a[c])a[c](e)}else(!f||a.t()!==e)&&a(e)}};b.b("expressionRewriting",b.g);b.b("expressionRewriting.bindingRewriteValidators",b.g.Q);b.b("expressionRewriting.parseObjectLiteral",b.g.aa);b.b("expressionRewriting.preProcessBindings",b.g.ba);b.b("jsonExpressionRewriting",b.g);b.b("jsonExpressionRewriting.insertPropertyAccessorsIntoJson",b.g.ba);var J="<\!--test--\>"===x.createComment("test").text,ia=J?/^<\!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*--\>$/:/^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/,ha=J?/^<\!--\s*\/ko\s*--\>$/:
3.56 -/^\s*\/ko\s*$/,oa={ul:l,ol:l};b.e={I:{},childNodes:function(a){return A(a)?$(a):a.childNodes},Y:function(a){if(A(a))for(var a=b.e.childNodes(a),d=0,c=a.length;d<c;d++)b.removeNode(a[d]);else b.a.ka(a)},N:function(a,d){if(A(a)){b.e.Y(a);for(var c=a.nextSibling,e=0,f=d.length;e<f;e++)c.parentNode.insertBefore(d[e],c)}else b.a.N(a,d)},Ua:function(a,b){A(a)?a.parentNode.insertBefore(b,a.nextSibling):a.firstChild?a.insertBefore(b,a.firstChild):a.appendChild(b)},Oa:function(a,d,c){c?A(a)?a.parentNode.insertBefore(d,
3.57 -c.nextSibling):c.nextSibling?a.insertBefore(d,c.nextSibling):a.appendChild(d):b.e.Ua(a,d)},firstChild:function(a){return!A(a)?a.firstChild:!a.nextSibling||G(a.nextSibling)?n:a.nextSibling},nextSibling:function(a){A(a)&&(a=Z(a));return a.nextSibling&&G(a.nextSibling)?n:a.nextSibling},ib:function(a){return(a=A(a))?a[1]:n},Sa:function(a){if(oa[b.a.u(a)]){var d=a.firstChild;if(d){do if(1===d.nodeType){var c;c=d.firstChild;var e=n;if(c){do if(e)e.push(c);else if(A(c)){var f=Z(c,l);f?c=f:e=[c]}else G(c)&&
3.58 -(e=[c]);while(c=c.nextSibling)}if(c=e){e=d.nextSibling;for(f=0;f<c.length;f++)e?a.insertBefore(c[f],e):a.appendChild(c[f])}}while(d=d.nextSibling)}}}};b.b("virtualElements",b.e);b.b("virtualElements.allowedBindings",b.e.I);b.b("virtualElements.emptyNode",b.e.Y);b.b("virtualElements.insertAfter",b.e.Oa);b.b("virtualElements.prepend",b.e.Ua);b.b("virtualElements.setDomNodeChildren",b.e.N);b.J=function(){this.Ga={}};b.a.extend(b.J.prototype,{nodeHasBindings:function(a){switch(a.nodeType){case 1:return a.getAttribute("data-bind")!=
3.59 -n;case 8:return b.e.ib(a)!=n;default:return q}},getBindings:function(a,b){var c=this.getBindingsString(a,b);return c?this.parseBindingsString(c,b,a):n},getBindingsString:function(a){switch(a.nodeType){case 1:return a.getAttribute("data-bind");case 8:return b.e.ib(a);default:return n}},parseBindingsString:function(a,d,c){try{var e;if(!(e=this.Ga[a])){var f=this.Ga,g="with($context){with($data||{}){return{"+b.g.ba(a)+"}}}";e=f[a]=new Function("$context","$element",g)}return e(d,c)}catch(h){i(Error("Unable to parse bindings.\nMessage: "+
3.60 -h+";\nBindings value: "+a))}}});b.J.instance=new b.J;b.b("bindingProvider",b.J);b.c={};b.z=function(a,d,c){d?(b.a.extend(this,d),this.$parentContext=d,this.$parent=d.$data,this.$parents=(d.$parents||[]).slice(0),this.$parents.unshift(this.$parent)):(this.$parents=[],this.$root=a,this.ko=b);this.$data=a;c&&(this[c]=a)};b.z.prototype.createChildContext=function(a,d){return new b.z(a,this,d)};b.z.prototype.extend=function(a){var d=b.a.extend(new b.z,this);return b.a.extend(d,a)};b.cb=function(a,d){if(2==
3.61 -arguments.length)b.a.f.set(a,"__ko_bindingContext__",d);else return b.a.f.get(a,"__ko_bindingContext__")};b.Ea=function(a,d,c){1===a.nodeType&&b.e.Sa(a);return W(a,d,c,l)};b.Da=function(a,b){(1===b.nodeType||8===b.nodeType)&&Y(a,b,l)};b.Ca=function(a,b){b&&(1!==b.nodeType&&8!==b.nodeType)&&i(Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node"));b=b||w.document.body;X(a,b,l)};b.ja=function(a){switch(a.nodeType){case 1:case 8:var d=b.cb(a);if(d)return d;
3.62 -if(a.parentNode)return b.ja(a.parentNode)}return H};b.ob=function(a){return(a=b.ja(a))?a.$data:H};b.b("bindingHandlers",b.c);b.b("applyBindings",b.Ca);b.b("applyBindingsToDescendants",b.Da);b.b("applyBindingsToNode",b.Ea);b.b("contextFor",b.ja);b.b("dataFor",b.ob);var ea={"class":"className","for":"htmlFor"};b.c.attr={update:function(a,d){var c=b.a.d(d())||{},e;for(e in c)if("string"==typeof e){var f=b.a.d(c[e]),g=f===q||f===n||f===H;g&&a.removeAttribute(e);8>=b.a.Z&&e in ea?(e=ea[e],g?a.removeAttribute(e):
3.63 -a[e]=f):g||a.setAttribute(e,f.toString());"name"===e&&b.a.$a(a,g?"":f.toString())}}};b.c.checked={init:function(a,d,c){b.a.n(a,"click",function(){var e;if("checkbox"==a.type)e=a.checked;else if("radio"==a.type&&a.checked)e=a.value;else return;var f=d(),g=b.a.d(f);"checkbox"==a.type&&g instanceof Array?(e=b.a.i(g,a.value),a.checked&&0>e?f.push(a.value):!a.checked&&0<=e&&f.splice(e,1)):b.g.ea(f,c,"checked",e,l)});"radio"==a.type&&!a.name&&b.c.uniqueName.init(a,t(l))},update:function(a,d){var c=b.a.d(d());
3.64 -"checkbox"==a.type?a.checked=c instanceof Array?0<=b.a.i(c,a.value):c:"radio"==a.type&&(a.checked=a.value==c)}};b.c.css={update:function(a,d){var c=b.a.d(d());if("object"==typeof c)for(var e in c){var f=b.a.d(c[e]);b.a.da(a,e,f)}else c=String(c||""),b.a.da(a,a.__ko__cssValue,q),a.__ko__cssValue=c,b.a.da(a,c,l)}};b.c.enable={update:function(a,d){var c=b.a.d(d());c&&a.disabled?a.removeAttribute("disabled"):!c&&!a.disabled&&(a.disabled=l)}};b.c.disable={update:function(a,d){b.c.enable.update(a,function(){return!b.a.d(d())})}};
3.65 -b.c.event={init:function(a,d,c,e){var f=d()||{},g;for(g in f)(function(){var f=g;"string"==typeof f&&b.a.n(a,f,function(a){var g,m=d()[f];if(m){var p=c();try{var r=b.a.L(arguments);r.unshift(e);g=m.apply(e,r)}finally{g!==l&&(a.preventDefault?a.preventDefault():a.returnValue=q)}p[f+"Bubble"]===q&&(a.cancelBubble=l,a.stopPropagation&&a.stopPropagation())}})})()}};b.c.foreach={Ra:function(a){return function(){var d=a(),c=b.a.ta(d);if(!c||"number"==typeof c.length)return{foreach:d,templateEngine:b.C.na};
3.66 -b.a.d(d);return{foreach:c.data,as:c.as,includeDestroyed:c.includeDestroyed,afterAdd:c.afterAdd,beforeRemove:c.beforeRemove,afterRender:c.afterRender,beforeMove:c.beforeMove,afterMove:c.afterMove,templateEngine:b.C.na}}},init:function(a,d){return b.c.template.init(a,b.c.foreach.Ra(d))},update:function(a,d,c,e,f){return b.c.template.update(a,b.c.foreach.Ra(d),c,e,f)}};b.g.Q.foreach=q;b.e.I.foreach=l;b.c.hasfocus={init:function(a,d,c){function e(e){a.__ko_hasfocusUpdating=l;var f=a.ownerDocument;"activeElement"in
3.67 -f&&(e=f.activeElement===a);f=d();b.g.ea(f,c,"hasfocus",e,l);a.__ko_hasfocusUpdating=q}var f=e.bind(n,l),g=e.bind(n,q);b.a.n(a,"focus",f);b.a.n(a,"focusin",f);b.a.n(a,"blur",g);b.a.n(a,"focusout",g)},update:function(a,d){var c=b.a.d(d());a.__ko_hasfocusUpdating||(c?a.focus():a.blur(),b.r.K(b.a.Aa,n,[a,c?"focusin":"focusout"]))}};b.c.html={init:function(){return{controlsDescendantBindings:l}},update:function(a,d){b.a.ca(a,d())}};var ca="__ko_withIfBindingData";P("if");P("ifnot",q,l);P("with",l,q,function(a,
3.68 -b){return a.createChildContext(b)});b.c.options={update:function(a,d,c){"select"!==b.a.u(a)&&i(Error("options binding applies only to SELECT elements"));for(var e=0==a.length,f=b.a.V(b.a.fa(a.childNodes,function(a){return a.tagName&&"option"===b.a.u(a)&&a.selected}),function(a){return b.k.q(a)||a.innerText||a.textContent}),g=a.scrollTop,h=b.a.d(d());0<a.length;)b.A(a.options[0]),a.remove(0);if(h){var c=c(),j=c.optionsIncludeDestroyed;"number"!=typeof h.length&&(h=[h]);if(c.optionsCaption){var k=x.createElement("option");
3.69 -b.a.ca(k,c.optionsCaption);b.k.T(k,H);a.appendChild(k)}for(var d=0,m=h.length;d<m;d++){var p=h[d];if(!p||!p._destroy||j){var k=x.createElement("option"),r=function(a,b,c){var d=typeof b;return"function"==d?b(a):"string"==d?a[b]:c},u=r(p,c.optionsValue,p);b.k.T(k,b.a.d(u));p=r(p,c.optionsText,u);b.a.bb(k,p);a.appendChild(k)}}h=a.getElementsByTagName("option");d=j=0;for(m=h.length;d<m;d++)0<=b.a.i(f,b.k.q(h[d]))&&(b.a.ab(h[d],l),j++);a.scrollTop=g;e&&"value"in c&&da(a,b.a.ta(c.value),l);b.a.tb(a)}}};
3.70 -b.c.options.ra="__ko.optionValueDomData__";b.c.selectedOptions={init:function(a,d,c){b.a.n(a,"change",function(){var e=d(),f=[];b.a.o(a.getElementsByTagName("option"),function(a){a.selected&&f.push(b.k.q(a))});b.g.ea(e,c,"value",f)})},update:function(a,d){"select"!=b.a.u(a)&&i(Error("values binding applies only to SELECT elements"));var c=b.a.d(d());c&&"number"==typeof c.length&&b.a.o(a.getElementsByTagName("option"),function(a){var d=0<=b.a.i(c,b.k.q(a));b.a.ab(a,d)})}};b.c.style={update:function(a,
3.71 -d){var c=b.a.d(d()||{}),e;for(e in c)if("string"==typeof e){var f=b.a.d(c[e]);a.style[e]=f||""}}};b.c.submit={init:function(a,d,c,e){"function"!=typeof d()&&i(Error("The value for a submit binding must be a function"));b.a.n(a,"submit",function(b){var c,h=d();try{c=h.call(e,a)}finally{c!==l&&(b.preventDefault?b.preventDefault():b.returnValue=q)}})}};b.c.text={update:function(a,d){b.a.bb(a,d())}};b.e.I.text=l;b.c.uniqueName={init:function(a,d){if(d()){var c="ko_unique_"+ ++b.c.uniqueName.nb;b.a.$a(a,
3.72 -c)}}};b.c.uniqueName.nb=0;b.c.value={init:function(a,d,c){function e(){h=q;var e=d(),f=b.k.q(a);b.g.ea(e,c,"value",f)}var f=["change"],g=c().valueUpdate,h=q;g&&("string"==typeof g&&(g=[g]),b.a.P(f,g),f=b.a.Fa(f));if(b.a.Z&&("input"==a.tagName.toLowerCase()&&"text"==a.type&&"off"!=a.autocomplete&&(!a.form||"off"!=a.form.autocomplete))&&-1==b.a.i(f,"propertychange"))b.a.n(a,"propertychange",function(){h=l}),b.a.n(a,"blur",function(){h&&e()});b.a.o(f,function(c){var d=e;b.a.Nb(c,"after")&&(d=function(){setTimeout(e,
3.73 -0)},c=c.substring(5));b.a.n(a,c,d)})},update:function(a,d){var c="select"===b.a.u(a),e=b.a.d(d()),f=b.k.q(a),g=e!=f;0===e&&(0!==f&&"0"!==f)&&(g=l);g&&(f=function(){b.k.T(a,e)},f(),c&&setTimeout(f,0));c&&0<a.length&&da(a,e,q)}};b.c.visible={update:function(a,d){var c=b.a.d(d()),e="none"!=a.style.display;c&&!e?a.style.display="":!c&&e&&(a.style.display="none")}};b.c.click={init:function(a,d,c,e){return b.c.event.init.call(this,a,function(){var a={};a.click=d();return a},c,e)}};b.v=function(){};b.v.prototype.renderTemplateSource=
3.74 -function(){i(Error("Override renderTemplateSource"))};b.v.prototype.createJavaScriptEvaluatorBlock=function(){i(Error("Override createJavaScriptEvaluatorBlock"))};b.v.prototype.makeTemplateSource=function(a,d){if("string"==typeof a){var d=d||x,c=d.getElementById(a);c||i(Error("Cannot find template with ID "+a));return new b.l.h(c)}if(1==a.nodeType||8==a.nodeType)return new b.l.O(a);i(Error("Unknown template type: "+a))};b.v.prototype.renderTemplate=function(a,b,c,e){a=this.makeTemplateSource(a,e);
3.75 -return this.renderTemplateSource(a,b,c)};b.v.prototype.isTemplateRewritten=function(a,b){return this.allowTemplateRewriting===q?l:this.makeTemplateSource(a,b).data("isRewritten")};b.v.prototype.rewriteTemplate=function(a,b,c){a=this.makeTemplateSource(a,c);b=b(a.text());a.text(b);a.data("isRewritten",l)};b.b("templateEngine",b.v);var pa=/(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi,qa=/<\!--\s*ko\b\s*([\s\S]*?)\s*--\>/g;b.ya={ub:function(a,
3.76 -d,c){d.isTemplateRewritten(a,c)||d.rewriteTemplate(a,function(a){return b.ya.Fb(a,d)},c)},Fb:function(a,b){return a.replace(pa,function(a,e,f,g,h,j,k){return V(k,e,b)}).replace(qa,function(a,e){return V(e,"<\!-- ko --\>",b)})},jb:function(a){return b.s.qa(function(d,c){d.nextSibling&&b.Ea(d.nextSibling,a,c)})}};b.b("__tr_ambtns",b.ya.jb);b.l={};b.l.h=function(a){this.h=a};b.l.h.prototype.text=function(){var a=b.a.u(this.h),a="script"===a?"text":"textarea"===a?"value":"innerHTML";if(0==arguments.length)return this.h[a];
3.77 -var d=arguments[0];"innerHTML"===a?b.a.ca(this.h,d):this.h[a]=d};b.l.h.prototype.data=function(a){if(1===arguments.length)return b.a.f.get(this.h,"templateSourceData_"+a);b.a.f.set(this.h,"templateSourceData_"+a,arguments[1])};b.l.O=function(a){this.h=a};b.l.O.prototype=new b.l.h;b.l.O.prototype.text=function(){if(0==arguments.length){var a=b.a.f.get(this.h,"__ko_anon_template__")||{};a.za===H&&a.ia&&(a.za=a.ia.innerHTML);return a.za}b.a.f.set(this.h,"__ko_anon_template__",{za:arguments[0]})};b.l.h.prototype.nodes=
3.78 -function(){if(0==arguments.length)return(b.a.f.get(this.h,"__ko_anon_template__")||{}).ia;b.a.f.set(this.h,"__ko_anon_template__",{ia:arguments[0]})};b.b("templateSources",b.l);b.b("templateSources.domElement",b.l.h);b.b("templateSources.anonymousTemplate",b.l.O);var N;b.va=function(a){a!=H&&!(a instanceof b.v)&&i(Error("templateEngine must inherit from ko.templateEngine"));N=a};b.ua=function(a,d,c,e,f){c=c||{};(c.templateEngine||N)==H&&i(Error("Set a template engine before calling renderTemplate"));
3.79 -f=f||"replaceChildren";if(e){var g=M(e);return b.j(function(){var h=d&&d instanceof b.z?d:new b.z(b.a.d(d)),j="function"==typeof a?a(h.$data,h):a,h=S(e,f,j,h,c);"replaceNode"==f&&(e=h,g=M(e))},n,{Ja:function(){return!g||!b.a.X(g)},W:g&&"replaceNode"==f?g.parentNode:g})}return b.s.qa(function(e){b.ua(a,d,c,e,"replaceNode")})};b.Lb=function(a,d,c,e,f){function g(a,b){T(b,j);c.afterRender&&c.afterRender(b,a)}function h(d,e){j=f.createChildContext(b.a.d(d),c.as);j.$index=e;var g="function"==typeof a?
3.80 -a(d,j):a;return S(n,"ignoreTargetNode",g,j,c)}var j;return b.j(function(){var a=b.a.d(d)||[];"undefined"==typeof a.length&&(a=[a]);a=b.a.fa(a,function(a){return c.includeDestroyed||a===H||a===n||!b.a.d(a._destroy)});b.r.K(b.a.Za,n,[e,a,h,c,g])},n,{W:e})};b.c.template={init:function(a,d){var c=b.a.d(d());if("string"!=typeof c&&!c.name&&(1==a.nodeType||8==a.nodeType))c=1==a.nodeType?a.childNodes:b.e.childNodes(a),c=b.a.Gb(c),(new b.l.O(a)).nodes(c);return{controlsDescendantBindings:l}},update:function(a,
3.81 -d,c,e,f){var d=b.a.d(d()),c={},e=l,g,h=n;"string"!=typeof d&&(c=d,d=c.name,"if"in c&&(e=b.a.d(c["if"])),e&&"ifnot"in c&&(e=!b.a.d(c.ifnot)),g=b.a.d(c.data));"foreach"in c?h=b.Lb(d||a,e&&c.foreach||[],c,a,f):e?(f="data"in c?f.createChildContext(g,c.as):f,h=b.ua(d||a,f,c,a)):b.e.Y(a);f=h;(g=b.a.f.get(a,"__ko__templateComputedDomDataKey__"))&&"function"==typeof g.B&&g.B();b.a.f.set(a,"__ko__templateComputedDomDataKey__",f&&f.oa()?f:H)}};b.g.Q.template=function(a){a=b.g.aa(a);return 1==a.length&&a[0].unknown||
3.82 -b.g.Db(a,"name")?n:"This template engine does not support anonymous templates nested within its templates"};b.e.I.template=l;b.b("setTemplateEngine",b.va);b.b("renderTemplate",b.ua);b.a.Ia=function(a,b,c){a=a||[];b=b||[];return a.length<=b.length?R(a,b,"added","deleted",c):R(b,a,"deleted","added",c)};b.b("utils.compareArrays",b.a.Ia);b.a.Za=function(a,d,c,e,f){function g(a,b){s=k[b];v!==b&&(y[a]=s);s.ma(v++);L(s.M);r.push(s);z.push(s)}function h(a,c){if(a)for(var d=0,e=c.length;d<e;d++)c[d]&&b.a.o(c[d].M,
3.83 -function(b){a(b,d,c[d].U)})}for(var d=d||[],e=e||{},j=b.a.f.get(a,"setDomNodeChildrenFromArrayMapping_lastMappingResult")===H,k=b.a.f.get(a,"setDomNodeChildrenFromArrayMapping_lastMappingResult")||[],m=b.a.V(k,function(a){return a.U}),p=b.a.Ia(m,d),r=[],u=0,v=0,A=[],z=[],d=[],y=[],m=[],s,C=0,B,D;B=p[C];C++)switch(D=B.moved,B.status){case "deleted":D===H&&(s=k[u],s.j&&s.j.B(),A.push.apply(A,L(s.M)),e.beforeRemove&&(d[C]=s,z.push(s)));u++;break;case "retained":g(C,u++);break;case "added":D!==H?g(C,
3.84 -D):(s={U:B.value,ma:b.m(v++)},r.push(s),z.push(s),j||(m[C]=s))}h(e.beforeMove,y);b.a.o(A,e.beforeRemove?b.A:b.removeNode);for(var C=0,j=b.e.firstChild(a),G;s=z[C];C++){s.M||b.a.extend(s,ga(a,c,s.U,f,s.ma));for(u=0;p=s.M[u];j=p.nextSibling,G=p,u++)p!==j&&b.e.Oa(a,p,G);!s.zb&&f&&(f(s.U,s.M,s.ma),s.zb=l)}h(e.beforeRemove,d);h(e.afterMove,y);h(e.afterAdd,m);b.a.f.set(a,"setDomNodeChildrenFromArrayMapping_lastMappingResult",r)};b.b("utils.setDomNodeChildrenFromArrayMapping",b.a.Za);b.C=function(){this.allowTemplateRewriting=
3.85 -q};b.C.prototype=new b.v;b.C.prototype.renderTemplateSource=function(a){var d=!(9>b.a.Z)&&a.nodes?a.nodes():n;if(d)return b.a.L(d.cloneNode(l).childNodes);a=a.text();return b.a.sa(a)};b.C.na=new b.C;b.va(b.C.na);b.b("nativeTemplateEngine",b.C);b.pa=function(){var a=this.Cb=function(){if("undefined"==typeof E||!E.tmpl)return 0;try{if(0<=E.tmpl.tag.tmpl.open.toString().indexOf("__"))return 2}catch(a){}return 1}();this.renderTemplateSource=function(b,c,e){e=e||{};2>a&&i(Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later."));
3.86 -var f=b.data("precompiled");f||(f=b.text()||"",f=E.template(n,"{{ko_with $item.koBindingContext}}"+f+"{{/ko_with}}"),b.data("precompiled",f));b=[c.$data];c=E.extend({koBindingContext:c},e.templateOptions);c=E.tmpl(f,b,c);c.appendTo(x.createElement("div"));E.fragments={};return c};this.createJavaScriptEvaluatorBlock=function(a){return"{{ko_code ((function() { return "+a+" })()) }}"};this.addTemplate=function(a,b){x.write("<script type='text/html' id='"+a+"'>"+b+"<\/script>")};0<a&&(E.tmpl.tag.ko_code=
3.87 -{open:"__.push($1 || '');"},E.tmpl.tag.ko_with={open:"with($1) {",close:"} "})};b.pa.prototype=new b.v;v=new b.pa;0<v.Cb&&b.va(v);b.b("jqueryTmplTemplateEngine",b.pa)}"function"===typeof require&&"object"===typeof exports&&"object"===typeof module?K(module.exports||exports):"function"===typeof define&&define.amd?define(["exports"],K):K(w.ko={});l;
3.88 -})();