1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/ko/fx/src/main/resources/org/apidesign/bck2brwsr/kofx/knockout-2.2.1.js Wed Jun 26 20:11:13 2013 +0200
1.3 @@ -0,0 +1,3594 @@
1.4 +// Knockout JavaScript library v2.2.1
1.5 +// (c) Steven Sanderson - http://knockoutjs.com/
1.6 +// License: MIT (http://www.opensource.org/licenses/mit-license.php)
1.7 +
1.8 +(function(){
1.9 +var DEBUG=true;
1.10 +(function(window,document,navigator,jQuery,undefined){
1.11 +!function(factory) {
1.12 + // Support three module loading scenarios
1.13 + if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
1.14 + // [1] CommonJS/Node.js
1.15 + var target = module['exports'] || exports; // module.exports is for Node.js
1.16 + factory(target);
1.17 + } else if (typeof define === 'function' && define['amd']) {
1.18 + // [2] AMD anonymous module
1.19 + define(['exports'], factory);
1.20 + } else {
1.21 + // [3] No module loader (plain <script> tag) - put directly in global namespace
1.22 + factory(window['ko'] = {});
1.23 + }
1.24 +}(function(koExports){
1.25 +// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
1.26 +// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
1.27 +var ko = typeof koExports !== 'undefined' ? koExports : {};
1.28 +// Google Closure Compiler helpers (used only to make the minified file smaller)
1.29 +ko.exportSymbol = function(koPath, object) {
1.30 + var tokens = koPath.split(".");
1.31 +
1.32 + // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
1.33 + // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
1.34 + var target = ko;
1.35 +
1.36 + for (var i = 0; i < tokens.length - 1; i++)
1.37 + target = target[tokens[i]];
1.38 + target[tokens[tokens.length - 1]] = object;
1.39 +};
1.40 +ko.exportProperty = function(owner, publicName, object) {
1.41 + owner[publicName] = object;
1.42 +};
1.43 +ko.version = "2.2.1";
1.44 +
1.45 +ko.exportSymbol('version', ko.version);
1.46 +ko.utils = new (function () {
1.47 + var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
1.48 +
1.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)
1.50 + var knownEvents = {}, knownEventTypesByEventName = {};
1.51 + var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';
1.52 + knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
1.53 + knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
1.54 + for (var eventType in knownEvents) {
1.55 + var knownEventsForType = knownEvents[eventType];
1.56 + if (knownEventsForType.length) {
1.57 + for (var i = 0, j = knownEventsForType.length; i < j; i++)
1.58 + knownEventTypesByEventName[knownEventsForType[i]] = eventType;
1.59 + }
1.60 + }
1.61 + var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
1.62 +
1.63 + // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
1.64 + // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
1.65 + // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
1.66 + // If there is a future need to detect specific versions of IE10+, we will amend this.
1.67 + var ieVersion = (function() {
1.68 + var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
1.69 +
1.70 + // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
1.71 + while (
1.72 + div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
1.73 + iElems[0]
1.74 + );
1.75 + return version > 4 ? version : undefined;
1.76 + }());
1.77 + var isIe6 = ieVersion === 6,
1.78 + isIe7 = ieVersion === 7;
1.79 +
1.80 + function isClickOnCheckableElement(element, eventType) {
1.81 + if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
1.82 + if (eventType.toLowerCase() != "click") return false;
1.83 + var inputType = element.type;
1.84 + return (inputType == "checkbox") || (inputType == "radio");
1.85 + }
1.86 +
1.87 + return {
1.88 + fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
1.89 +
1.90 + arrayForEach: function (array, action) {
1.91 + for (var i = 0, j = array.length; i < j; i++)
1.92 + action(array[i]);
1.93 + },
1.94 +
1.95 + arrayIndexOf: function (array, item) {
1.96 + if (typeof Array.prototype.indexOf == "function")
1.97 + return Array.prototype.indexOf.call(array, item);
1.98 + for (var i = 0, j = array.length; i < j; i++)
1.99 + if (array[i] === item)
1.100 + return i;
1.101 + return -1;
1.102 + },
1.103 +
1.104 + arrayFirst: function (array, predicate, predicateOwner) {
1.105 + for (var i = 0, j = array.length; i < j; i++)
1.106 + if (predicate.call(predicateOwner, array[i]))
1.107 + return array[i];
1.108 + return null;
1.109 + },
1.110 +
1.111 + arrayRemoveItem: function (array, itemToRemove) {
1.112 + var index = ko.utils.arrayIndexOf(array, itemToRemove);
1.113 + if (index >= 0)
1.114 + array.splice(index, 1);
1.115 + },
1.116 +
1.117 + arrayGetDistinctValues: function (array) {
1.118 + array = array || [];
1.119 + var result = [];
1.120 + for (var i = 0, j = array.length; i < j; i++) {
1.121 + if (ko.utils.arrayIndexOf(result, array[i]) < 0)
1.122 + result.push(array[i]);
1.123 + }
1.124 + return result;
1.125 + },
1.126 +
1.127 + arrayMap: function (array, mapping) {
1.128 + array = array || [];
1.129 + var result = [];
1.130 + for (var i = 0, j = array.length; i < j; i++)
1.131 + result.push(mapping(array[i]));
1.132 + return result;
1.133 + },
1.134 +
1.135 + arrayFilter: function (array, predicate) {
1.136 + array = array || [];
1.137 + var result = [];
1.138 + for (var i = 0, j = array.length; i < j; i++)
1.139 + if (predicate(array[i]))
1.140 + result.push(array[i]);
1.141 + return result;
1.142 + },
1.143 +
1.144 + arrayPushAll: function (array, valuesToPush) {
1.145 + if (valuesToPush instanceof Array)
1.146 + array.push.apply(array, valuesToPush);
1.147 + else
1.148 + for (var i = 0, j = valuesToPush.length; i < j; i++)
1.149 + array.push(valuesToPush[i]);
1.150 + return array;
1.151 + },
1.152 +
1.153 + extend: function (target, source) {
1.154 + if (source) {
1.155 + for(var prop in source) {
1.156 + if(source.hasOwnProperty(prop)) {
1.157 + target[prop] = source[prop];
1.158 + }
1.159 + }
1.160 + }
1.161 + return target;
1.162 + },
1.163 +
1.164 + emptyDomNode: function (domNode) {
1.165 + while (domNode.firstChild) {
1.166 + ko.removeNode(domNode.firstChild);
1.167 + }
1.168 + },
1.169 +
1.170 + moveCleanedNodesToContainerElement: function(nodes) {
1.171 + // Ensure it's a real array, as we're about to reparent the nodes and
1.172 + // we don't want the underlying collection to change while we're doing that.
1.173 + var nodesArray = ko.utils.makeArray(nodes);
1.174 +
1.175 + var container = document.createElement('div');
1.176 + for (var i = 0, j = nodesArray.length; i < j; i++) {
1.177 + container.appendChild(ko.cleanNode(nodesArray[i]));
1.178 + }
1.179 + return container;
1.180 + },
1.181 +
1.182 + cloneNodes: function (nodesArray, shouldCleanNodes) {
1.183 + for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
1.184 + var clonedNode = nodesArray[i].cloneNode(true);
1.185 + newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
1.186 + }
1.187 + return newNodesArray;
1.188 + },
1.189 +
1.190 + setDomNodeChildren: function (domNode, childNodes) {
1.191 + ko.utils.emptyDomNode(domNode);
1.192 + if (childNodes) {
1.193 + for (var i = 0, j = childNodes.length; i < j; i++)
1.194 + domNode.appendChild(childNodes[i]);
1.195 + }
1.196 + },
1.197 +
1.198 + replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
1.199 + var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
1.200 + if (nodesToReplaceArray.length > 0) {
1.201 + var insertionPoint = nodesToReplaceArray[0];
1.202 + var parent = insertionPoint.parentNode;
1.203 + for (var i = 0, j = newNodesArray.length; i < j; i++)
1.204 + parent.insertBefore(newNodesArray[i], insertionPoint);
1.205 + for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
1.206 + ko.removeNode(nodesToReplaceArray[i]);
1.207 + }
1.208 + }
1.209 + },
1.210 +
1.211 + setOptionNodeSelectionState: function (optionNode, isSelected) {
1.212 + // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
1.213 + if (ieVersion < 7)
1.214 + optionNode.setAttribute("selected", isSelected);
1.215 + else
1.216 + optionNode.selected = isSelected;
1.217 + },
1.218 +
1.219 + stringTrim: function (string) {
1.220 + return (string || "").replace(stringTrimRegex, "");
1.221 + },
1.222 +
1.223 + stringTokenize: function (string, delimiter) {
1.224 + var result = [];
1.225 + var tokens = (string || "").split(delimiter);
1.226 + for (var i = 0, j = tokens.length; i < j; i++) {
1.227 + var trimmed = ko.utils.stringTrim(tokens[i]);
1.228 + if (trimmed !== "")
1.229 + result.push(trimmed);
1.230 + }
1.231 + return result;
1.232 + },
1.233 +
1.234 + stringStartsWith: function (string, startsWith) {
1.235 + string = string || "";
1.236 + if (startsWith.length > string.length)
1.237 + return false;
1.238 + return string.substring(0, startsWith.length) === startsWith;
1.239 + },
1.240 +
1.241 + domNodeIsContainedBy: function (node, containedByNode) {
1.242 + if (containedByNode.compareDocumentPosition)
1.243 + return (containedByNode.compareDocumentPosition(node) & 16) == 16;
1.244 + while (node != null) {
1.245 + if (node == containedByNode)
1.246 + return true;
1.247 + node = node.parentNode;
1.248 + }
1.249 + return false;
1.250 + },
1.251 +
1.252 + domNodeIsAttachedToDocument: function (node) {
1.253 + return ko.utils.domNodeIsContainedBy(node, node.ownerDocument);
1.254 + },
1.255 +
1.256 + tagNameLower: function(element) {
1.257 + // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
1.258 + // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
1.259 + // we don't need to do the .toLowerCase() as it will always be lower case anyway.
1.260 + return element && element.tagName && element.tagName.toLowerCase();
1.261 + },
1.262 +
1.263 + registerEventHandler: function (element, eventType, handler) {
1.264 + var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
1.265 + if (!mustUseAttachEvent && typeof jQuery != "undefined") {
1.266 + if (isClickOnCheckableElement(element, eventType)) {
1.267 + // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
1.268 + // it toggles the element checked state *after* the click event handlers run, whereas native
1.269 + // click events toggle the checked state *before* the event handler.
1.270 + // Fix this by intecepting the handler and applying the correct checkedness before it runs.
1.271 + var originalHandler = handler;
1.272 + handler = function(event, eventData) {
1.273 + var jQuerySuppliedCheckedState = this.checked;
1.274 + if (eventData)
1.275 + this.checked = eventData.checkedStateBeforeEvent !== true;
1.276 + originalHandler.call(this, event);
1.277 + this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
1.278 + };
1.279 + }
1.280 + jQuery(element)['bind'](eventType, handler);
1.281 + } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
1.282 + element.addEventListener(eventType, handler, false);
1.283 + else if (typeof element.attachEvent != "undefined")
1.284 + element.attachEvent("on" + eventType, function (event) {
1.285 + handler.call(element, event);
1.286 + });
1.287 + else
1.288 + throw new Error("Browser doesn't support addEventListener or attachEvent");
1.289 + },
1.290 +
1.291 + triggerEvent: function (element, eventType) {
1.292 + if (!(element && element.nodeType))
1.293 + throw new Error("element must be a DOM node when calling triggerEvent");
1.294 +
1.295 + if (typeof jQuery != "undefined") {
1.296 + var eventData = [];
1.297 + if (isClickOnCheckableElement(element, eventType)) {
1.298 + // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
1.299 + eventData.push({ checkedStateBeforeEvent: element.checked });
1.300 + }
1.301 + jQuery(element)['trigger'](eventType, eventData);
1.302 + } else if (typeof document.createEvent == "function") {
1.303 + if (typeof element.dispatchEvent == "function") {
1.304 + var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
1.305 + var event = document.createEvent(eventCategory);
1.306 + event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
1.307 + element.dispatchEvent(event);
1.308 + }
1.309 + else
1.310 + throw new Error("The supplied element doesn't support dispatchEvent");
1.311 + } else if (typeof element.fireEvent != "undefined") {
1.312 + // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
1.313 + // so to make it consistent, we'll do it manually here
1.314 + if (isClickOnCheckableElement(element, eventType))
1.315 + element.checked = element.checked !== true;
1.316 + element.fireEvent("on" + eventType);
1.317 + }
1.318 + else
1.319 + throw new Error("Browser doesn't support triggering events");
1.320 + },
1.321 +
1.322 + unwrapObservable: function (value) {
1.323 + return ko.isObservable(value) ? value() : value;
1.324 + },
1.325 +
1.326 + peekObservable: function (value) {
1.327 + return ko.isObservable(value) ? value.peek() : value;
1.328 + },
1.329 +
1.330 + toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
1.331 + if (classNames) {
1.332 + var cssClassNameRegex = /[\w-]+/g,
1.333 + currentClassNames = node.className.match(cssClassNameRegex) || [];
1.334 + ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
1.335 + var indexOfClass = ko.utils.arrayIndexOf(currentClassNames, className);
1.336 + if (indexOfClass >= 0) {
1.337 + if (!shouldHaveClass)
1.338 + currentClassNames.splice(indexOfClass, 1);
1.339 + } else {
1.340 + if (shouldHaveClass)
1.341 + currentClassNames.push(className);
1.342 + }
1.343 + });
1.344 + node.className = currentClassNames.join(" ");
1.345 + }
1.346 + },
1.347 +
1.348 + setTextContent: function(element, textContent) {
1.349 + var value = ko.utils.unwrapObservable(textContent);
1.350 + if ((value === null) || (value === undefined))
1.351 + value = "";
1.352 +
1.353 + if (element.nodeType === 3) {
1.354 + element.data = value;
1.355 + } else {
1.356 + // We need there to be exactly one child: a text node.
1.357 + // If there are no children, more than one, or if it's not a text node,
1.358 + // we'll clear everything and create a single text node.
1.359 + var innerTextNode = ko.virtualElements.firstChild(element);
1.360 + if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
1.361 + ko.virtualElements.setDomNodeChildren(element, [document.createTextNode(value)]);
1.362 + } else {
1.363 + innerTextNode.data = value;
1.364 + }
1.365 +
1.366 + ko.utils.forceRefresh(element);
1.367 + }
1.368 + },
1.369 +
1.370 + setElementName: function(element, name) {
1.371 + element.name = name;
1.372 +
1.373 + // Workaround IE 6/7 issue
1.374 + // - https://github.com/SteveSanderson/knockout/issues/197
1.375 + // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
1.376 + if (ieVersion <= 7) {
1.377 + try {
1.378 + element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
1.379 + }
1.380 + catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
1.381 + }
1.382 + },
1.383 +
1.384 + forceRefresh: function(node) {
1.385 + // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
1.386 + if (ieVersion >= 9) {
1.387 + // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
1.388 + var elem = node.nodeType == 1 ? node : node.parentNode;
1.389 + if (elem.style)
1.390 + elem.style.zoom = elem.style.zoom;
1.391 + }
1.392 + },
1.393 +
1.394 + ensureSelectElementIsRenderedCorrectly: function(selectElement) {
1.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.
1.396 + // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
1.397 + if (ieVersion >= 9) {
1.398 + var originalWidth = selectElement.style.width;
1.399 + selectElement.style.width = 0;
1.400 + selectElement.style.width = originalWidth;
1.401 + }
1.402 + },
1.403 +
1.404 + range: function (min, max) {
1.405 + min = ko.utils.unwrapObservable(min);
1.406 + max = ko.utils.unwrapObservable(max);
1.407 + var result = [];
1.408 + for (var i = min; i <= max; i++)
1.409 + result.push(i);
1.410 + return result;
1.411 + },
1.412 +
1.413 + makeArray: function(arrayLikeObject) {
1.414 + var result = [];
1.415 + for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
1.416 + result.push(arrayLikeObject[i]);
1.417 + };
1.418 + return result;
1.419 + },
1.420 +
1.421 + isIe6 : isIe6,
1.422 + isIe7 : isIe7,
1.423 + ieVersion : ieVersion,
1.424 +
1.425 + getFormFields: function(form, fieldName) {
1.426 + var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
1.427 + var isMatchingField = (typeof fieldName == 'string')
1.428 + ? function(field) { return field.name === fieldName }
1.429 + : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
1.430 + var matches = [];
1.431 + for (var i = fields.length - 1; i >= 0; i--) {
1.432 + if (isMatchingField(fields[i]))
1.433 + matches.push(fields[i]);
1.434 + };
1.435 + return matches;
1.436 + },
1.437 +
1.438 + parseJson: function (jsonString) {
1.439 + if (typeof jsonString == "string") {
1.440 + jsonString = ko.utils.stringTrim(jsonString);
1.441 + if (jsonString) {
1.442 + if (window.JSON && window.JSON.parse) // Use native parsing where available
1.443 + return window.JSON.parse(jsonString);
1.444 + return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
1.445 + }
1.446 + }
1.447 + return null;
1.448 + },
1.449 +
1.450 + stringifyJson: function (data, replacer, space) { // replacer and space are optional
1.451 + if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
1.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");
1.453 + return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
1.454 + },
1.455 +
1.456 + postJson: function (urlOrForm, data, options) {
1.457 + options = options || {};
1.458 + var params = options['params'] || {};
1.459 + var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
1.460 + var url = urlOrForm;
1.461 +
1.462 + // If we were given a form, use its 'action' URL and pick out any requested field values
1.463 + if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
1.464 + var originalForm = urlOrForm;
1.465 + url = originalForm.action;
1.466 + for (var i = includeFields.length - 1; i >= 0; i--) {
1.467 + var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
1.468 + for (var j = fields.length - 1; j >= 0; j--)
1.469 + params[fields[j].name] = fields[j].value;
1.470 + }
1.471 + }
1.472 +
1.473 + data = ko.utils.unwrapObservable(data);
1.474 + var form = document.createElement("form");
1.475 + form.style.display = "none";
1.476 + form.action = url;
1.477 + form.method = "post";
1.478 + for (var key in data) {
1.479 + var input = document.createElement("input");
1.480 + input.name = key;
1.481 + input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
1.482 + form.appendChild(input);
1.483 + }
1.484 + for (var key in params) {
1.485 + var input = document.createElement("input");
1.486 + input.name = key;
1.487 + input.value = params[key];
1.488 + form.appendChild(input);
1.489 + }
1.490 + document.body.appendChild(form);
1.491 + options['submitter'] ? options['submitter'](form) : form.submit();
1.492 + setTimeout(function () { form.parentNode.removeChild(form); }, 0);
1.493 + }
1.494 + }
1.495 +})();
1.496 +
1.497 +ko.exportSymbol('utils', ko.utils);
1.498 +ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
1.499 +ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
1.500 +ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
1.501 +ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
1.502 +ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
1.503 +ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
1.504 +ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
1.505 +ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
1.506 +ko.exportSymbol('utils.extend', ko.utils.extend);
1.507 +ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
1.508 +ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
1.509 +ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
1.510 +ko.exportSymbol('utils.postJson', ko.utils.postJson);
1.511 +ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
1.512 +ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
1.513 +ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
1.514 +ko.exportSymbol('utils.range', ko.utils.range);
1.515 +ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
1.516 +ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
1.517 +ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
1.518 +
1.519 +if (!Function.prototype['bind']) {
1.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)
1.521 + // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
1.522 + Function.prototype['bind'] = function (object) {
1.523 + var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
1.524 + return function () {
1.525 + return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
1.526 + };
1.527 + };
1.528 +}
1.529 +
1.530 +ko.utils.domData = new (function () {
1.531 + var uniqueId = 0;
1.532 + var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
1.533 + var dataStore = {};
1.534 + return {
1.535 + get: function (node, key) {
1.536 + var allDataForNode = ko.utils.domData.getAll(node, false);
1.537 + return allDataForNode === undefined ? undefined : allDataForNode[key];
1.538 + },
1.539 + set: function (node, key, value) {
1.540 + if (value === undefined) {
1.541 + // Make sure we don't actually create a new domData key if we are actually deleting a value
1.542 + if (ko.utils.domData.getAll(node, false) === undefined)
1.543 + return;
1.544 + }
1.545 + var allDataForNode = ko.utils.domData.getAll(node, true);
1.546 + allDataForNode[key] = value;
1.547 + },
1.548 + getAll: function (node, createIfNotFound) {
1.549 + var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
1.550 + var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
1.551 + if (!hasExistingDataStore) {
1.552 + if (!createIfNotFound)
1.553 + return undefined;
1.554 + dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
1.555 + dataStore[dataStoreKey] = {};
1.556 + }
1.557 + return dataStore[dataStoreKey];
1.558 + },
1.559 + clear: function (node) {
1.560 + var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
1.561 + if (dataStoreKey) {
1.562 + delete dataStore[dataStoreKey];
1.563 + node[dataStoreKeyExpandoPropertyName] = null;
1.564 + return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
1.565 + }
1.566 + return false;
1.567 + }
1.568 + }
1.569 +})();
1.570 +
1.571 +ko.exportSymbol('utils.domData', ko.utils.domData);
1.572 +ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
1.573 +
1.574 +ko.utils.domNodeDisposal = new (function () {
1.575 + var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();
1.576 + var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
1.577 + var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
1.578 +
1.579 + function getDisposeCallbacksCollection(node, createIfNotFound) {
1.580 + var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
1.581 + if ((allDisposeCallbacks === undefined) && createIfNotFound) {
1.582 + allDisposeCallbacks = [];
1.583 + ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
1.584 + }
1.585 + return allDisposeCallbacks;
1.586 + }
1.587 + function destroyCallbacksCollection(node) {
1.588 + ko.utils.domData.set(node, domDataKey, undefined);
1.589 + }
1.590 +
1.591 + function cleanSingleNode(node) {
1.592 + // Run all the dispose callbacks
1.593 + var callbacks = getDisposeCallbacksCollection(node, false);
1.594 + if (callbacks) {
1.595 + callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
1.596 + for (var i = 0; i < callbacks.length; i++)
1.597 + callbacks[i](node);
1.598 + }
1.599 +
1.600 + // Also erase the DOM data
1.601 + ko.utils.domData.clear(node);
1.602 +
1.603 + // Special support for jQuery here because it's so commonly used.
1.604 + // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
1.605 + // so notify it to tear down any resources associated with the node & descendants here.
1.606 + if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
1.607 + jQuery['cleanData']([node]);
1.608 +
1.609 + // Also clear any immediate-child comment nodes, as these wouldn't have been found by
1.610 + // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
1.611 + if (cleanableNodeTypesWithDescendants[node.nodeType])
1.612 + cleanImmediateCommentTypeChildren(node);
1.613 + }
1.614 +
1.615 + function cleanImmediateCommentTypeChildren(nodeWithChildren) {
1.616 + var child, nextChild = nodeWithChildren.firstChild;
1.617 + while (child = nextChild) {
1.618 + nextChild = child.nextSibling;
1.619 + if (child.nodeType === 8)
1.620 + cleanSingleNode(child);
1.621 + }
1.622 + }
1.623 +
1.624 + return {
1.625 + addDisposeCallback : function(node, callback) {
1.626 + if (typeof callback != "function")
1.627 + throw new Error("Callback must be a function");
1.628 + getDisposeCallbacksCollection(node, true).push(callback);
1.629 + },
1.630 +
1.631 + removeDisposeCallback : function(node, callback) {
1.632 + var callbacksCollection = getDisposeCallbacksCollection(node, false);
1.633 + if (callbacksCollection) {
1.634 + ko.utils.arrayRemoveItem(callbacksCollection, callback);
1.635 + if (callbacksCollection.length == 0)
1.636 + destroyCallbacksCollection(node);
1.637 + }
1.638 + },
1.639 +
1.640 + cleanNode : function(node) {
1.641 + // First clean this node, where applicable
1.642 + if (cleanableNodeTypes[node.nodeType]) {
1.643 + cleanSingleNode(node);
1.644 +
1.645 + // ... then its descendants, where applicable
1.646 + if (cleanableNodeTypesWithDescendants[node.nodeType]) {
1.647 + // Clone the descendants list in case it changes during iteration
1.648 + var descendants = [];
1.649 + ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
1.650 + for (var i = 0, j = descendants.length; i < j; i++)
1.651 + cleanSingleNode(descendants[i]);
1.652 + }
1.653 + }
1.654 + return node;
1.655 + },
1.656 +
1.657 + removeNode : function(node) {
1.658 + ko.cleanNode(node);
1.659 + if (node.parentNode)
1.660 + node.parentNode.removeChild(node);
1.661 + }
1.662 + }
1.663 +})();
1.664 +ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
1.665 +ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
1.666 +ko.exportSymbol('cleanNode', ko.cleanNode);
1.667 +ko.exportSymbol('removeNode', ko.removeNode);
1.668 +ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
1.669 +ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
1.670 +ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
1.671 +(function () {
1.672 + var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
1.673 +
1.674 + function simpleHtmlParse(html) {
1.675 + // Based on jQuery's "clean" function, but only accounting for table-related elements.
1.676 + // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
1.677 +
1.678 + // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
1.679 + // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
1.680 + // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
1.681 + // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
1.682 +
1.683 + // Trim whitespace, otherwise indexOf won't work as expected
1.684 + var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
1.685 +
1.686 + // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
1.687 + var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
1.688 + !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
1.689 + (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
1.690 + /* anything else */ [0, "", ""];
1.691 +
1.692 + // Go to html and back, then peel off extra wrappers
1.693 + // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
1.694 + var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
1.695 + if (typeof window['innerShiv'] == "function") {
1.696 + div.appendChild(window['innerShiv'](markup));
1.697 + } else {
1.698 + div.innerHTML = markup;
1.699 + }
1.700 +
1.701 + // Move to the right depth
1.702 + while (wrap[0]--)
1.703 + div = div.lastChild;
1.704 +
1.705 + return ko.utils.makeArray(div.lastChild.childNodes);
1.706 + }
1.707 +
1.708 + function jQueryHtmlParse(html) {
1.709 + // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
1.710 + if (jQuery['parseHTML']) {
1.711 + return jQuery['parseHTML'](html);
1.712 + } else {
1.713 + // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
1.714 + var elems = jQuery['clean']([html]);
1.715 +
1.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.
1.717 + // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
1.718 + // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
1.719 + if (elems && elems[0]) {
1.720 + // Find the top-most parent element that's a direct child of a document fragment
1.721 + var elem = elems[0];
1.722 + while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
1.723 + elem = elem.parentNode;
1.724 + // ... then detach it
1.725 + if (elem.parentNode)
1.726 + elem.parentNode.removeChild(elem);
1.727 + }
1.728 +
1.729 + return elems;
1.730 + }
1.731 + }
1.732 +
1.733 + ko.utils.parseHtmlFragment = function(html) {
1.734 + return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
1.735 + : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
1.736 + };
1.737 +
1.738 + ko.utils.setHtml = function(node, html) {
1.739 + ko.utils.emptyDomNode(node);
1.740 +
1.741 + // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
1.742 + html = ko.utils.unwrapObservable(html);
1.743 +
1.744 + if ((html !== null) && (html !== undefined)) {
1.745 + if (typeof html != 'string')
1.746 + html = html.toString();
1.747 +
1.748 + // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
1.749 + // for example <tr> elements which are not normally allowed to exist on their own.
1.750 + // If you've referenced jQuery we'll use that rather than duplicating its code.
1.751 + if (typeof jQuery != 'undefined') {
1.752 + jQuery(node)['html'](html);
1.753 + } else {
1.754 + // ... otherwise, use KO's own parsing logic.
1.755 + var parsedNodes = ko.utils.parseHtmlFragment(html);
1.756 + for (var i = 0; i < parsedNodes.length; i++)
1.757 + node.appendChild(parsedNodes[i]);
1.758 + }
1.759 + }
1.760 + };
1.761 +})();
1.762 +
1.763 +ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
1.764 +ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
1.765 +
1.766 +ko.memoization = (function () {
1.767 + var memos = {};
1.768 +
1.769 + function randomMax8HexChars() {
1.770 + return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
1.771 + }
1.772 + function generateRandomId() {
1.773 + return randomMax8HexChars() + randomMax8HexChars();
1.774 + }
1.775 + function findMemoNodes(rootNode, appendToArray) {
1.776 + if (!rootNode)
1.777 + return;
1.778 + if (rootNode.nodeType == 8) {
1.779 + var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
1.780 + if (memoId != null)
1.781 + appendToArray.push({ domNode: rootNode, memoId: memoId });
1.782 + } else if (rootNode.nodeType == 1) {
1.783 + for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
1.784 + findMemoNodes(childNodes[i], appendToArray);
1.785 + }
1.786 + }
1.787 +
1.788 + return {
1.789 + memoize: function (callback) {
1.790 + if (typeof callback != "function")
1.791 + throw new Error("You can only pass a function to ko.memoization.memoize()");
1.792 + var memoId = generateRandomId();
1.793 + memos[memoId] = callback;
1.794 + return "<!--[ko_memo:" + memoId + "]-->";
1.795 + },
1.796 +
1.797 + unmemoize: function (memoId, callbackParams) {
1.798 + var callback = memos[memoId];
1.799 + if (callback === undefined)
1.800 + throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
1.801 + try {
1.802 + callback.apply(null, callbackParams || []);
1.803 + return true;
1.804 + }
1.805 + finally { delete memos[memoId]; }
1.806 + },
1.807 +
1.808 + unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
1.809 + var memos = [];
1.810 + findMemoNodes(domNode, memos);
1.811 + for (var i = 0, j = memos.length; i < j; i++) {
1.812 + var node = memos[i].domNode;
1.813 + var combinedParams = [node];
1.814 + if (extraCallbackParamsArray)
1.815 + ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
1.816 + ko.memoization.unmemoize(memos[i].memoId, combinedParams);
1.817 + node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
1.818 + if (node.parentNode)
1.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)
1.820 + }
1.821 + },
1.822 +
1.823 + parseMemoText: function (memoText) {
1.824 + var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
1.825 + return match ? match[1] : null;
1.826 + }
1.827 + };
1.828 +})();
1.829 +
1.830 +ko.exportSymbol('memoization', ko.memoization);
1.831 +ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
1.832 +ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
1.833 +ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
1.834 +ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
1.835 +ko.extenders = {
1.836 + 'throttle': function(target, timeout) {
1.837 + // Throttling means two things:
1.838 +
1.839 + // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
1.840 + // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
1.841 + target['throttleEvaluation'] = timeout;
1.842 +
1.843 + // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
1.844 + // so the target cannot change value synchronously or faster than a certain rate
1.845 + var writeTimeoutInstance = null;
1.846 + return ko.dependentObservable({
1.847 + 'read': target,
1.848 + 'write': function(value) {
1.849 + clearTimeout(writeTimeoutInstance);
1.850 + writeTimeoutInstance = setTimeout(function() {
1.851 + target(value);
1.852 + }, timeout);
1.853 + }
1.854 + });
1.855 + },
1.856 +
1.857 + 'notify': function(target, notifyWhen) {
1.858 + target["equalityComparer"] = notifyWhen == "always"
1.859 + ? function() { return false } // Treat all values as not equal
1.860 + : ko.observable["fn"]["equalityComparer"];
1.861 + return target;
1.862 + }
1.863 +};
1.864 +
1.865 +function applyExtenders(requestedExtenders) {
1.866 + var target = this;
1.867 + if (requestedExtenders) {
1.868 + for (var key in requestedExtenders) {
1.869 + var extenderHandler = ko.extenders[key];
1.870 + if (typeof extenderHandler == 'function') {
1.871 + target = extenderHandler(target, requestedExtenders[key]);
1.872 + }
1.873 + }
1.874 + }
1.875 + return target;
1.876 +}
1.877 +
1.878 +ko.exportSymbol('extenders', ko.extenders);
1.879 +
1.880 +ko.subscription = function (target, callback, disposeCallback) {
1.881 + this.target = target;
1.882 + this.callback = callback;
1.883 + this.disposeCallback = disposeCallback;
1.884 + ko.exportProperty(this, 'dispose', this.dispose);
1.885 +};
1.886 +ko.subscription.prototype.dispose = function () {
1.887 + this.isDisposed = true;
1.888 + this.disposeCallback();
1.889 +};
1.890 +
1.891 +ko.subscribable = function () {
1.892 + this._subscriptions = {};
1.893 +
1.894 + ko.utils.extend(this, ko.subscribable['fn']);
1.895 + ko.exportProperty(this, 'subscribe', this.subscribe);
1.896 + ko.exportProperty(this, 'extend', this.extend);
1.897 + ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
1.898 +}
1.899 +
1.900 +var defaultEvent = "change";
1.901 +
1.902 +ko.subscribable['fn'] = {
1.903 + subscribe: function (callback, callbackTarget, event) {
1.904 + event = event || defaultEvent;
1.905 + var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
1.906 +
1.907 + var subscription = new ko.subscription(this, boundCallback, function () {
1.908 + ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
1.909 + }.bind(this));
1.910 +
1.911 + if (!this._subscriptions[event])
1.912 + this._subscriptions[event] = [];
1.913 + this._subscriptions[event].push(subscription);
1.914 + return subscription;
1.915 + },
1.916 +
1.917 + "notifySubscribers": function (valueToNotify, event) {
1.918 + event = event || defaultEvent;
1.919 + if (this._subscriptions[event]) {
1.920 + ko.dependencyDetection.ignore(function() {
1.921 + ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
1.922 + // In case a subscription was disposed during the arrayForEach cycle, check
1.923 + // for isDisposed on each subscription before invoking its callback
1.924 + if (subscription && (subscription.isDisposed !== true))
1.925 + subscription.callback(valueToNotify);
1.926 + });
1.927 + }, this);
1.928 + }
1.929 + },
1.930 +
1.931 + getSubscriptionsCount: function () {
1.932 + var total = 0;
1.933 + for (var eventName in this._subscriptions) {
1.934 + if (this._subscriptions.hasOwnProperty(eventName))
1.935 + total += this._subscriptions[eventName].length;
1.936 + }
1.937 + return total;
1.938 + },
1.939 +
1.940 + extend: applyExtenders
1.941 +};
1.942 +
1.943 +
1.944 +ko.isSubscribable = function (instance) {
1.945 + return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
1.946 +};
1.947 +
1.948 +ko.exportSymbol('subscribable', ko.subscribable);
1.949 +ko.exportSymbol('isSubscribable', ko.isSubscribable);
1.950 +
1.951 +ko.dependencyDetection = (function () {
1.952 + var _frames = [];
1.953 +
1.954 + return {
1.955 + begin: function (callback) {
1.956 + _frames.push({ callback: callback, distinctDependencies:[] });
1.957 + },
1.958 +
1.959 + end: function () {
1.960 + _frames.pop();
1.961 + },
1.962 +
1.963 + registerDependency: function (subscribable) {
1.964 + if (!ko.isSubscribable(subscribable))
1.965 + throw new Error("Only subscribable things can act as dependencies");
1.966 + if (_frames.length > 0) {
1.967 + var topFrame = _frames[_frames.length - 1];
1.968 + if (!topFrame || ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
1.969 + return;
1.970 + topFrame.distinctDependencies.push(subscribable);
1.971 + topFrame.callback(subscribable);
1.972 + }
1.973 + },
1.974 +
1.975 + ignore: function(callback, callbackTarget, callbackArgs) {
1.976 + try {
1.977 + _frames.push(null);
1.978 + return callback.apply(callbackTarget, callbackArgs || []);
1.979 + } finally {
1.980 + _frames.pop();
1.981 + }
1.982 + }
1.983 + };
1.984 +})();
1.985 +var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };
1.986 +
1.987 +ko.observable = function (initialValue) {
1.988 + var _latestValue = initialValue;
1.989 +
1.990 + function observable() {
1.991 + if (arguments.length > 0) {
1.992 + // Write
1.993 +
1.994 + // Ignore writes if the value hasn't changed
1.995 + if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
1.996 + observable.valueWillMutate();
1.997 + _latestValue = arguments[0];
1.998 + if (DEBUG) observable._latestValue = _latestValue;
1.999 + observable.valueHasMutated();
1.1000 + }
1.1001 + return this; // Permits chained assignments
1.1002 + }
1.1003 + else {
1.1004 + // Read
1.1005 + ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
1.1006 + return _latestValue;
1.1007 + }
1.1008 + }
1.1009 + if (DEBUG) observable._latestValue = _latestValue;
1.1010 + ko.subscribable.call(observable);
1.1011 + observable.peek = function() { return _latestValue };
1.1012 + observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
1.1013 + observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
1.1014 + ko.utils.extend(observable, ko.observable['fn']);
1.1015 +
1.1016 + ko.exportProperty(observable, 'peek', observable.peek);
1.1017 + ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
1.1018 + ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
1.1019 +
1.1020 + return observable;
1.1021 +}
1.1022 +
1.1023 +ko.observable['fn'] = {
1.1024 + "equalityComparer": function valuesArePrimitiveAndEqual(a, b) {
1.1025 + var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
1.1026 + return oldValueIsPrimitive ? (a === b) : false;
1.1027 + }
1.1028 +};
1.1029 +
1.1030 +var protoProperty = ko.observable.protoProperty = "__ko_proto__";
1.1031 +ko.observable['fn'][protoProperty] = ko.observable;
1.1032 +
1.1033 +ko.hasPrototype = function(instance, prototype) {
1.1034 + if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
1.1035 + if (instance[protoProperty] === prototype) return true;
1.1036 + return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
1.1037 +};
1.1038 +
1.1039 +ko.isObservable = function (instance) {
1.1040 + return ko.hasPrototype(instance, ko.observable);
1.1041 +}
1.1042 +ko.isWriteableObservable = function (instance) {
1.1043 + // Observable
1.1044 + if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
1.1045 + return true;
1.1046 + // Writeable dependent observable
1.1047 + if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
1.1048 + return true;
1.1049 + // Anything else
1.1050 + return false;
1.1051 +}
1.1052 +
1.1053 +
1.1054 +ko.exportSymbol('observable', ko.observable);
1.1055 +ko.exportSymbol('isObservable', ko.isObservable);
1.1056 +ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
1.1057 +ko.observableArray = function (initialValues) {
1.1058 + if (arguments.length == 0) {
1.1059 + // Zero-parameter constructor initializes to empty array
1.1060 + initialValues = [];
1.1061 + }
1.1062 + if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
1.1063 + throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
1.1064 +
1.1065 + var result = ko.observable(initialValues);
1.1066 + ko.utils.extend(result, ko.observableArray['fn']);
1.1067 + return result;
1.1068 +}
1.1069 +
1.1070 +ko.observableArray['fn'] = {
1.1071 + 'remove': function (valueOrPredicate) {
1.1072 + var underlyingArray = this.peek();
1.1073 + var removedValues = [];
1.1074 + var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
1.1075 + for (var i = 0; i < underlyingArray.length; i++) {
1.1076 + var value = underlyingArray[i];
1.1077 + if (predicate(value)) {
1.1078 + if (removedValues.length === 0) {
1.1079 + this.valueWillMutate();
1.1080 + }
1.1081 + removedValues.push(value);
1.1082 + underlyingArray.splice(i, 1);
1.1083 + i--;
1.1084 + }
1.1085 + }
1.1086 + if (removedValues.length) {
1.1087 + this.valueHasMutated();
1.1088 + }
1.1089 + return removedValues;
1.1090 + },
1.1091 +
1.1092 + 'removeAll': function (arrayOfValues) {
1.1093 + // If you passed zero args, we remove everything
1.1094 + if (arrayOfValues === undefined) {
1.1095 + var underlyingArray = this.peek();
1.1096 + var allValues = underlyingArray.slice(0);
1.1097 + this.valueWillMutate();
1.1098 + underlyingArray.splice(0, underlyingArray.length);
1.1099 + this.valueHasMutated();
1.1100 + return allValues;
1.1101 + }
1.1102 + // If you passed an arg, we interpret it as an array of entries to remove
1.1103 + if (!arrayOfValues)
1.1104 + return [];
1.1105 + return this['remove'](function (value) {
1.1106 + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
1.1107 + });
1.1108 + },
1.1109 +
1.1110 + 'destroy': function (valueOrPredicate) {
1.1111 + var underlyingArray = this.peek();
1.1112 + var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
1.1113 + this.valueWillMutate();
1.1114 + for (var i = underlyingArray.length - 1; i >= 0; i--) {
1.1115 + var value = underlyingArray[i];
1.1116 + if (predicate(value))
1.1117 + underlyingArray[i]["_destroy"] = true;
1.1118 + }
1.1119 + this.valueHasMutated();
1.1120 + },
1.1121 +
1.1122 + 'destroyAll': function (arrayOfValues) {
1.1123 + // If you passed zero args, we destroy everything
1.1124 + if (arrayOfValues === undefined)
1.1125 + return this['destroy'](function() { return true });
1.1126 +
1.1127 + // If you passed an arg, we interpret it as an array of entries to destroy
1.1128 + if (!arrayOfValues)
1.1129 + return [];
1.1130 + return this['destroy'](function (value) {
1.1131 + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
1.1132 + });
1.1133 + },
1.1134 +
1.1135 + 'indexOf': function (item) {
1.1136 + var underlyingArray = this();
1.1137 + return ko.utils.arrayIndexOf(underlyingArray, item);
1.1138 + },
1.1139 +
1.1140 + 'replace': function(oldItem, newItem) {
1.1141 + var index = this['indexOf'](oldItem);
1.1142 + if (index >= 0) {
1.1143 + this.valueWillMutate();
1.1144 + this.peek()[index] = newItem;
1.1145 + this.valueHasMutated();
1.1146 + }
1.1147 + }
1.1148 +}
1.1149 +
1.1150 +// Populate ko.observableArray.fn with read/write functions from native arrays
1.1151 +// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
1.1152 +// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
1.1153 +ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
1.1154 + ko.observableArray['fn'][methodName] = function () {
1.1155 + // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
1.1156 + // (for consistency with mutating regular observables)
1.1157 + var underlyingArray = this.peek();
1.1158 + this.valueWillMutate();
1.1159 + var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
1.1160 + this.valueHasMutated();
1.1161 + return methodCallResult;
1.1162 + };
1.1163 +});
1.1164 +
1.1165 +// Populate ko.observableArray.fn with read-only functions from native arrays
1.1166 +ko.utils.arrayForEach(["slice"], function (methodName) {
1.1167 + ko.observableArray['fn'][methodName] = function () {
1.1168 + var underlyingArray = this();
1.1169 + return underlyingArray[methodName].apply(underlyingArray, arguments);
1.1170 + };
1.1171 +});
1.1172 +
1.1173 +ko.exportSymbol('observableArray', ko.observableArray);
1.1174 +ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
1.1175 + var _latestValue,
1.1176 + _hasBeenEvaluated = false,
1.1177 + _isBeingEvaluated = false,
1.1178 + readFunction = evaluatorFunctionOrOptions;
1.1179 +
1.1180 + if (readFunction && typeof readFunction == "object") {
1.1181 + // Single-parameter syntax - everything is on this "options" param
1.1182 + options = readFunction;
1.1183 + readFunction = options["read"];
1.1184 + } else {
1.1185 + // Multi-parameter syntax - construct the options according to the params passed
1.1186 + options = options || {};
1.1187 + if (!readFunction)
1.1188 + readFunction = options["read"];
1.1189 + }
1.1190 + if (typeof readFunction != "function")
1.1191 + throw new Error("Pass a function that returns the value of the ko.computed");
1.1192 +
1.1193 + function addSubscriptionToDependency(subscribable) {
1.1194 + _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync));
1.1195 + }
1.1196 +
1.1197 + function disposeAllSubscriptionsToDependencies() {
1.1198 + ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
1.1199 + subscription.dispose();
1.1200 + });
1.1201 + _subscriptionsToDependencies = [];
1.1202 + }
1.1203 +
1.1204 + function evaluatePossiblyAsync() {
1.1205 + var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
1.1206 + if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
1.1207 + clearTimeout(evaluationTimeoutInstance);
1.1208 + evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
1.1209 + } else
1.1210 + evaluateImmediate();
1.1211 + }
1.1212 +
1.1213 + function evaluateImmediate() {
1.1214 + if (_isBeingEvaluated) {
1.1215 + // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
1.1216 + // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
1.1217 + // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
1.1218 + // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
1.1219 + return;
1.1220 + }
1.1221 +
1.1222 + // Don't dispose on first evaluation, because the "disposeWhen" callback might
1.1223 + // e.g., dispose when the associated DOM element isn't in the doc, and it's not
1.1224 + // going to be in the doc until *after* the first evaluation
1.1225 + if (_hasBeenEvaluated && disposeWhen()) {
1.1226 + dispose();
1.1227 + return;
1.1228 + }
1.1229 +
1.1230 + _isBeingEvaluated = true;
1.1231 + try {
1.1232 + // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
1.1233 + // Then, during evaluation, we cross off any that are in fact still being used.
1.1234 + var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
1.1235 +
1.1236 + ko.dependencyDetection.begin(function(subscribable) {
1.1237 + var inOld;
1.1238 + if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
1.1239 + disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
1.1240 + else
1.1241 + addSubscriptionToDependency(subscribable); // Brand new subscription - add it
1.1242 + });
1.1243 +
1.1244 + var newValue = readFunction.call(evaluatorFunctionTarget);
1.1245 +
1.1246 + // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
1.1247 + for (var i = disposalCandidates.length - 1; i >= 0; i--) {
1.1248 + if (disposalCandidates[i])
1.1249 + _subscriptionsToDependencies.splice(i, 1)[0].dispose();
1.1250 + }
1.1251 + _hasBeenEvaluated = true;
1.1252 +
1.1253 + dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
1.1254 + _latestValue = newValue;
1.1255 + if (DEBUG) dependentObservable._latestValue = _latestValue;
1.1256 + } finally {
1.1257 + ko.dependencyDetection.end();
1.1258 + }
1.1259 +
1.1260 + dependentObservable["notifySubscribers"](_latestValue);
1.1261 + _isBeingEvaluated = false;
1.1262 + if (!_subscriptionsToDependencies.length)
1.1263 + dispose();
1.1264 + }
1.1265 +
1.1266 + function dependentObservable() {
1.1267 + if (arguments.length > 0) {
1.1268 + if (typeof writeFunction === "function") {
1.1269 + // Writing a value
1.1270 + writeFunction.apply(evaluatorFunctionTarget, arguments);
1.1271 + } else {
1.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.");
1.1273 + }
1.1274 + return this; // Permits chained assignments
1.1275 + } else {
1.1276 + // Reading the value
1.1277 + if (!_hasBeenEvaluated)
1.1278 + evaluateImmediate();
1.1279 + ko.dependencyDetection.registerDependency(dependentObservable);
1.1280 + return _latestValue;
1.1281 + }
1.1282 + }
1.1283 +
1.1284 + function peek() {
1.1285 + if (!_hasBeenEvaluated)
1.1286 + evaluateImmediate();
1.1287 + return _latestValue;
1.1288 + }
1.1289 +
1.1290 + function isActive() {
1.1291 + return !_hasBeenEvaluated || _subscriptionsToDependencies.length > 0;
1.1292 + }
1.1293 +
1.1294 + // By here, "options" is always non-null
1.1295 + var writeFunction = options["write"],
1.1296 + disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
1.1297 + disposeWhen = options["disposeWhen"] || options.disposeWhen || function() { return false; },
1.1298 + dispose = disposeAllSubscriptionsToDependencies,
1.1299 + _subscriptionsToDependencies = [],
1.1300 + evaluationTimeoutInstance = null;
1.1301 +
1.1302 + if (!evaluatorFunctionTarget)
1.1303 + evaluatorFunctionTarget = options["owner"];
1.1304 +
1.1305 + dependentObservable.peek = peek;
1.1306 + dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
1.1307 + dependentObservable.hasWriteFunction = typeof options["write"] === "function";
1.1308 + dependentObservable.dispose = function () { dispose(); };
1.1309 + dependentObservable.isActive = isActive;
1.1310 + dependentObservable.valueHasMutated = function() {
1.1311 + _hasBeenEvaluated = false;
1.1312 + evaluateImmediate();
1.1313 + };
1.1314 +
1.1315 + ko.subscribable.call(dependentObservable);
1.1316 + ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
1.1317 +
1.1318 + ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
1.1319 + ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
1.1320 + ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
1.1321 + ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
1.1322 +
1.1323 + // Evaluate, unless deferEvaluation is true
1.1324 + if (options['deferEvaluation'] !== true)
1.1325 + evaluateImmediate();
1.1326 +
1.1327 + // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values.
1.1328 + // But skip if isActive is false (there will never be any dependencies to dispose).
1.1329 + // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
1.1330 + // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
1.1331 + if (disposeWhenNodeIsRemoved && isActive()) {
1.1332 + dispose = function() {
1.1333 + ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
1.1334 + disposeAllSubscriptionsToDependencies();
1.1335 + };
1.1336 + ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
1.1337 + var existingDisposeWhenFunction = disposeWhen;
1.1338 + disposeWhen = function () {
1.1339 + return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
1.1340 + }
1.1341 + }
1.1342 +
1.1343 + return dependentObservable;
1.1344 +};
1.1345 +
1.1346 +ko.isComputed = function(instance) {
1.1347 + return ko.hasPrototype(instance, ko.dependentObservable);
1.1348 +};
1.1349 +
1.1350 +var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
1.1351 +ko.dependentObservable[protoProp] = ko.observable;
1.1352 +
1.1353 +ko.dependentObservable['fn'] = {};
1.1354 +ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
1.1355 +
1.1356 +ko.exportSymbol('dependentObservable', ko.dependentObservable);
1.1357 +ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
1.1358 +ko.exportSymbol('isComputed', ko.isComputed);
1.1359 +
1.1360 +(function() {
1.1361 + var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
1.1362 +
1.1363 + ko.toJS = function(rootObject) {
1.1364 + if (arguments.length == 0)
1.1365 + throw new Error("When calling ko.toJS, pass the object you want to convert.");
1.1366 +
1.1367 + // We just unwrap everything at every level in the object graph
1.1368 + return mapJsObjectGraph(rootObject, function(valueToMap) {
1.1369 + // Loop because an observable's value might in turn be another observable wrapper
1.1370 + for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
1.1371 + valueToMap = valueToMap();
1.1372 + return valueToMap;
1.1373 + });
1.1374 + };
1.1375 +
1.1376 + ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
1.1377 + var plainJavaScriptObject = ko.toJS(rootObject);
1.1378 + return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
1.1379 + };
1.1380 +
1.1381 + function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
1.1382 + visitedObjects = visitedObjects || new objectLookup();
1.1383 +
1.1384 + rootObject = mapInputCallback(rootObject);
1.1385 + var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
1.1386 + if (!canHaveProperties)
1.1387 + return rootObject;
1.1388 +
1.1389 + var outputProperties = rootObject instanceof Array ? [] : {};
1.1390 + visitedObjects.save(rootObject, outputProperties);
1.1391 +
1.1392 + visitPropertiesOrArrayEntries(rootObject, function(indexer) {
1.1393 + var propertyValue = mapInputCallback(rootObject[indexer]);
1.1394 +
1.1395 + switch (typeof propertyValue) {
1.1396 + case "boolean":
1.1397 + case "number":
1.1398 + case "string":
1.1399 + case "function":
1.1400 + outputProperties[indexer] = propertyValue;
1.1401 + break;
1.1402 + case "object":
1.1403 + case "undefined":
1.1404 + var previouslyMappedValue = visitedObjects.get(propertyValue);
1.1405 + outputProperties[indexer] = (previouslyMappedValue !== undefined)
1.1406 + ? previouslyMappedValue
1.1407 + : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
1.1408 + break;
1.1409 + }
1.1410 + });
1.1411 +
1.1412 + return outputProperties;
1.1413 + }
1.1414 +
1.1415 + function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
1.1416 + if (rootObject instanceof Array) {
1.1417 + for (var i = 0; i < rootObject.length; i++)
1.1418 + visitorCallback(i);
1.1419 +
1.1420 + // For arrays, also respect toJSON property for custom mappings (fixes #278)
1.1421 + if (typeof rootObject['toJSON'] == 'function')
1.1422 + visitorCallback('toJSON');
1.1423 + } else {
1.1424 + for (var propertyName in rootObject)
1.1425 + visitorCallback(propertyName);
1.1426 + }
1.1427 + };
1.1428 +
1.1429 + function objectLookup() {
1.1430 + var keys = [];
1.1431 + var values = [];
1.1432 + this.save = function(key, value) {
1.1433 + var existingIndex = ko.utils.arrayIndexOf(keys, key);
1.1434 + if (existingIndex >= 0)
1.1435 + values[existingIndex] = value;
1.1436 + else {
1.1437 + keys.push(key);
1.1438 + values.push(value);
1.1439 + }
1.1440 + };
1.1441 + this.get = function(key) {
1.1442 + var existingIndex = ko.utils.arrayIndexOf(keys, key);
1.1443 + return (existingIndex >= 0) ? values[existingIndex] : undefined;
1.1444 + };
1.1445 + };
1.1446 +})();
1.1447 +
1.1448 +ko.exportSymbol('toJS', ko.toJS);
1.1449 +ko.exportSymbol('toJSON', ko.toJSON);
1.1450 +(function () {
1.1451 + var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
1.1452 +
1.1453 + // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
1.1454 + // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
1.1455 + // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
1.1456 + ko.selectExtensions = {
1.1457 + readValue : function(element) {
1.1458 + switch (ko.utils.tagNameLower(element)) {
1.1459 + case 'option':
1.1460 + if (element[hasDomDataExpandoProperty] === true)
1.1461 + return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
1.1462 + return ko.utils.ieVersion <= 7
1.1463 + ? (element.getAttributeNode('value').specified ? element.value : element.text)
1.1464 + : element.value;
1.1465 + case 'select':
1.1466 + return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
1.1467 + default:
1.1468 + return element.value;
1.1469 + }
1.1470 + },
1.1471 +
1.1472 + writeValue: function(element, value) {
1.1473 + switch (ko.utils.tagNameLower(element)) {
1.1474 + case 'option':
1.1475 + switch(typeof value) {
1.1476 + case "string":
1.1477 + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
1.1478 + if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
1.1479 + delete element[hasDomDataExpandoProperty];
1.1480 + }
1.1481 + element.value = value;
1.1482 + break;
1.1483 + default:
1.1484 + // Store arbitrary object using DomData
1.1485 + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
1.1486 + element[hasDomDataExpandoProperty] = true;
1.1487 +
1.1488 + // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
1.1489 + element.value = typeof value === "number" ? value : "";
1.1490 + break;
1.1491 + }
1.1492 + break;
1.1493 + case 'select':
1.1494 + for (var i = element.options.length - 1; i >= 0; i--) {
1.1495 + if (ko.selectExtensions.readValue(element.options[i]) == value) {
1.1496 + element.selectedIndex = i;
1.1497 + break;
1.1498 + }
1.1499 + }
1.1500 + break;
1.1501 + default:
1.1502 + if ((value === null) || (value === undefined))
1.1503 + value = "";
1.1504 + element.value = value;
1.1505 + break;
1.1506 + }
1.1507 + }
1.1508 + };
1.1509 +})();
1.1510 +
1.1511 +ko.exportSymbol('selectExtensions', ko.selectExtensions);
1.1512 +ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
1.1513 +ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
1.1514 +ko.expressionRewriting = (function () {
1.1515 + var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
1.1516 + var javaScriptReservedWords = ["true", "false"];
1.1517 +
1.1518 + // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
1.1519 + // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
1.1520 + var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
1.1521 +
1.1522 + function restoreTokens(string, tokens) {
1.1523 + var prevValue = null;
1.1524 + while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
1.1525 + prevValue = string;
1.1526 + string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
1.1527 + return tokens[tokenIndex];
1.1528 + });
1.1529 + }
1.1530 + return string;
1.1531 + }
1.1532 +
1.1533 + function getWriteableValue(expression) {
1.1534 + if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
1.1535 + return false;
1.1536 + var match = expression.match(javaScriptAssignmentTarget);
1.1537 + return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
1.1538 + }
1.1539 +
1.1540 + function ensureQuoted(key) {
1.1541 + var trimmedKey = ko.utils.stringTrim(key);
1.1542 + switch (trimmedKey.length && trimmedKey.charAt(0)) {
1.1543 + case "'":
1.1544 + case '"':
1.1545 + return key;
1.1546 + default:
1.1547 + return "'" + trimmedKey + "'";
1.1548 + }
1.1549 + }
1.1550 +
1.1551 + return {
1.1552 + bindingRewriteValidators: [],
1.1553 +
1.1554 + parseObjectLiteral: function(objectLiteralString) {
1.1555 + // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
1.1556 + // that is sufficient just to split an object literal string into a set of top-level key-value pairs
1.1557 +
1.1558 + var str = ko.utils.stringTrim(objectLiteralString);
1.1559 + if (str.length < 3)
1.1560 + return [];
1.1561 + if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
1.1562 + str = str.substring(1, str.length - 1);
1.1563 +
1.1564 + // Pull out any string literals and regex literals
1.1565 + var tokens = [];
1.1566 + var tokenStart = null, tokenEndChar;
1.1567 + for (var position = 0; position < str.length; position++) {
1.1568 + var c = str.charAt(position);
1.1569 + if (tokenStart === null) {
1.1570 + switch (c) {
1.1571 + case '"':
1.1572 + case "'":
1.1573 + case "/":
1.1574 + tokenStart = position;
1.1575 + tokenEndChar = c;
1.1576 + break;
1.1577 + }
1.1578 + } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
1.1579 + var token = str.substring(tokenStart, position + 1);
1.1580 + tokens.push(token);
1.1581 + var replacement = "@ko_token_" + (tokens.length - 1) + "@";
1.1582 + str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
1.1583 + position -= (token.length - replacement.length);
1.1584 + tokenStart = null;
1.1585 + }
1.1586 + }
1.1587 +
1.1588 + // Next pull out balanced paren, brace, and bracket blocks
1.1589 + tokenStart = null;
1.1590 + tokenEndChar = null;
1.1591 + var tokenDepth = 0, tokenStartChar = null;
1.1592 + for (var position = 0; position < str.length; position++) {
1.1593 + var c = str.charAt(position);
1.1594 + if (tokenStart === null) {
1.1595 + switch (c) {
1.1596 + case "{": tokenStart = position; tokenStartChar = c;
1.1597 + tokenEndChar = "}";
1.1598 + break;
1.1599 + case "(": tokenStart = position; tokenStartChar = c;
1.1600 + tokenEndChar = ")";
1.1601 + break;
1.1602 + case "[": tokenStart = position; tokenStartChar = c;
1.1603 + tokenEndChar = "]";
1.1604 + break;
1.1605 + }
1.1606 + }
1.1607 +
1.1608 + if (c === tokenStartChar)
1.1609 + tokenDepth++;
1.1610 + else if (c === tokenEndChar) {
1.1611 + tokenDepth--;
1.1612 + if (tokenDepth === 0) {
1.1613 + var token = str.substring(tokenStart, position + 1);
1.1614 + tokens.push(token);
1.1615 + var replacement = "@ko_token_" + (tokens.length - 1) + "@";
1.1616 + str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
1.1617 + position -= (token.length - replacement.length);
1.1618 + tokenStart = null;
1.1619 + }
1.1620 + }
1.1621 + }
1.1622 +
1.1623 + // Now we can safely split on commas to get the key/value pairs
1.1624 + var result = [];
1.1625 + var keyValuePairs = str.split(",");
1.1626 + for (var i = 0, j = keyValuePairs.length; i < j; i++) {
1.1627 + var pair = keyValuePairs[i];
1.1628 + var colonPos = pair.indexOf(":");
1.1629 + if ((colonPos > 0) && (colonPos < pair.length - 1)) {
1.1630 + var key = pair.substring(0, colonPos);
1.1631 + var value = pair.substring(colonPos + 1);
1.1632 + result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
1.1633 + } else {
1.1634 + result.push({ 'unknown': restoreTokens(pair, tokens) });
1.1635 + }
1.1636 + }
1.1637 + return result;
1.1638 + },
1.1639 +
1.1640 + preProcessBindings: function (objectLiteralStringOrKeyValueArray) {
1.1641 + var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
1.1642 + ? ko.expressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
1.1643 + : objectLiteralStringOrKeyValueArray;
1.1644 + var resultStrings = [], propertyAccessorResultStrings = [];
1.1645 +
1.1646 + var keyValueEntry;
1.1647 + for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
1.1648 + if (resultStrings.length > 0)
1.1649 + resultStrings.push(",");
1.1650 +
1.1651 + if (keyValueEntry['key']) {
1.1652 + var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
1.1653 + resultStrings.push(quotedKey);
1.1654 + resultStrings.push(":");
1.1655 + resultStrings.push(val);
1.1656 +
1.1657 + if (val = getWriteableValue(ko.utils.stringTrim(val))) {
1.1658 + if (propertyAccessorResultStrings.length > 0)
1.1659 + propertyAccessorResultStrings.push(", ");
1.1660 + propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
1.1661 + }
1.1662 + } else if (keyValueEntry['unknown']) {
1.1663 + resultStrings.push(keyValueEntry['unknown']);
1.1664 + }
1.1665 + }
1.1666 +
1.1667 + var combinedResult = resultStrings.join("");
1.1668 + if (propertyAccessorResultStrings.length > 0) {
1.1669 + var allPropertyAccessors = propertyAccessorResultStrings.join("");
1.1670 + combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
1.1671 + }
1.1672 +
1.1673 + return combinedResult;
1.1674 + },
1.1675 +
1.1676 + keyValueArrayContainsKey: function(keyValueArray, key) {
1.1677 + for (var i = 0; i < keyValueArray.length; i++)
1.1678 + if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
1.1679 + return true;
1.1680 + return false;
1.1681 + },
1.1682 +
1.1683 + // Internal, private KO utility for updating model properties from within bindings
1.1684 + // property: If the property being updated is (or might be) an observable, pass it here
1.1685 + // If it turns out to be a writable observable, it will be written to directly
1.1686 + // allBindingsAccessor: All bindings in the current execution context.
1.1687 + // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
1.1688 + // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
1.1689 + // value: The value to be written
1.1690 + // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
1.1691 + // it is !== existing value on that writable observable
1.1692 + writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
1.1693 + if (!property || !ko.isWriteableObservable(property)) {
1.1694 + var propWriters = allBindingsAccessor()['_ko_property_writers'];
1.1695 + if (propWriters && propWriters[key])
1.1696 + propWriters[key](value);
1.1697 + } else if (!checkIfDifferent || property.peek() !== value) {
1.1698 + property(value);
1.1699 + }
1.1700 + }
1.1701 + };
1.1702 +})();
1.1703 +
1.1704 +ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
1.1705 +ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
1.1706 +ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
1.1707 +ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
1.1708 +
1.1709 +// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
1.1710 +// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
1.1711 +ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
1.1712 +ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);(function() {
1.1713 + // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
1.1714 + // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
1.1715 + // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
1.1716 + // of that virtual hierarchy
1.1717 + //
1.1718 + // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
1.1719 + // without having to scatter special cases all over the binding and templating code.
1.1720 +
1.1721 + // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
1.1722 + // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
1.1723 + // So, use node.text where available, and node.nodeValue elsewhere
1.1724 + var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
1.1725 +
1.1726 + var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*-->$/ : /^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/;
1.1727 + var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
1.1728 + var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
1.1729 +
1.1730 + function isStartComment(node) {
1.1731 + return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
1.1732 + }
1.1733 +
1.1734 + function isEndComment(node) {
1.1735 + return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
1.1736 + }
1.1737 +
1.1738 + function getVirtualChildren(startComment, allowUnbalanced) {
1.1739 + var currentNode = startComment;
1.1740 + var depth = 1;
1.1741 + var children = [];
1.1742 + while (currentNode = currentNode.nextSibling) {
1.1743 + if (isEndComment(currentNode)) {
1.1744 + depth--;
1.1745 + if (depth === 0)
1.1746 + return children;
1.1747 + }
1.1748 +
1.1749 + children.push(currentNode);
1.1750 +
1.1751 + if (isStartComment(currentNode))
1.1752 + depth++;
1.1753 + }
1.1754 + if (!allowUnbalanced)
1.1755 + throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
1.1756 + return null;
1.1757 + }
1.1758 +
1.1759 + function getMatchingEndComment(startComment, allowUnbalanced) {
1.1760 + var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
1.1761 + if (allVirtualChildren) {
1.1762 + if (allVirtualChildren.length > 0)
1.1763 + return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
1.1764 + return startComment.nextSibling;
1.1765 + } else
1.1766 + return null; // Must have no matching end comment, and allowUnbalanced is true
1.1767 + }
1.1768 +
1.1769 + function getUnbalancedChildTags(node) {
1.1770 + // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
1.1771 + // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
1.1772 + var childNode = node.firstChild, captureRemaining = null;
1.1773 + if (childNode) {
1.1774 + do {
1.1775 + if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
1.1776 + captureRemaining.push(childNode);
1.1777 + else if (isStartComment(childNode)) {
1.1778 + var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
1.1779 + if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
1.1780 + childNode = matchingEndComment;
1.1781 + else
1.1782 + captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
1.1783 + } else if (isEndComment(childNode)) {
1.1784 + captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
1.1785 + }
1.1786 + } while (childNode = childNode.nextSibling);
1.1787 + }
1.1788 + return captureRemaining;
1.1789 + }
1.1790 +
1.1791 + ko.virtualElements = {
1.1792 + allowedBindings: {},
1.1793 +
1.1794 + childNodes: function(node) {
1.1795 + return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
1.1796 + },
1.1797 +
1.1798 + emptyNode: function(node) {
1.1799 + if (!isStartComment(node))
1.1800 + ko.utils.emptyDomNode(node);
1.1801 + else {
1.1802 + var virtualChildren = ko.virtualElements.childNodes(node);
1.1803 + for (var i = 0, j = virtualChildren.length; i < j; i++)
1.1804 + ko.removeNode(virtualChildren[i]);
1.1805 + }
1.1806 + },
1.1807 +
1.1808 + setDomNodeChildren: function(node, childNodes) {
1.1809 + if (!isStartComment(node))
1.1810 + ko.utils.setDomNodeChildren(node, childNodes);
1.1811 + else {
1.1812 + ko.virtualElements.emptyNode(node);
1.1813 + var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
1.1814 + for (var i = 0, j = childNodes.length; i < j; i++)
1.1815 + endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
1.1816 + }
1.1817 + },
1.1818 +
1.1819 + prepend: function(containerNode, nodeToPrepend) {
1.1820 + if (!isStartComment(containerNode)) {
1.1821 + if (containerNode.firstChild)
1.1822 + containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
1.1823 + else
1.1824 + containerNode.appendChild(nodeToPrepend);
1.1825 + } else {
1.1826 + // Start comments must always have a parent and at least one following sibling (the end comment)
1.1827 + containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
1.1828 + }
1.1829 + },
1.1830 +
1.1831 + insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
1.1832 + if (!insertAfterNode) {
1.1833 + ko.virtualElements.prepend(containerNode, nodeToInsert);
1.1834 + } else if (!isStartComment(containerNode)) {
1.1835 + // Insert after insertion point
1.1836 + if (insertAfterNode.nextSibling)
1.1837 + containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
1.1838 + else
1.1839 + containerNode.appendChild(nodeToInsert);
1.1840 + } else {
1.1841 + // Children of start comments must always have a parent and at least one following sibling (the end comment)
1.1842 + containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
1.1843 + }
1.1844 + },
1.1845 +
1.1846 + firstChild: function(node) {
1.1847 + if (!isStartComment(node))
1.1848 + return node.firstChild;
1.1849 + if (!node.nextSibling || isEndComment(node.nextSibling))
1.1850 + return null;
1.1851 + return node.nextSibling;
1.1852 + },
1.1853 +
1.1854 + nextSibling: function(node) {
1.1855 + if (isStartComment(node))
1.1856 + node = getMatchingEndComment(node);
1.1857 + if (node.nextSibling && isEndComment(node.nextSibling))
1.1858 + return null;
1.1859 + return node.nextSibling;
1.1860 + },
1.1861 +
1.1862 + virtualNodeBindingValue: function(node) {
1.1863 + var regexMatch = isStartComment(node);
1.1864 + return regexMatch ? regexMatch[1] : null;
1.1865 + },
1.1866 +
1.1867 + normaliseVirtualElementDomStructure: function(elementVerified) {
1.1868 + // Workaround for https://github.com/SteveSanderson/knockout/issues/155
1.1869 + // (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
1.1870 + // that are direct descendants of <ul> into the preceding <li>)
1.1871 + if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
1.1872 + return;
1.1873 +
1.1874 + // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
1.1875 + // must be intended to appear *after* that child, so move them there.
1.1876 + var childNode = elementVerified.firstChild;
1.1877 + if (childNode) {
1.1878 + do {
1.1879 + if (childNode.nodeType === 1) {
1.1880 + var unbalancedTags = getUnbalancedChildTags(childNode);
1.1881 + if (unbalancedTags) {
1.1882 + // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
1.1883 + var nodeToInsertBefore = childNode.nextSibling;
1.1884 + for (var i = 0; i < unbalancedTags.length; i++) {
1.1885 + if (nodeToInsertBefore)
1.1886 + elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
1.1887 + else
1.1888 + elementVerified.appendChild(unbalancedTags[i]);
1.1889 + }
1.1890 + }
1.1891 + }
1.1892 + } while (childNode = childNode.nextSibling);
1.1893 + }
1.1894 + }
1.1895 + };
1.1896 +})();
1.1897 +ko.exportSymbol('virtualElements', ko.virtualElements);
1.1898 +ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
1.1899 +ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
1.1900 +//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
1.1901 +ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
1.1902 +//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
1.1903 +ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
1.1904 +ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
1.1905 +(function() {
1.1906 + var defaultBindingAttributeName = "data-bind";
1.1907 +
1.1908 + ko.bindingProvider = function() {
1.1909 + this.bindingCache = {};
1.1910 + };
1.1911 +
1.1912 + ko.utils.extend(ko.bindingProvider.prototype, {
1.1913 + 'nodeHasBindings': function(node) {
1.1914 + switch (node.nodeType) {
1.1915 + case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
1.1916 + case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
1.1917 + default: return false;
1.1918 + }
1.1919 + },
1.1920 +
1.1921 + 'getBindings': function(node, bindingContext) {
1.1922 + var bindingsString = this['getBindingsString'](node, bindingContext);
1.1923 + return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
1.1924 + },
1.1925 +
1.1926 + // The following function is only used internally by this default provider.
1.1927 + // It's not part of the interface definition for a general binding provider.
1.1928 + 'getBindingsString': function(node, bindingContext) {
1.1929 + switch (node.nodeType) {
1.1930 + case 1: return node.getAttribute(defaultBindingAttributeName); // Element
1.1931 + case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
1.1932 + default: return null;
1.1933 + }
1.1934 + },
1.1935 +
1.1936 + // The following function is only used internally by this default provider.
1.1937 + // It's not part of the interface definition for a general binding provider.
1.1938 + 'parseBindingsString': function(bindingsString, bindingContext, node) {
1.1939 + try {
1.1940 + var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
1.1941 + return bindingFunction(bindingContext, node);
1.1942 + } catch (ex) {
1.1943 + throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
1.1944 + }
1.1945 + }
1.1946 + });
1.1947 +
1.1948 + ko.bindingProvider['instance'] = new ko.bindingProvider();
1.1949 +
1.1950 + function createBindingsStringEvaluatorViaCache(bindingsString, cache) {
1.1951 + var cacheKey = bindingsString;
1.1952 + return cache[cacheKey]
1.1953 + || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString));
1.1954 + }
1.1955 +
1.1956 + function createBindingsStringEvaluator(bindingsString) {
1.1957 + // Build the source for a function that evaluates "expression"
1.1958 + // For each scope variable, add an extra level of "with" nesting
1.1959 + // Example result: with(sc1) { with(sc0) { return (expression) } }
1.1960 + var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString),
1.1961 + functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
1.1962 + return new Function("$context", "$element", functionBody);
1.1963 + }
1.1964 +})();
1.1965 +
1.1966 +ko.exportSymbol('bindingProvider', ko.bindingProvider);
1.1967 +(function () {
1.1968 + ko.bindingHandlers = {};
1.1969 +
1.1970 + ko.bindingContext = function(dataItem, parentBindingContext, dataItemAlias) {
1.1971 + if (parentBindingContext) {
1.1972 + ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
1.1973 + this['$parentContext'] = parentBindingContext;
1.1974 + this['$parent'] = parentBindingContext['$data'];
1.1975 + this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
1.1976 + this['$parents'].unshift(this['$parent']);
1.1977 + } else {
1.1978 + this['$parents'] = [];
1.1979 + this['$root'] = dataItem;
1.1980 + // Export 'ko' in the binding context so it will be available in bindings and templates
1.1981 + // even if 'ko' isn't exported as a global, such as when using an AMD loader.
1.1982 + // See https://github.com/SteveSanderson/knockout/issues/490
1.1983 + this['ko'] = ko;
1.1984 + }
1.1985 + this['$data'] = dataItem;
1.1986 + if (dataItemAlias)
1.1987 + this[dataItemAlias] = dataItem;
1.1988 + }
1.1989 + ko.bindingContext.prototype['createChildContext'] = function (dataItem, dataItemAlias) {
1.1990 + return new ko.bindingContext(dataItem, this, dataItemAlias);
1.1991 + };
1.1992 + ko.bindingContext.prototype['extend'] = function(properties) {
1.1993 + var clone = ko.utils.extend(new ko.bindingContext(), this);
1.1994 + return ko.utils.extend(clone, properties);
1.1995 + };
1.1996 +
1.1997 + function validateThatBindingIsAllowedForVirtualElements(bindingName) {
1.1998 + var validator = ko.virtualElements.allowedBindings[bindingName];
1.1999 + if (!validator)
1.2000 + throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
1.2001 + }
1.2002 +
1.2003 + function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
1.2004 + var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
1.2005 + while (currentChild = nextInQueue) {
1.2006 + // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
1.2007 + nextInQueue = ko.virtualElements.nextSibling(currentChild);
1.2008 + applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
1.2009 + }
1.2010 + }
1.2011 +
1.2012 + function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
1.2013 + var shouldBindDescendants = true;
1.2014 +
1.2015 + // Perf optimisation: Apply bindings only if...
1.2016 + // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
1.2017 + // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
1.2018 + // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
1.2019 + var isElement = (nodeVerified.nodeType === 1);
1.2020 + if (isElement) // Workaround IE <= 8 HTML parsing weirdness
1.2021 + ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
1.2022 +
1.2023 + var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
1.2024 + || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
1.2025 + if (shouldApplyBindings)
1.2026 + shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
1.2027 +
1.2028 + if (shouldBindDescendants) {
1.2029 + // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
1.2030 + // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
1.2031 + // hence bindingContextsMayDifferFromDomParentElement is false
1.2032 + // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
1.2033 + // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
1.2034 + // hence bindingContextsMayDifferFromDomParentElement is true
1.2035 + applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
1.2036 + }
1.2037 + }
1.2038 +
1.2039 + function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
1.2040 + // Need to be sure that inits are only run once, and updates never run until all the inits have been run
1.2041 + var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
1.2042 +
1.2043 + // Each time the dependentObservable is evaluated (after data changes),
1.2044 + // the binding attribute is reparsed so that it can pick out the correct
1.2045 + // model properties in the context of the changed data.
1.2046 + // DOM event callbacks need to be able to access this changed data,
1.2047 + // so we need a single parsedBindings variable (shared by all callbacks
1.2048 + // associated with this node's bindings) that all the closures can access.
1.2049 + var parsedBindings;
1.2050 + function makeValueAccessor(bindingKey) {
1.2051 + return function () { return parsedBindings[bindingKey] }
1.2052 + }
1.2053 + function parsedBindingsAccessor() {
1.2054 + return parsedBindings;
1.2055 + }
1.2056 +
1.2057 + var bindingHandlerThatControlsDescendantBindings;
1.2058 + ko.dependentObservable(
1.2059 + function () {
1.2060 + // Ensure we have a nonnull binding context to work with
1.2061 + var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
1.2062 + ? viewModelOrBindingContext
1.2063 + : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
1.2064 + var viewModel = bindingContextInstance['$data'];
1.2065 +
1.2066 + // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
1.2067 + // we can easily recover it just by scanning up the node's ancestors in the DOM
1.2068 + // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
1.2069 + if (bindingContextMayDifferFromDomParentElement)
1.2070 + ko.storedBindingContextForNode(node, bindingContextInstance);
1.2071 +
1.2072 + // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
1.2073 + var evaluatedBindings = (typeof bindings == "function") ? bindings(bindingContextInstance, node) : bindings;
1.2074 + parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
1.2075 +
1.2076 + if (parsedBindings) {
1.2077 + // First run all the inits, so bindings can register for notification on changes
1.2078 + if (initPhase === 0) {
1.2079 + initPhase = 1;
1.2080 + for (var bindingKey in parsedBindings) {
1.2081 + var binding = ko.bindingHandlers[bindingKey];
1.2082 + if (binding && node.nodeType === 8)
1.2083 + validateThatBindingIsAllowedForVirtualElements(bindingKey);
1.2084 +
1.2085 + if (binding && typeof binding["init"] == "function") {
1.2086 + var handlerInitFn = binding["init"];
1.2087 + var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
1.2088 +
1.2089 + // If this binding handler claims to control descendant bindings, make a note of this
1.2090 + if (initResult && initResult['controlsDescendantBindings']) {
1.2091 + if (bindingHandlerThatControlsDescendantBindings !== undefined)
1.2092 + 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.");
1.2093 + bindingHandlerThatControlsDescendantBindings = bindingKey;
1.2094 + }
1.2095 + }
1.2096 + }
1.2097 + initPhase = 2;
1.2098 + }
1.2099 +
1.2100 + // ... then run all the updates, which might trigger changes even on the first evaluation
1.2101 + if (initPhase === 2) {
1.2102 + for (var bindingKey in parsedBindings) {
1.2103 + var binding = ko.bindingHandlers[bindingKey];
1.2104 + if (binding && typeof binding["update"] == "function") {
1.2105 + var handlerUpdateFn = binding["update"];
1.2106 + handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
1.2107 + }
1.2108 + }
1.2109 + }
1.2110 + }
1.2111 + },
1.2112 + null,
1.2113 + { disposeWhenNodeIsRemoved : node }
1.2114 + );
1.2115 +
1.2116 + return {
1.2117 + shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
1.2118 + };
1.2119 + };
1.2120 +
1.2121 + var storedBindingContextDomDataKey = "__ko_bindingContext__";
1.2122 + ko.storedBindingContextForNode = function (node, bindingContext) {
1.2123 + if (arguments.length == 2)
1.2124 + ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
1.2125 + else
1.2126 + return ko.utils.domData.get(node, storedBindingContextDomDataKey);
1.2127 + }
1.2128 +
1.2129 + ko.applyBindingsToNode = function (node, bindings, viewModel) {
1.2130 + if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
1.2131 + ko.virtualElements.normaliseVirtualElementDomStructure(node);
1.2132 + return applyBindingsToNodeInternal(node, bindings, viewModel, true);
1.2133 + };
1.2134 +
1.2135 + ko.applyBindingsToDescendants = function(viewModel, rootNode) {
1.2136 + if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
1.2137 + applyBindingsToDescendantsInternal(viewModel, rootNode, true);
1.2138 + };
1.2139 +
1.2140 + ko.applyBindings = function (viewModel, rootNode) {
1.2141 + if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
1.2142 + throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
1.2143 + rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
1.2144 +
1.2145 + applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
1.2146 + };
1.2147 +
1.2148 + // Retrieving binding context from arbitrary nodes
1.2149 + ko.contextFor = function(node) {
1.2150 + // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
1.2151 + switch (node.nodeType) {
1.2152 + case 1:
1.2153 + case 8:
1.2154 + var context = ko.storedBindingContextForNode(node);
1.2155 + if (context) return context;
1.2156 + if (node.parentNode) return ko.contextFor(node.parentNode);
1.2157 + break;
1.2158 + }
1.2159 + return undefined;
1.2160 + };
1.2161 + ko.dataFor = function(node) {
1.2162 + var context = ko.contextFor(node);
1.2163 + return context ? context['$data'] : undefined;
1.2164 + };
1.2165 +
1.2166 + ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
1.2167 + ko.exportSymbol('applyBindings', ko.applyBindings);
1.2168 + ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
1.2169 + ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
1.2170 + ko.exportSymbol('contextFor', ko.contextFor);
1.2171 + ko.exportSymbol('dataFor', ko.dataFor);
1.2172 +})();
1.2173 +var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
1.2174 +ko.bindingHandlers['attr'] = {
1.2175 + 'update': function(element, valueAccessor, allBindingsAccessor) {
1.2176 + var value = ko.utils.unwrapObservable(valueAccessor()) || {};
1.2177 + for (var attrName in value) {
1.2178 + if (typeof attrName == "string") {
1.2179 + var attrValue = ko.utils.unwrapObservable(value[attrName]);
1.2180 +
1.2181 + // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
1.2182 + // when someProp is a "no value"-like value (strictly null, false, or undefined)
1.2183 + // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
1.2184 + var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
1.2185 + if (toRemove)
1.2186 + element.removeAttribute(attrName);
1.2187 +
1.2188 + // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
1.2189 + // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
1.2190 + // but instead of figuring out the mode, we'll just set the attribute through the Javascript
1.2191 + // property for IE <= 8.
1.2192 + if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
1.2193 + attrName = attrHtmlToJavascriptMap[attrName];
1.2194 + if (toRemove)
1.2195 + element.removeAttribute(attrName);
1.2196 + else
1.2197 + element[attrName] = attrValue;
1.2198 + } else if (!toRemove) {
1.2199 + try {
1.2200 + element.setAttribute(attrName, attrValue.toString());
1.2201 + } catch (err) {
1.2202 + // ignore for now
1.2203 + if (console) {
1.2204 + console.log("Can't set attribute " + attrName + " to " + attrValue + " error: " + err);
1.2205 + }
1.2206 + }
1.2207 + }
1.2208 +
1.2209 + // Treat "name" specially - although you can think of it as an attribute, it also needs
1.2210 + // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
1.2211 + // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
1.2212 + // entirely, and there's no strong reason to allow for such casing in HTML.
1.2213 + if (attrName === "name") {
1.2214 + ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
1.2215 + }
1.2216 + }
1.2217 + }
1.2218 + }
1.2219 +};
1.2220 +ko.bindingHandlers['checked'] = {
1.2221 + 'init': function (element, valueAccessor, allBindingsAccessor) {
1.2222 + var updateHandler = function() {
1.2223 + var valueToWrite;
1.2224 + if (element.type == "checkbox") {
1.2225 + valueToWrite = element.checked;
1.2226 + } else if ((element.type == "radio") && (element.checked)) {
1.2227 + valueToWrite = element.value;
1.2228 + } else {
1.2229 + return; // "checked" binding only responds to checkboxes and selected radio buttons
1.2230 + }
1.2231 +
1.2232 + var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
1.2233 + if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
1.2234 + // For checkboxes bound to an array, we add/remove the checkbox value to that array
1.2235 + // This works for both observable and non-observable arrays
1.2236 + var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
1.2237 + if (element.checked && (existingEntryIndex < 0))
1.2238 + modelValue.push(element.value);
1.2239 + else if ((!element.checked) && (existingEntryIndex >= 0))
1.2240 + modelValue.splice(existingEntryIndex, 1);
1.2241 + } else {
1.2242 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
1.2243 + }
1.2244 + };
1.2245 + ko.utils.registerEventHandler(element, "click", updateHandler);
1.2246 +
1.2247 + // IE 6 won't allow radio buttons to be selected unless they have a name
1.2248 + if ((element.type == "radio") && !element.name)
1.2249 + ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
1.2250 + },
1.2251 + 'update': function (element, valueAccessor) {
1.2252 + var value = ko.utils.unwrapObservable(valueAccessor());
1.2253 +
1.2254 + if (element.type == "checkbox") {
1.2255 + if (value instanceof Array) {
1.2256 + // When bound to an array, the checkbox being checked represents its value being present in that array
1.2257 + element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
1.2258 + } else {
1.2259 + // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
1.2260 + element.checked = value;
1.2261 + }
1.2262 + } else if (element.type == "radio") {
1.2263 + element.checked = (element.value == value);
1.2264 + }
1.2265 + }
1.2266 +};
1.2267 +var classesWrittenByBindingKey = '__ko__cssValue';
1.2268 +ko.bindingHandlers['css'] = {
1.2269 + 'update': function (element, valueAccessor) {
1.2270 + var value = ko.utils.unwrapObservable(valueAccessor());
1.2271 + if (typeof value == "object") {
1.2272 + for (var className in value) {
1.2273 + var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
1.2274 + ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
1.2275 + }
1.2276 + } else {
1.2277 + value = String(value || ''); // Make sure we don't try to store or set a non-string value
1.2278 + ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
1.2279 + element[classesWrittenByBindingKey] = value;
1.2280 + ko.utils.toggleDomNodeCssClass(element, value, true);
1.2281 + }
1.2282 + }
1.2283 +};
1.2284 +ko.bindingHandlers['enable'] = {
1.2285 + 'update': function (element, valueAccessor) {
1.2286 + var value = ko.utils.unwrapObservable(valueAccessor());
1.2287 + if (value && element.disabled)
1.2288 + element.removeAttribute("disabled");
1.2289 + else if ((!value) && (!element.disabled))
1.2290 + element.disabled = true;
1.2291 + }
1.2292 +};
1.2293 +
1.2294 +ko.bindingHandlers['disable'] = {
1.2295 + 'update': function (element, valueAccessor) {
1.2296 + ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
1.2297 + }
1.2298 +};
1.2299 +// For certain common events (currently just 'click'), allow a simplified data-binding syntax
1.2300 +// e.g. click:handler instead of the usual full-length event:{click:handler}
1.2301 +function makeEventHandlerShortcut(eventName) {
1.2302 + ko.bindingHandlers[eventName] = {
1.2303 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
1.2304 + var newValueAccessor = function () {
1.2305 + var result = {};
1.2306 + result[eventName] = valueAccessor();
1.2307 + return result;
1.2308 + };
1.2309 + return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
1.2310 + }
1.2311 + }
1.2312 +}
1.2313 +
1.2314 +ko.bindingHandlers['event'] = {
1.2315 + 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
1.2316 + var eventsToHandle = valueAccessor() || {};
1.2317 + for(var eventNameOutsideClosure in eventsToHandle) {
1.2318 + (function() {
1.2319 + var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
1.2320 + if (typeof eventName == "string") {
1.2321 + ko.utils.registerEventHandler(element, eventName, function (event) {
1.2322 + var handlerReturnValue;
1.2323 + var handlerFunction = valueAccessor()[eventName];
1.2324 + if (!handlerFunction)
1.2325 + return;
1.2326 + var allBindings = allBindingsAccessor();
1.2327 +
1.2328 + try {
1.2329 + // Take all the event args, and prefix with the viewmodel
1.2330 + var argsForHandler = ko.utils.makeArray(arguments);
1.2331 + argsForHandler.unshift(viewModel);
1.2332 + handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
1.2333 + } finally {
1.2334 + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
1.2335 + if (event.preventDefault)
1.2336 + event.preventDefault();
1.2337 + else
1.2338 + event.returnValue = false;
1.2339 + }
1.2340 + }
1.2341 +
1.2342 + var bubble = allBindings[eventName + 'Bubble'] !== false;
1.2343 + if (!bubble) {
1.2344 + event.cancelBubble = true;
1.2345 + if (event.stopPropagation)
1.2346 + event.stopPropagation();
1.2347 + }
1.2348 + });
1.2349 + }
1.2350 + })();
1.2351 + }
1.2352 + }
1.2353 +};
1.2354 +// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
1.2355 +// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
1.2356 +ko.bindingHandlers['foreach'] = {
1.2357 + makeTemplateValueAccessor: function(valueAccessor) {
1.2358 + return function() {
1.2359 + var modelValue = valueAccessor(),
1.2360 + unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
1.2361 +
1.2362 + // If unwrappedValue is the array, pass in the wrapped value on its own
1.2363 + // The value will be unwrapped and tracked within the template binding
1.2364 + // (See https://github.com/SteveSanderson/knockout/issues/523)
1.2365 + if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
1.2366 + return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
1.2367 +
1.2368 + // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
1.2369 + ko.utils.unwrapObservable(modelValue);
1.2370 + return {
1.2371 + 'foreach': unwrappedValue['data'],
1.2372 + 'as': unwrappedValue['as'],
1.2373 + 'includeDestroyed': unwrappedValue['includeDestroyed'],
1.2374 + 'afterAdd': unwrappedValue['afterAdd'],
1.2375 + 'beforeRemove': unwrappedValue['beforeRemove'],
1.2376 + 'afterRender': unwrappedValue['afterRender'],
1.2377 + 'beforeMove': unwrappedValue['beforeMove'],
1.2378 + 'afterMove': unwrappedValue['afterMove'],
1.2379 + 'templateEngine': ko.nativeTemplateEngine.instance
1.2380 + };
1.2381 + };
1.2382 + },
1.2383 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
1.2384 + return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
1.2385 + },
1.2386 + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
1.2387 + return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
1.2388 + }
1.2389 +};
1.2390 +ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
1.2391 +ko.virtualElements.allowedBindings['foreach'] = true;
1.2392 +var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
1.2393 +ko.bindingHandlers['hasfocus'] = {
1.2394 + 'init': function(element, valueAccessor, allBindingsAccessor) {
1.2395 + var handleElementFocusChange = function(isFocused) {
1.2396 + // Where possible, ignore which event was raised and determine focus state using activeElement,
1.2397 + // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
1.2398 + // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
1.2399 + // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
1.2400 + // from calling 'blur()' on the element when it loses focus.
1.2401 + // Discussion at https://github.com/SteveSanderson/knockout/pull/352
1.2402 + element[hasfocusUpdatingProperty] = true;
1.2403 + var ownerDoc = element.ownerDocument;
1.2404 + if ("activeElement" in ownerDoc) {
1.2405 + isFocused = (ownerDoc.activeElement === element);
1.2406 + }
1.2407 + var modelValue = valueAccessor();
1.2408 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true);
1.2409 + element[hasfocusUpdatingProperty] = false;
1.2410 + };
1.2411 + var handleElementFocusIn = handleElementFocusChange.bind(null, true);
1.2412 + var handleElementFocusOut = handleElementFocusChange.bind(null, false);
1.2413 +
1.2414 + ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
1.2415 + ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
1.2416 + ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
1.2417 + ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
1.2418 + },
1.2419 + 'update': function(element, valueAccessor) {
1.2420 + var value = ko.utils.unwrapObservable(valueAccessor());
1.2421 + if (!element[hasfocusUpdatingProperty]) {
1.2422 + value ? element.focus() : element.blur();
1.2423 + ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
1.2424 + }
1.2425 + }
1.2426 +};
1.2427 +ko.bindingHandlers['html'] = {
1.2428 + 'init': function() {
1.2429 + // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
1.2430 + return { 'controlsDescendantBindings': true };
1.2431 + },
1.2432 + 'update': function (element, valueAccessor) {
1.2433 + // setHtml will unwrap the value if needed
1.2434 + ko.utils.setHtml(element, valueAccessor());
1.2435 + }
1.2436 +};
1.2437 +var withIfDomDataKey = '__ko_withIfBindingData';
1.2438 +// Makes a binding like with or if
1.2439 +function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
1.2440 + ko.bindingHandlers[bindingKey] = {
1.2441 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
1.2442 + ko.utils.domData.set(element, withIfDomDataKey, {});
1.2443 + return { 'controlsDescendantBindings': true };
1.2444 + },
1.2445 + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
1.2446 + var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
1.2447 + dataValue = ko.utils.unwrapObservable(valueAccessor()),
1.2448 + shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
1.2449 + isFirstRender = !withIfData.savedNodes,
1.2450 + needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
1.2451 +
1.2452 + if (needsRefresh) {
1.2453 + if (isFirstRender) {
1.2454 + withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
1.2455 + }
1.2456 +
1.2457 + if (shouldDisplay) {
1.2458 + if (!isFirstRender) {
1.2459 + ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
1.2460 + }
1.2461 + ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
1.2462 + } else {
1.2463 + ko.virtualElements.emptyNode(element);
1.2464 + }
1.2465 +
1.2466 + withIfData.didDisplayOnLastUpdate = shouldDisplay;
1.2467 + }
1.2468 + }
1.2469 + };
1.2470 + ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
1.2471 + ko.virtualElements.allowedBindings[bindingKey] = true;
1.2472 +}
1.2473 +
1.2474 +// Construct the actual binding handlers
1.2475 +makeWithIfBinding('if');
1.2476 +makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
1.2477 +makeWithIfBinding('with', true /* isWith */, false /* isNot */,
1.2478 + function(bindingContext, dataValue) {
1.2479 + return bindingContext['createChildContext'](dataValue);
1.2480 + }
1.2481 +);
1.2482 +function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
1.2483 + if (preferModelValue) {
1.2484 + if (modelValue !== ko.selectExtensions.readValue(element))
1.2485 + ko.selectExtensions.writeValue(element, modelValue);
1.2486 + }
1.2487 +
1.2488 + // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
1.2489 + // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
1.2490 + // change the model value to match the dropdown.
1.2491 + if (modelValue !== ko.selectExtensions.readValue(element))
1.2492 + ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
1.2493 +};
1.2494 +
1.2495 +ko.bindingHandlers['options'] = {
1.2496 + 'update': function (element, valueAccessor, allBindingsAccessor) {
1.2497 + if (ko.utils.tagNameLower(element) !== "select")
1.2498 + throw new Error("options binding applies only to SELECT elements");
1.2499 +
1.2500 + var selectWasPreviouslyEmpty = element.length == 0;
1.2501 + var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
1.2502 + return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
1.2503 + }), function (node) {
1.2504 + return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
1.2505 + });
1.2506 + var previousScrollTop = element.scrollTop;
1.2507 +
1.2508 + var value = ko.utils.unwrapObservable(valueAccessor());
1.2509 + var selectedValue = element.value;
1.2510 +
1.2511 + // Remove all existing <option>s.
1.2512 + // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
1.2513 + while (element.length > 0) {
1.2514 + ko.cleanNode(element.options[0]);
1.2515 + element.remove(0);
1.2516 + }
1.2517 +
1.2518 + if (value) {
1.2519 + var allBindings = allBindingsAccessor(),
1.2520 + includeDestroyed = allBindings['optionsIncludeDestroyed'];
1.2521 +
1.2522 + if (typeof value.length != "number")
1.2523 + value = [value];
1.2524 + if (allBindings['optionsCaption']) {
1.2525 + var option = document.createElement("option");
1.2526 + ko.utils.setHtml(option, allBindings['optionsCaption']);
1.2527 + ko.selectExtensions.writeValue(option, undefined);
1.2528 + element.appendChild(option);
1.2529 + }
1.2530 +
1.2531 + for (var i = 0, j = value.length; i < j; i++) {
1.2532 + // Skip destroyed items
1.2533 + var arrayEntry = value[i];
1.2534 + if (arrayEntry && arrayEntry['_destroy'] && !includeDestroyed)
1.2535 + continue;
1.2536 +
1.2537 + var option = document.createElement("option");
1.2538 +
1.2539 + function applyToObject(object, predicate, defaultValue) {
1.2540 + var predicateType = typeof predicate;
1.2541 + if (predicateType == "function") // Given a function; run it against the data value
1.2542 + return predicate(object);
1.2543 + else if (predicateType == "string") // Given a string; treat it as a property name on the data value
1.2544 + return object[predicate];
1.2545 + else // Given no optionsText arg; use the data value itself
1.2546 + return defaultValue;
1.2547 + }
1.2548 +
1.2549 + // Apply a value to the option element
1.2550 + var optionValue = applyToObject(arrayEntry, allBindings['optionsValue'], arrayEntry);
1.2551 + ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
1.2552 +
1.2553 + // Apply some text to the option element
1.2554 + var optionText = applyToObject(arrayEntry, allBindings['optionsText'], optionValue);
1.2555 + ko.utils.setTextContent(option, optionText);
1.2556 +
1.2557 + element.appendChild(option);
1.2558 + }
1.2559 +
1.2560 + // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
1.2561 + // That's why we first added them without selection. Now it's time to set the selection.
1.2562 + var newOptions = element.getElementsByTagName("option");
1.2563 + var countSelectionsRetained = 0;
1.2564 + for (var i = 0, j = newOptions.length; i < j; i++) {
1.2565 + if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
1.2566 + ko.utils.setOptionNodeSelectionState(newOptions[i], true);
1.2567 + countSelectionsRetained++;
1.2568 + }
1.2569 + }
1.2570 +
1.2571 + element.scrollTop = previousScrollTop;
1.2572 +
1.2573 + if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
1.2574 + // Ensure consistency between model value and selected option.
1.2575 + // If the dropdown is being populated for the first time here (or was otherwise previously empty),
1.2576 + // the dropdown selection state is meaningless, so we preserve the model value.
1.2577 + ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.peekObservable(allBindings['value']), /* preferModelValue */ true);
1.2578 + }
1.2579 +
1.2580 + // Workaround for IE9 bug
1.2581 + ko.utils.ensureSelectElementIsRenderedCorrectly(element);
1.2582 + }
1.2583 + }
1.2584 +};
1.2585 +ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
1.2586 +ko.bindingHandlers['selectedOptions'] = {
1.2587 + 'init': function (element, valueAccessor, allBindingsAccessor) {
1.2588 + ko.utils.registerEventHandler(element, "change", function () {
1.2589 + var value = valueAccessor(), valueToWrite = [];
1.2590 + ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
1.2591 + if (node.selected)
1.2592 + valueToWrite.push(ko.selectExtensions.readValue(node));
1.2593 + });
1.2594 + ko.expressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
1.2595 + });
1.2596 + },
1.2597 + 'update': function (element, valueAccessor) {
1.2598 + if (ko.utils.tagNameLower(element) != "select")
1.2599 + throw new Error("values binding applies only to SELECT elements");
1.2600 +
1.2601 + var newValue = ko.utils.unwrapObservable(valueAccessor());
1.2602 + if (newValue && typeof newValue.length == "number") {
1.2603 + ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
1.2604 + var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
1.2605 + ko.utils.setOptionNodeSelectionState(node, isSelected);
1.2606 + });
1.2607 + }
1.2608 + }
1.2609 +};
1.2610 +ko.bindingHandlers['style'] = {
1.2611 + 'update': function (element, valueAccessor) {
1.2612 + var value = ko.utils.unwrapObservable(valueAccessor() || {});
1.2613 + for (var styleName in value) {
1.2614 + if (typeof styleName == "string") {
1.2615 + var styleValue = ko.utils.unwrapObservable(value[styleName]);
1.2616 + element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
1.2617 + }
1.2618 + }
1.2619 + }
1.2620 +};
1.2621 +ko.bindingHandlers['submit'] = {
1.2622 + 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
1.2623 + if (typeof valueAccessor() != "function")
1.2624 + throw new Error("The value for a submit binding must be a function");
1.2625 + ko.utils.registerEventHandler(element, "submit", function (event) {
1.2626 + var handlerReturnValue;
1.2627 + var value = valueAccessor();
1.2628 + try { handlerReturnValue = value.call(viewModel, element); }
1.2629 + finally {
1.2630 + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
1.2631 + if (event.preventDefault)
1.2632 + event.preventDefault();
1.2633 + else
1.2634 + event.returnValue = false;
1.2635 + }
1.2636 + }
1.2637 + });
1.2638 + }
1.2639 +};
1.2640 +ko.bindingHandlers['text'] = {
1.2641 + 'update': function (element, valueAccessor) {
1.2642 + ko.utils.setTextContent(element, valueAccessor());
1.2643 + }
1.2644 +};
1.2645 +ko.virtualElements.allowedBindings['text'] = true;
1.2646 +ko.bindingHandlers['uniqueName'] = {
1.2647 + 'init': function (element, valueAccessor) {
1.2648 + if (valueAccessor()) {
1.2649 + var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
1.2650 + ko.utils.setElementName(element, name);
1.2651 + }
1.2652 + }
1.2653 +};
1.2654 +ko.bindingHandlers['uniqueName'].currentIndex = 0;
1.2655 +ko.bindingHandlers['value'] = {
1.2656 + 'init': function (element, valueAccessor, allBindingsAccessor) {
1.2657 + // Always catch "change" event; possibly other events too if asked
1.2658 + var eventsToCatch = ["change"];
1.2659 + var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
1.2660 + var propertyChangedFired = false;
1.2661 + if (requestedEventsToCatch) {
1.2662 + if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
1.2663 + requestedEventsToCatch = [requestedEventsToCatch];
1.2664 + ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
1.2665 + eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
1.2666 + }
1.2667 +
1.2668 + var valueUpdateHandler = function() {
1.2669 + propertyChangedFired = false;
1.2670 + var modelValue = valueAccessor();
1.2671 + var elementValue = ko.selectExtensions.readValue(element);
1.2672 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
1.2673 + }
1.2674 +
1.2675 + // Workaround for https://github.com/SteveSanderson/knockout/issues/122
1.2676 + // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
1.2677 + var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
1.2678 + && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
1.2679 + if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
1.2680 + ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
1.2681 + ko.utils.registerEventHandler(element, "blur", function() {
1.2682 + if (propertyChangedFired) {
1.2683 + valueUpdateHandler();
1.2684 + }
1.2685 + });
1.2686 + }
1.2687 +
1.2688 + ko.utils.arrayForEach(eventsToCatch, function(eventName) {
1.2689 + // The syntax "after<eventname>" means "run the handler asynchronously after the event"
1.2690 + // This is useful, for example, to catch "keydown" events after the browser has updated the control
1.2691 + // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
1.2692 + var handler = valueUpdateHandler;
1.2693 + if (ko.utils.stringStartsWith(eventName, "after")) {
1.2694 + handler = function() { setTimeout(valueUpdateHandler, 0) };
1.2695 + eventName = eventName.substring("after".length);
1.2696 + }
1.2697 + ko.utils.registerEventHandler(element, eventName, handler);
1.2698 + });
1.2699 + },
1.2700 + 'update': function (element, valueAccessor) {
1.2701 + var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
1.2702 + var newValue = ko.utils.unwrapObservable(valueAccessor());
1.2703 + var elementValue = ko.selectExtensions.readValue(element);
1.2704 + var valueHasChanged = (newValue != elementValue);
1.2705 +
1.2706 + // 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).
1.2707 + // 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.
1.2708 + if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
1.2709 + valueHasChanged = true;
1.2710 +
1.2711 + if (valueHasChanged) {
1.2712 + var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
1.2713 + applyValueAction();
1.2714 +
1.2715 + // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
1.2716 + // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
1.2717 + // to apply the value as well.
1.2718 + var alsoApplyAsynchronously = valueIsSelectOption;
1.2719 + if (alsoApplyAsynchronously)
1.2720 + setTimeout(applyValueAction, 0);
1.2721 + }
1.2722 +
1.2723 + // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
1.2724 + // because you're not allowed to have a model value that disagrees with a visible UI selection.
1.2725 + if (valueIsSelectOption && (element.length > 0))
1.2726 + ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
1.2727 + }
1.2728 +};
1.2729 +ko.bindingHandlers['visible'] = {
1.2730 + 'update': function (element, valueAccessor) {
1.2731 + var value = ko.utils.unwrapObservable(valueAccessor());
1.2732 + var isCurrentlyVisible = !(element.style.display == "none");
1.2733 + if (value && !isCurrentlyVisible)
1.2734 + element.style.display = "";
1.2735 + else if ((!value) && isCurrentlyVisible)
1.2736 + element.style.display = "none";
1.2737 + }
1.2738 +};
1.2739 +// 'click' is just a shorthand for the usual full-length event:{click:handler}
1.2740 +makeEventHandlerShortcut('click');
1.2741 +// If you want to make a custom template engine,
1.2742 +//
1.2743 +// [1] Inherit from this class (like ko.nativeTemplateEngine does)
1.2744 +// [2] Override 'renderTemplateSource', supplying a function with this signature:
1.2745 +//
1.2746 +// function (templateSource, bindingContext, options) {
1.2747 +// // - templateSource.text() is the text of the template you should render
1.2748 +// // - bindingContext.$data is the data you should pass into the template
1.2749 +// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
1.2750 +// // and bindingContext.$root available in the template too
1.2751 +// // - options gives you access to any other properties set on "data-bind: { template: options }"
1.2752 +// //
1.2753 +// // Return value: an array of DOM nodes
1.2754 +// }
1.2755 +//
1.2756 +// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
1.2757 +//
1.2758 +// function (script) {
1.2759 +// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
1.2760 +// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
1.2761 +// }
1.2762 +//
1.2763 +// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
1.2764 +// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
1.2765 +// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
1.2766 +
1.2767 +ko.templateEngine = function () { };
1.2768 +
1.2769 +ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
1.2770 + throw new Error("Override renderTemplateSource");
1.2771 +};
1.2772 +
1.2773 +ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
1.2774 + throw new Error("Override createJavaScriptEvaluatorBlock");
1.2775 +};
1.2776 +
1.2777 +ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
1.2778 + // Named template
1.2779 + if (typeof template == "string") {
1.2780 + templateDocument = templateDocument || document;
1.2781 + var elem = templateDocument.getElementById(template);
1.2782 + if (!elem)
1.2783 + throw new Error("Cannot find template with ID " + template);
1.2784 + return new ko.templateSources.domElement(elem);
1.2785 + } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
1.2786 + // Anonymous template
1.2787 + return new ko.templateSources.anonymousTemplate(template);
1.2788 + } else
1.2789 + throw new Error("Unknown template type: " + template);
1.2790 +};
1.2791 +
1.2792 +ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
1.2793 + var templateSource = this['makeTemplateSource'](template, templateDocument);
1.2794 + return this['renderTemplateSource'](templateSource, bindingContext, options);
1.2795 +};
1.2796 +
1.2797 +ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
1.2798 + // Skip rewriting if requested
1.2799 + if (this['allowTemplateRewriting'] === false)
1.2800 + return true;
1.2801 + return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
1.2802 +};
1.2803 +
1.2804 +ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
1.2805 + var templateSource = this['makeTemplateSource'](template, templateDocument);
1.2806 + var rewritten = rewriterCallback(templateSource['text']());
1.2807 + templateSource['text'](rewritten);
1.2808 + templateSource['data']("isRewritten", true);
1.2809 +};
1.2810 +
1.2811 +ko.exportSymbol('templateEngine', ko.templateEngine);
1.2812 +
1.2813 +ko.templateRewriting = (function () {
1.2814 + var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
1.2815 + var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
1.2816 +
1.2817 + function validateDataBindValuesForRewriting(keyValueArray) {
1.2818 + var allValidators = ko.expressionRewriting.bindingRewriteValidators;
1.2819 + for (var i = 0; i < keyValueArray.length; i++) {
1.2820 + var key = keyValueArray[i]['key'];
1.2821 + if (allValidators.hasOwnProperty(key)) {
1.2822 + var validator = allValidators[key];
1.2823 +
1.2824 + if (typeof validator === "function") {
1.2825 + var possibleErrorMessage = validator(keyValueArray[i]['value']);
1.2826 + if (possibleErrorMessage)
1.2827 + throw new Error(possibleErrorMessage);
1.2828 + } else if (!validator) {
1.2829 + throw new Error("This template engine does not support the '" + key + "' binding within its templates");
1.2830 + }
1.2831 + }
1.2832 + }
1.2833 + }
1.2834 +
1.2835 + function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
1.2836 + var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
1.2837 + validateDataBindValuesForRewriting(dataBindKeyValueArray);
1.2838 + var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray);
1.2839 +
1.2840 + // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
1.2841 + // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
1.2842 + // extra indirection.
1.2843 + var applyBindingsToNextSiblingScript =
1.2844 + "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()})";
1.2845 + return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
1.2846 + }
1.2847 +
1.2848 + return {
1.2849 + ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
1.2850 + if (!templateEngine['isTemplateRewritten'](template, templateDocument))
1.2851 + templateEngine['rewriteTemplate'](template, function (htmlString) {
1.2852 + return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
1.2853 + }, templateDocument);
1.2854 + },
1.2855 +
1.2856 + memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
1.2857 + return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
1.2858 + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
1.2859 + }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
1.2860 + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
1.2861 + });
1.2862 + },
1.2863 +
1.2864 + applyMemoizedBindingsToNextSibling: function (bindings) {
1.2865 + return ko.memoization.memoize(function (domNode, bindingContext) {
1.2866 + if (domNode.nextSibling)
1.2867 + ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
1.2868 + });
1.2869 + }
1.2870 + }
1.2871 +})();
1.2872 +
1.2873 +
1.2874 +// Exported only because it has to be referenced by string lookup from within rewritten template
1.2875 +ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
1.2876 +(function() {
1.2877 + // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
1.2878 + // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
1.2879 + //
1.2880 + // Two are provided by default:
1.2881 + // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
1.2882 + // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
1.2883 + // without reading/writing the actual element text content, since it will be overwritten
1.2884 + // with the rendered template output.
1.2885 + // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
1.2886 + // Template sources need to have the following functions:
1.2887 + // text() - returns the template text from your storage location
1.2888 + // text(value) - writes the supplied template text to your storage location
1.2889 + // data(key) - reads values stored using data(key, value) - see below
1.2890 + // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
1.2891 + //
1.2892 + // Optionally, template sources can also have the following functions:
1.2893 + // nodes() - returns a DOM element containing the nodes of this template, where available
1.2894 + // nodes(value) - writes the given DOM element to your storage location
1.2895 + // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
1.2896 + // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
1.2897 + //
1.2898 + // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
1.2899 + // using and overriding "makeTemplateSource" to return an instance of your custom template source.
1.2900 +
1.2901 + ko.templateSources = {};
1.2902 +
1.2903 + // ---- ko.templateSources.domElement -----
1.2904 +
1.2905 + ko.templateSources.domElement = function(element) {
1.2906 + this.domElement = element;
1.2907 + }
1.2908 +
1.2909 + ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
1.2910 + var tagNameLower = ko.utils.tagNameLower(this.domElement),
1.2911 + elemContentsProperty = tagNameLower === "script" ? "text"
1.2912 + : tagNameLower === "textarea" ? "value"
1.2913 + : "innerHTML";
1.2914 +
1.2915 + if (arguments.length == 0) {
1.2916 + return this.domElement[elemContentsProperty];
1.2917 + } else {
1.2918 + var valueToWrite = arguments[0];
1.2919 + if (elemContentsProperty === "innerHTML")
1.2920 + ko.utils.setHtml(this.domElement, valueToWrite);
1.2921 + else
1.2922 + this.domElement[elemContentsProperty] = valueToWrite;
1.2923 + }
1.2924 + };
1.2925 +
1.2926 + ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
1.2927 + if (arguments.length === 1) {
1.2928 + return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
1.2929 + } else {
1.2930 + ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
1.2931 + }
1.2932 + };
1.2933 +
1.2934 + // ---- ko.templateSources.anonymousTemplate -----
1.2935 + // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
1.2936 + // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
1.2937 + // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
1.2938 +
1.2939 + var anonymousTemplatesDomDataKey = "__ko_anon_template__";
1.2940 + ko.templateSources.anonymousTemplate = function(element) {
1.2941 + this.domElement = element;
1.2942 + }
1.2943 + ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
1.2944 + ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
1.2945 + if (arguments.length == 0) {
1.2946 + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
1.2947 + if (templateData.textData === undefined && templateData.containerData)
1.2948 + templateData.textData = templateData.containerData.innerHTML;
1.2949 + return templateData.textData;
1.2950 + } else {
1.2951 + var valueToWrite = arguments[0];
1.2952 + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
1.2953 + }
1.2954 + };
1.2955 + ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
1.2956 + if (arguments.length == 0) {
1.2957 + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
1.2958 + return templateData.containerData;
1.2959 + } else {
1.2960 + var valueToWrite = arguments[0];
1.2961 + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
1.2962 + }
1.2963 + };
1.2964 +
1.2965 + ko.exportSymbol('templateSources', ko.templateSources);
1.2966 + ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
1.2967 + ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
1.2968 +})();
1.2969 +(function () {
1.2970 + var _templateEngine;
1.2971 + ko.setTemplateEngine = function (templateEngine) {
1.2972 + if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
1.2973 + throw new Error("templateEngine must inherit from ko.templateEngine");
1.2974 + _templateEngine = templateEngine;
1.2975 + }
1.2976 +
1.2977 + function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
1.2978 + var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
1.2979 + while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
1.2980 + nextInQueue = ko.virtualElements.nextSibling(node);
1.2981 + if (node.nodeType === 1 || node.nodeType === 8)
1.2982 + action(node);
1.2983 + }
1.2984 + }
1.2985 +
1.2986 + function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
1.2987 + // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
1.2988 + // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
1.2989 + // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
1.2990 + // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
1.2991 + // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
1.2992 +
1.2993 + if (continuousNodeArray.length) {
1.2994 + var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
1.2995 +
1.2996 + // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
1.2997 + // whereas a regular applyBindings won't introduce new memoized nodes
1.2998 + invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
1.2999 + ko.applyBindings(bindingContext, node);
1.3000 + });
1.3001 + invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
1.3002 + ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
1.3003 + });
1.3004 + }
1.3005 + }
1.3006 +
1.3007 + function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
1.3008 + return nodeOrNodeArray.nodeType ? nodeOrNodeArray
1.3009 + : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
1.3010 + : null;
1.3011 + }
1.3012 +
1.3013 + function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
1.3014 + options = options || {};
1.3015 + var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
1.3016 + var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
1.3017 + var templateEngineToUse = (options['templateEngine'] || _templateEngine);
1.3018 + ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
1.3019 + var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
1.3020 +
1.3021 + // Loosely check result is an array of DOM nodes
1.3022 + if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
1.3023 + throw new Error("Template engine must return an array of DOM nodes");
1.3024 +
1.3025 + var haveAddedNodesToParent = false;
1.3026 + switch (renderMode) {
1.3027 + case "replaceChildren":
1.3028 + ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
1.3029 + haveAddedNodesToParent = true;
1.3030 + break;
1.3031 + case "replaceNode":
1.3032 + ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
1.3033 + haveAddedNodesToParent = true;
1.3034 + break;
1.3035 + case "ignoreTargetNode": break;
1.3036 + default:
1.3037 + throw new Error("Unknown renderMode: " + renderMode);
1.3038 + }
1.3039 +
1.3040 + if (haveAddedNodesToParent) {
1.3041 + activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
1.3042 + if (options['afterRender'])
1.3043 + ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
1.3044 + }
1.3045 +
1.3046 + return renderedNodesArray;
1.3047 + }
1.3048 +
1.3049 + ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
1.3050 + options = options || {};
1.3051 + if ((options['templateEngine'] || _templateEngine) == undefined)
1.3052 + throw new Error("Set a template engine before calling renderTemplate");
1.3053 + renderMode = renderMode || "replaceChildren";
1.3054 +
1.3055 + if (targetNodeOrNodeArray) {
1.3056 + var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
1.3057 +
1.3058 + var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
1.3059 + var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
1.3060 +
1.3061 + return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
1.3062 + function () {
1.3063 + // Ensure we've got a proper binding context to work with
1.3064 + var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
1.3065 + ? dataOrBindingContext
1.3066 + : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
1.3067 +
1.3068 + // Support selecting template as a function of the data being rendered
1.3069 + var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
1.3070 +
1.3071 + var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
1.3072 + if (renderMode == "replaceNode") {
1.3073 + targetNodeOrNodeArray = renderedNodesArray;
1.3074 + firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
1.3075 + }
1.3076 + },
1.3077 + null,
1.3078 + { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
1.3079 + );
1.3080 + } else {
1.3081 + // 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
1.3082 + return ko.memoization.memoize(function (domNode) {
1.3083 + ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
1.3084 + });
1.3085 + }
1.3086 + };
1.3087 +
1.3088 + ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
1.3089 + // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
1.3090 + // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
1.3091 + var arrayItemContext;
1.3092 +
1.3093 + // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
1.3094 + var executeTemplateForArrayItem = function (arrayValue, index) {
1.3095 + // Support selecting template as a function of the data being rendered
1.3096 + arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue), options['as']);
1.3097 + arrayItemContext['$index'] = index;
1.3098 + var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
1.3099 + return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
1.3100 + }
1.3101 +
1.3102 + // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
1.3103 + var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
1.3104 + activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
1.3105 + if (options['afterRender'])
1.3106 + options['afterRender'](addedNodesArray, arrayValue);
1.3107 + };
1.3108 +
1.3109 + return ko.dependentObservable(function () {
1.3110 + var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
1.3111 + if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
1.3112 + unwrappedArray = [unwrappedArray];
1.3113 +
1.3114 + // Filter out any entries marked as destroyed
1.3115 + var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
1.3116 + return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
1.3117 + });
1.3118 +
1.3119 + // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
1.3120 + // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
1.3121 + ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
1.3122 +
1.3123 + }, null, { disposeWhenNodeIsRemoved: targetNode });
1.3124 + };
1.3125 +
1.3126 + var templateComputedDomDataKey = '__ko__templateComputedDomDataKey__';
1.3127 + function disposeOldComputedAndStoreNewOne(element, newComputed) {
1.3128 + var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
1.3129 + if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
1.3130 + oldComputed.dispose();
1.3131 + ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
1.3132 + }
1.3133 +
1.3134 + ko.bindingHandlers['template'] = {
1.3135 + 'init': function(element, valueAccessor) {
1.3136 + // Support anonymous templates
1.3137 + var bindingValue = ko.utils.unwrapObservable(valueAccessor());
1.3138 + if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
1.3139 + // It's an anonymous template - store the element contents, then clear the element
1.3140 + var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
1.3141 + container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
1.3142 + new ko.templateSources.anonymousTemplate(element)['nodes'](container);
1.3143 + }
1.3144 + return { 'controlsDescendantBindings': true };
1.3145 + },
1.3146 + 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
1.3147 + var templateName = ko.utils.unwrapObservable(valueAccessor()),
1.3148 + options = {},
1.3149 + shouldDisplay = true,
1.3150 + dataValue,
1.3151 + templateComputed = null;
1.3152 +
1.3153 + if (typeof templateName != "string") {
1.3154 + options = templateName;
1.3155 + templateName = options['name'];
1.3156 +
1.3157 + // Support "if"/"ifnot" conditions
1.3158 + if ('if' in options)
1.3159 + shouldDisplay = ko.utils.unwrapObservable(options['if']);
1.3160 + if (shouldDisplay && 'ifnot' in options)
1.3161 + shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
1.3162 +
1.3163 + dataValue = ko.utils.unwrapObservable(options['data']);
1.3164 + }
1.3165 +
1.3166 + if ('foreach' in options) {
1.3167 + // Render once for each data point (treating data set as empty if shouldDisplay==false)
1.3168 + var dataArray = (shouldDisplay && options['foreach']) || [];
1.3169 + templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
1.3170 + } else if (!shouldDisplay) {
1.3171 + ko.virtualElements.emptyNode(element);
1.3172 + } else {
1.3173 + // Render once for this single data point (or use the viewModel if no data was provided)
1.3174 + var innerBindingContext = ('data' in options) ?
1.3175 + bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
1.3176 + bindingContext; // Given no explicit 'data' value, we retain the same binding context
1.3177 + templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
1.3178 + }
1.3179 +
1.3180 + // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
1.3181 + disposeOldComputedAndStoreNewOne(element, templateComputed);
1.3182 + }
1.3183 + };
1.3184 +
1.3185 + // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
1.3186 + ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
1.3187 + var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
1.3188 +
1.3189 + if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
1.3190 + return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
1.3191 +
1.3192 + if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
1.3193 + return null; // Named templates can be rewritten, so return "no error"
1.3194 + return "This template engine does not support anonymous templates nested within its templates";
1.3195 + };
1.3196 +
1.3197 + ko.virtualElements.allowedBindings['template'] = true;
1.3198 +})();
1.3199 +
1.3200 +ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
1.3201 +ko.exportSymbol('renderTemplate', ko.renderTemplate);
1.3202 +
1.3203 +ko.utils.compareArrays = (function () {
1.3204 + var statusNotInOld = 'added', statusNotInNew = 'deleted';
1.3205 +
1.3206 + // Simple calculation based on Levenshtein distance.
1.3207 + function compareArrays(oldArray, newArray, dontLimitMoves) {
1.3208 + oldArray = oldArray || [];
1.3209 + newArray = newArray || [];
1.3210 +
1.3211 + if (oldArray.length <= newArray.length)
1.3212 + return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, dontLimitMoves);
1.3213 + else
1.3214 + return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, dontLimitMoves);
1.3215 + }
1.3216 +
1.3217 + function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, dontLimitMoves) {
1.3218 + var myMin = Math.min,
1.3219 + myMax = Math.max,
1.3220 + editDistanceMatrix = [],
1.3221 + smlIndex, smlIndexMax = smlArray.length,
1.3222 + bigIndex, bigIndexMax = bigArray.length,
1.3223 + compareRange = (bigIndexMax - smlIndexMax) || 1,
1.3224 + maxDistance = smlIndexMax + bigIndexMax + 1,
1.3225 + thisRow, lastRow,
1.3226 + bigIndexMaxForRow, bigIndexMinForRow;
1.3227 +
1.3228 + for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
1.3229 + lastRow = thisRow;
1.3230 + editDistanceMatrix.push(thisRow = []);
1.3231 + bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
1.3232 + bigIndexMinForRow = myMax(0, smlIndex - 1);
1.3233 + for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
1.3234 + if (!bigIndex)
1.3235 + thisRow[bigIndex] = smlIndex + 1;
1.3236 + else if (!smlIndex) // Top row - transform empty array into new array via additions
1.3237 + thisRow[bigIndex] = bigIndex + 1;
1.3238 + else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
1.3239 + thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
1.3240 + else {
1.3241 + var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
1.3242 + var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
1.3243 + thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
1.3244 + }
1.3245 + }
1.3246 + }
1.3247 +
1.3248 + var editScript = [], meMinusOne, notInSml = [], notInBig = [];
1.3249 + for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
1.3250 + meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
1.3251 + if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
1.3252 + notInSml.push(editScript[editScript.length] = { // added
1.3253 + 'status': statusNotInSml,
1.3254 + 'value': bigArray[--bigIndex],
1.3255 + 'index': bigIndex });
1.3256 + } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
1.3257 + notInBig.push(editScript[editScript.length] = { // deleted
1.3258 + 'status': statusNotInBig,
1.3259 + 'value': smlArray[--smlIndex],
1.3260 + 'index': smlIndex });
1.3261 + } else {
1.3262 + editScript.push({
1.3263 + 'status': "retained",
1.3264 + 'value': bigArray[--bigIndex] });
1.3265 + --smlIndex;
1.3266 + }
1.3267 + }
1.3268 +
1.3269 + if (notInSml.length && notInBig.length) {
1.3270 + // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
1.3271 + // smlIndexMax keeps the time complexity of this algorithm linear.
1.3272 + var limitFailedCompares = smlIndexMax * 10, failedCompares,
1.3273 + a, d, notInSmlItem, notInBigItem;
1.3274 + // Go through the items that have been added and deleted and try to find matches between them.
1.3275 + for (failedCompares = a = 0; (dontLimitMoves || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
1.3276 + for (d = 0; notInBigItem = notInBig[d]; d++) {
1.3277 + if (notInSmlItem['value'] === notInBigItem['value']) {
1.3278 + notInSmlItem['moved'] = notInBigItem['index'];
1.3279 + notInBigItem['moved'] = notInSmlItem['index'];
1.3280 + notInBig.splice(d,1); // This item is marked as moved; so remove it from notInBig list
1.3281 + failedCompares = d = 0; // Reset failed compares count because we're checking for consecutive failures
1.3282 + break;
1.3283 + }
1.3284 + }
1.3285 + failedCompares += d;
1.3286 + }
1.3287 + }
1.3288 + return editScript.reverse();
1.3289 + }
1.3290 +
1.3291 + return compareArrays;
1.3292 +})();
1.3293 +
1.3294 +ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
1.3295 +
1.3296 +(function () {
1.3297 + // Objective:
1.3298 + // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
1.3299 + // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
1.3300 + // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
1.3301 + // 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
1.3302 + // previously mapped - retain those nodes, and just insert/delete other ones
1.3303 +
1.3304 + // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
1.3305 + // You can use this, for example, to activate bindings on those nodes.
1.3306 +
1.3307 + function fixUpNodesToBeMovedOrRemoved(contiguousNodeArray) {
1.3308 + // Before moving, deleting, or replacing a set of nodes that were previously outputted by the "map" function, we have to reconcile
1.3309 + // them against what is in the DOM right now. It may be that some of the nodes have already been removed from the document,
1.3310 + // or that new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
1.3311 + // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
1.3312 + // So, this function translates the old "map" output array into its best guess of what set of current DOM nodes should be removed.
1.3313 + //
1.3314 + // Rules:
1.3315 + // [A] Any leading nodes that aren't in the document any more should be ignored
1.3316 + // These most likely correspond to memoization nodes that were already removed during binding
1.3317 + // See https://github.com/SteveSanderson/knockout/pull/440
1.3318 + // [B] We want to output a contiguous series of nodes that are still in the document. So, ignore any nodes that
1.3319 + // have already been removed, and include any nodes that have been inserted among the previous collection
1.3320 +
1.3321 + // Rule [A]
1.3322 + while (contiguousNodeArray.length && !ko.utils.domNodeIsAttachedToDocument(contiguousNodeArray[0]))
1.3323 + contiguousNodeArray.splice(0, 1);
1.3324 +
1.3325 + // Rule [B]
1.3326 + if (contiguousNodeArray.length > 1) {
1.3327 + // Build up the actual new contiguous node set
1.3328 + var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
1.3329 + while (current !== last) {
1.3330 + current = current.nextSibling;
1.3331 + if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
1.3332 + return;
1.3333 + newContiguousSet.push(current);
1.3334 + }
1.3335 +
1.3336 + // ... then mutate the input array to match this.
1.3337 + // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
1.3338 + Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
1.3339 + }
1.3340 + return contiguousNodeArray;
1.3341 + }
1.3342 +
1.3343 + function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
1.3344 + // Map this array value inside a dependentObservable so we re-map when any dependency changes
1.3345 + var mappedNodes = [];
1.3346 + var dependentObservable = ko.dependentObservable(function() {
1.3347 + var newMappedNodes = mapping(valueToMap, index) || [];
1.3348 +
1.3349 + // On subsequent evaluations, just replace the previously-inserted DOM nodes
1.3350 + if (mappedNodes.length > 0) {
1.3351 + ko.utils.replaceDomNodes(fixUpNodesToBeMovedOrRemoved(mappedNodes), newMappedNodes);
1.3352 + if (callbackAfterAddingNodes)
1.3353 + ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
1.3354 + }
1.3355 +
1.3356 + // Replace the contents of the mappedNodes array, thereby updating the record
1.3357 + // of which nodes would be deleted if valueToMap was itself later removed
1.3358 + mappedNodes.splice(0, mappedNodes.length);
1.3359 + ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
1.3360 + }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
1.3361 + return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
1.3362 + }
1.3363 +
1.3364 + var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
1.3365 +
1.3366 + ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
1.3367 + // Compare the provided array against the previous one
1.3368 + array = array || [];
1.3369 + options = options || {};
1.3370 + var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
1.3371 + var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
1.3372 + var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
1.3373 + var editScript = ko.utils.compareArrays(lastArray, array);
1.3374 +
1.3375 + // Build the new mapping result
1.3376 + var newMappingResult = [];
1.3377 + var lastMappingResultIndex = 0;
1.3378 + var newMappingResultIndex = 0;
1.3379 +
1.3380 + var nodesToDelete = [];
1.3381 + var itemsToProcess = [];
1.3382 + var itemsForBeforeRemoveCallbacks = [];
1.3383 + var itemsForMoveCallbacks = [];
1.3384 + var itemsForAfterAddCallbacks = [];
1.3385 + var mapData;
1.3386 +
1.3387 + function itemMovedOrRetained(editScriptIndex, oldPosition) {
1.3388 + mapData = lastMappingResult[oldPosition];
1.3389 + if (newMappingResultIndex !== oldPosition)
1.3390 + itemsForMoveCallbacks[editScriptIndex] = mapData;
1.3391 + // Since updating the index might change the nodes, do so before calling fixUpNodesToBeMovedOrRemoved
1.3392 + mapData.indexObservable(newMappingResultIndex++);
1.3393 + fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes);
1.3394 + newMappingResult.push(mapData);
1.3395 + itemsToProcess.push(mapData);
1.3396 + }
1.3397 +
1.3398 + function callCallback(callback, items) {
1.3399 + if (callback) {
1.3400 + for (var i = 0, n = items.length; i < n; i++) {
1.3401 + if (items[i]) {
1.3402 + ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
1.3403 + callback(node, i, items[i].arrayEntry);
1.3404 + });
1.3405 + }
1.3406 + }
1.3407 + }
1.3408 + }
1.3409 +
1.3410 + for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
1.3411 + movedIndex = editScriptItem['moved'];
1.3412 + switch (editScriptItem['status']) {
1.3413 + case "deleted":
1.3414 + if (movedIndex === undefined) {
1.3415 + mapData = lastMappingResult[lastMappingResultIndex];
1.3416 +
1.3417 + // Stop tracking changes to the mapping for these nodes
1.3418 + if (mapData.dependentObservable)
1.3419 + mapData.dependentObservable.dispose();
1.3420 +
1.3421 + // Queue these nodes for later removal
1.3422 + nodesToDelete.push.apply(nodesToDelete, fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes));
1.3423 + if (options['beforeRemove']) {
1.3424 + itemsForBeforeRemoveCallbacks[i] = mapData;
1.3425 + itemsToProcess.push(mapData);
1.3426 + }
1.3427 + }
1.3428 + lastMappingResultIndex++;
1.3429 + break;
1.3430 +
1.3431 + case "retained":
1.3432 + itemMovedOrRetained(i, lastMappingResultIndex++);
1.3433 + break;
1.3434 +
1.3435 + case "added":
1.3436 + if (movedIndex !== undefined) {
1.3437 + itemMovedOrRetained(i, movedIndex);
1.3438 + } else {
1.3439 + mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
1.3440 + newMappingResult.push(mapData);
1.3441 + itemsToProcess.push(mapData);
1.3442 + if (!isFirstExecution)
1.3443 + itemsForAfterAddCallbacks[i] = mapData;
1.3444 + }
1.3445 + break;
1.3446 + }
1.3447 + }
1.3448 +
1.3449 + // Call beforeMove first before any changes have been made to the DOM
1.3450 + callCallback(options['beforeMove'], itemsForMoveCallbacks);
1.3451 +
1.3452 + // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
1.3453 + ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
1.3454 +
1.3455 + // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
1.3456 + for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
1.3457 + // Get nodes for newly added items
1.3458 + if (!mapData.mappedNodes)
1.3459 + ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
1.3460 +
1.3461 + // Put nodes in the right place if they aren't there already
1.3462 + for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
1.3463 + if (node !== nextNode)
1.3464 + ko.virtualElements.insertAfter(domNode, node, lastNode);
1.3465 + }
1.3466 +
1.3467 + // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
1.3468 + if (!mapData.initialized && callbackAfterAddingNodes) {
1.3469 + callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
1.3470 + mapData.initialized = true;
1.3471 + }
1.3472 + }
1.3473 +
1.3474 + // If there's a beforeRemove callback, call it after reordering.
1.3475 + // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
1.3476 + // some sort of animation, which is why we first reorder the nodes that will be removed. If the
1.3477 + // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
1.3478 + // Perhaps we'll make that change in the future if this scenario becomes more common.
1.3479 + callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
1.3480 +
1.3481 + // Finally call afterMove and afterAdd callbacks
1.3482 + callCallback(options['afterMove'], itemsForMoveCallbacks);
1.3483 + callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
1.3484 +
1.3485 + // Store a copy of the array items we just considered so we can difference it next time
1.3486 + ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
1.3487 + }
1.3488 +})();
1.3489 +
1.3490 +ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
1.3491 +ko.nativeTemplateEngine = function () {
1.3492 + this['allowTemplateRewriting'] = false;
1.3493 +}
1.3494 +
1.3495 +ko.nativeTemplateEngine.prototype = new ko.templateEngine();
1.3496 +ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
1.3497 + var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
1.3498 + templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
1.3499 + templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
1.3500 +
1.3501 + if (templateNodes) {
1.3502 + return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
1.3503 + } else {
1.3504 + var templateText = templateSource['text']();
1.3505 + return ko.utils.parseHtmlFragment(templateText);
1.3506 + }
1.3507 +};
1.3508 +
1.3509 +ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
1.3510 +ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
1.3511 +
1.3512 +ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
1.3513 +(function() {
1.3514 + ko.jqueryTmplTemplateEngine = function () {
1.3515 + // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
1.3516 + // doesn't expose a version number, so we have to infer it.
1.3517 + // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
1.3518 + // which KO internally refers to as version "2", so older versions are no longer detected.
1.3519 + var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
1.3520 + if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
1.3521 + return 0;
1.3522 + // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
1.3523 + try {
1.3524 + if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
1.3525 + // Since 1.0.0pre, custom tags should append markup to an array called "__"
1.3526 + return 2; // Final version of jquery.tmpl
1.3527 + }
1.3528 + } catch(ex) { /* Apparently not the version we were looking for */ }
1.3529 +
1.3530 + return 1; // Any older version that we don't support
1.3531 + })();
1.3532 +
1.3533 + function ensureHasReferencedJQueryTemplates() {
1.3534 + if (jQueryTmplVersion < 2)
1.3535 + throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
1.3536 + }
1.3537 +
1.3538 + function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
1.3539 + return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
1.3540 + }
1.3541 +
1.3542 + this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
1.3543 + options = options || {};
1.3544 + ensureHasReferencedJQueryTemplates();
1.3545 +
1.3546 + // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
1.3547 + var precompiled = templateSource['data']('precompiled');
1.3548 + if (!precompiled) {
1.3549 + var templateText = templateSource['text']() || "";
1.3550 + // Wrap in "with($whatever.koBindingContext) { ... }"
1.3551 + templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
1.3552 +
1.3553 + precompiled = jQuery['template'](null, templateText);
1.3554 + templateSource['data']('precompiled', precompiled);
1.3555 + }
1.3556 +
1.3557 + var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
1.3558 + var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
1.3559 +
1.3560 + var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
1.3561 + resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
1.3562 +
1.3563 + jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
1.3564 + return resultNodes;
1.3565 + };
1.3566 +
1.3567 + this['createJavaScriptEvaluatorBlock'] = function(script) {
1.3568 + return "{{ko_code ((function() { return " + script + " })()) }}";
1.3569 + };
1.3570 +
1.3571 + this['addTemplate'] = function(templateName, templateMarkup) {
1.3572 + document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
1.3573 + };
1.3574 +
1.3575 + if (jQueryTmplVersion > 0) {
1.3576 + jQuery['tmpl']['tag']['ko_code'] = {
1.3577 + open: "__.push($1 || '');"
1.3578 + };
1.3579 + jQuery['tmpl']['tag']['ko_with'] = {
1.3580 + open: "with($1) {",
1.3581 + close: "} "
1.3582 + };
1.3583 + }
1.3584 + };
1.3585 +
1.3586 + ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
1.3587 +
1.3588 + // Use this one by default *only if jquery.tmpl is referenced*
1.3589 + var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
1.3590 + if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
1.3591 + ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
1.3592 +
1.3593 + ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
1.3594 +})();
1.3595 +});
1.3596 +})(window,document,navigator,window["jQuery"]);
1.3597 +})();
1.3598 \ No newline at end of file
2.1 --- a/ko/fx/src/main/resources/org/apidesign/html/kofx/knockout-2.2.1.js Wed Jun 26 20:03:40 2013 +0200
2.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
2.3 @@ -1,3594 +0,0 @@
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 - dependentObservable.valueHasMutated = function() {
2.1311 - _hasBeenEvaluated = false;
2.1312 - evaluateImmediate();
2.1313 - };
2.1314 -
2.1315 - ko.subscribable.call(dependentObservable);
2.1316 - ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
2.1317 -
2.1318 - ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
2.1319 - ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
2.1320 - ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
2.1321 - ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
2.1322 -
2.1323 - // Evaluate, unless deferEvaluation is true
2.1324 - if (options['deferEvaluation'] !== true)
2.1325 - evaluateImmediate();
2.1326 -
2.1327 - // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values.
2.1328 - // But skip if isActive is false (there will never be any dependencies to dispose).
2.1329 - // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
2.1330 - // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
2.1331 - if (disposeWhenNodeIsRemoved && isActive()) {
2.1332 - dispose = function() {
2.1333 - ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
2.1334 - disposeAllSubscriptionsToDependencies();
2.1335 - };
2.1336 - ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
2.1337 - var existingDisposeWhenFunction = disposeWhen;
2.1338 - disposeWhen = function () {
2.1339 - return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
2.1340 - }
2.1341 - }
2.1342 -
2.1343 - return dependentObservable;
2.1344 -};
2.1345 -
2.1346 -ko.isComputed = function(instance) {
2.1347 - return ko.hasPrototype(instance, ko.dependentObservable);
2.1348 -};
2.1349 -
2.1350 -var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
2.1351 -ko.dependentObservable[protoProp] = ko.observable;
2.1352 -
2.1353 -ko.dependentObservable['fn'] = {};
2.1354 -ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
2.1355 -
2.1356 -ko.exportSymbol('dependentObservable', ko.dependentObservable);
2.1357 -ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
2.1358 -ko.exportSymbol('isComputed', ko.isComputed);
2.1359 -
2.1360 -(function() {
2.1361 - var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
2.1362 -
2.1363 - ko.toJS = function(rootObject) {
2.1364 - if (arguments.length == 0)
2.1365 - throw new Error("When calling ko.toJS, pass the object you want to convert.");
2.1366 -
2.1367 - // We just unwrap everything at every level in the object graph
2.1368 - return mapJsObjectGraph(rootObject, function(valueToMap) {
2.1369 - // Loop because an observable's value might in turn be another observable wrapper
2.1370 - for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
2.1371 - valueToMap = valueToMap();
2.1372 - return valueToMap;
2.1373 - });
2.1374 - };
2.1375 -
2.1376 - ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
2.1377 - var plainJavaScriptObject = ko.toJS(rootObject);
2.1378 - return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
2.1379 - };
2.1380 -
2.1381 - function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
2.1382 - visitedObjects = visitedObjects || new objectLookup();
2.1383 -
2.1384 - rootObject = mapInputCallback(rootObject);
2.1385 - var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
2.1386 - if (!canHaveProperties)
2.1387 - return rootObject;
2.1388 -
2.1389 - var outputProperties = rootObject instanceof Array ? [] : {};
2.1390 - visitedObjects.save(rootObject, outputProperties);
2.1391 -
2.1392 - visitPropertiesOrArrayEntries(rootObject, function(indexer) {
2.1393 - var propertyValue = mapInputCallback(rootObject[indexer]);
2.1394 -
2.1395 - switch (typeof propertyValue) {
2.1396 - case "boolean":
2.1397 - case "number":
2.1398 - case "string":
2.1399 - case "function":
2.1400 - outputProperties[indexer] = propertyValue;
2.1401 - break;
2.1402 - case "object":
2.1403 - case "undefined":
2.1404 - var previouslyMappedValue = visitedObjects.get(propertyValue);
2.1405 - outputProperties[indexer] = (previouslyMappedValue !== undefined)
2.1406 - ? previouslyMappedValue
2.1407 - : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
2.1408 - break;
2.1409 - }
2.1410 - });
2.1411 -
2.1412 - return outputProperties;
2.1413 - }
2.1414 -
2.1415 - function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
2.1416 - if (rootObject instanceof Array) {
2.1417 - for (var i = 0; i < rootObject.length; i++)
2.1418 - visitorCallback(i);
2.1419 -
2.1420 - // For arrays, also respect toJSON property for custom mappings (fixes #278)
2.1421 - if (typeof rootObject['toJSON'] == 'function')
2.1422 - visitorCallback('toJSON');
2.1423 - } else {
2.1424 - for (var propertyName in rootObject)
2.1425 - visitorCallback(propertyName);
2.1426 - }
2.1427 - };
2.1428 -
2.1429 - function objectLookup() {
2.1430 - var keys = [];
2.1431 - var values = [];
2.1432 - this.save = function(key, value) {
2.1433 - var existingIndex = ko.utils.arrayIndexOf(keys, key);
2.1434 - if (existingIndex >= 0)
2.1435 - values[existingIndex] = value;
2.1436 - else {
2.1437 - keys.push(key);
2.1438 - values.push(value);
2.1439 - }
2.1440 - };
2.1441 - this.get = function(key) {
2.1442 - var existingIndex = ko.utils.arrayIndexOf(keys, key);
2.1443 - return (existingIndex >= 0) ? values[existingIndex] : undefined;
2.1444 - };
2.1445 - };
2.1446 -})();
2.1447 -
2.1448 -ko.exportSymbol('toJS', ko.toJS);
2.1449 -ko.exportSymbol('toJSON', ko.toJSON);
2.1450 -(function () {
2.1451 - var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
2.1452 -
2.1453 - // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
2.1454 - // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
2.1455 - // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
2.1456 - ko.selectExtensions = {
2.1457 - readValue : function(element) {
2.1458 - switch (ko.utils.tagNameLower(element)) {
2.1459 - case 'option':
2.1460 - if (element[hasDomDataExpandoProperty] === true)
2.1461 - return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
2.1462 - return ko.utils.ieVersion <= 7
2.1463 - ? (element.getAttributeNode('value').specified ? element.value : element.text)
2.1464 - : element.value;
2.1465 - case 'select':
2.1466 - return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
2.1467 - default:
2.1468 - return element.value;
2.1469 - }
2.1470 - },
2.1471 -
2.1472 - writeValue: function(element, value) {
2.1473 - switch (ko.utils.tagNameLower(element)) {
2.1474 - case 'option':
2.1475 - switch(typeof value) {
2.1476 - case "string":
2.1477 - ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
2.1478 - if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
2.1479 - delete element[hasDomDataExpandoProperty];
2.1480 - }
2.1481 - element.value = value;
2.1482 - break;
2.1483 - default:
2.1484 - // Store arbitrary object using DomData
2.1485 - ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
2.1486 - element[hasDomDataExpandoProperty] = true;
2.1487 -
2.1488 - // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
2.1489 - element.value = typeof value === "number" ? value : "";
2.1490 - break;
2.1491 - }
2.1492 - break;
2.1493 - case 'select':
2.1494 - for (var i = element.options.length - 1; i >= 0; i--) {
2.1495 - if (ko.selectExtensions.readValue(element.options[i]) == value) {
2.1496 - element.selectedIndex = i;
2.1497 - break;
2.1498 - }
2.1499 - }
2.1500 - break;
2.1501 - default:
2.1502 - if ((value === null) || (value === undefined))
2.1503 - value = "";
2.1504 - element.value = value;
2.1505 - break;
2.1506 - }
2.1507 - }
2.1508 - };
2.1509 -})();
2.1510 -
2.1511 -ko.exportSymbol('selectExtensions', ko.selectExtensions);
2.1512 -ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
2.1513 -ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
2.1514 -ko.expressionRewriting = (function () {
2.1515 - var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
2.1516 - var javaScriptReservedWords = ["true", "false"];
2.1517 -
2.1518 - // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
2.1519 - // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
2.1520 - var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
2.1521 -
2.1522 - function restoreTokens(string, tokens) {
2.1523 - var prevValue = null;
2.1524 - while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
2.1525 - prevValue = string;
2.1526 - string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
2.1527 - return tokens[tokenIndex];
2.1528 - });
2.1529 - }
2.1530 - return string;
2.1531 - }
2.1532 -
2.1533 - function getWriteableValue(expression) {
2.1534 - if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
2.1535 - return false;
2.1536 - var match = expression.match(javaScriptAssignmentTarget);
2.1537 - return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
2.1538 - }
2.1539 -
2.1540 - function ensureQuoted(key) {
2.1541 - var trimmedKey = ko.utils.stringTrim(key);
2.1542 - switch (trimmedKey.length && trimmedKey.charAt(0)) {
2.1543 - case "'":
2.1544 - case '"':
2.1545 - return key;
2.1546 - default:
2.1547 - return "'" + trimmedKey + "'";
2.1548 - }
2.1549 - }
2.1550 -
2.1551 - return {
2.1552 - bindingRewriteValidators: [],
2.1553 -
2.1554 - parseObjectLiteral: function(objectLiteralString) {
2.1555 - // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
2.1556 - // that is sufficient just to split an object literal string into a set of top-level key-value pairs
2.1557 -
2.1558 - var str = ko.utils.stringTrim(objectLiteralString);
2.1559 - if (str.length < 3)
2.1560 - return [];
2.1561 - if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
2.1562 - str = str.substring(1, str.length - 1);
2.1563 -
2.1564 - // Pull out any string literals and regex literals
2.1565 - var tokens = [];
2.1566 - var tokenStart = null, tokenEndChar;
2.1567 - for (var position = 0; position < str.length; position++) {
2.1568 - var c = str.charAt(position);
2.1569 - if (tokenStart === null) {
2.1570 - switch (c) {
2.1571 - case '"':
2.1572 - case "'":
2.1573 - case "/":
2.1574 - tokenStart = position;
2.1575 - tokenEndChar = c;
2.1576 - break;
2.1577 - }
2.1578 - } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
2.1579 - var token = str.substring(tokenStart, position + 1);
2.1580 - tokens.push(token);
2.1581 - var replacement = "@ko_token_" + (tokens.length - 1) + "@";
2.1582 - str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
2.1583 - position -= (token.length - replacement.length);
2.1584 - tokenStart = null;
2.1585 - }
2.1586 - }
2.1587 -
2.1588 - // Next pull out balanced paren, brace, and bracket blocks
2.1589 - tokenStart = null;
2.1590 - tokenEndChar = null;
2.1591 - var tokenDepth = 0, tokenStartChar = null;
2.1592 - for (var position = 0; position < str.length; position++) {
2.1593 - var c = str.charAt(position);
2.1594 - if (tokenStart === null) {
2.1595 - switch (c) {
2.1596 - case "{": tokenStart = position; tokenStartChar = c;
2.1597 - tokenEndChar = "}";
2.1598 - break;
2.1599 - case "(": tokenStart = position; tokenStartChar = c;
2.1600 - tokenEndChar = ")";
2.1601 - break;
2.1602 - case "[": tokenStart = position; tokenStartChar = c;
2.1603 - tokenEndChar = "]";
2.1604 - break;
2.1605 - }
2.1606 - }
2.1607 -
2.1608 - if (c === tokenStartChar)
2.1609 - tokenDepth++;
2.1610 - else if (c === tokenEndChar) {
2.1611 - tokenDepth--;
2.1612 - if (tokenDepth === 0) {
2.1613 - var token = str.substring(tokenStart, position + 1);
2.1614 - tokens.push(token);
2.1615 - var replacement = "@ko_token_" + (tokens.length - 1) + "@";
2.1616 - str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
2.1617 - position -= (token.length - replacement.length);
2.1618 - tokenStart = null;
2.1619 - }
2.1620 - }
2.1621 - }
2.1622 -
2.1623 - // Now we can safely split on commas to get the key/value pairs
2.1624 - var result = [];
2.1625 - var keyValuePairs = str.split(",");
2.1626 - for (var i = 0, j = keyValuePairs.length; i < j; i++) {
2.1627 - var pair = keyValuePairs[i];
2.1628 - var colonPos = pair.indexOf(":");
2.1629 - if ((colonPos > 0) && (colonPos < pair.length - 1)) {
2.1630 - var key = pair.substring(0, colonPos);
2.1631 - var value = pair.substring(colonPos + 1);
2.1632 - result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
2.1633 - } else {
2.1634 - result.push({ 'unknown': restoreTokens(pair, tokens) });
2.1635 - }
2.1636 - }
2.1637 - return result;
2.1638 - },
2.1639 -
2.1640 - preProcessBindings: function (objectLiteralStringOrKeyValueArray) {
2.1641 - var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
2.1642 - ? ko.expressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
2.1643 - : objectLiteralStringOrKeyValueArray;
2.1644 - var resultStrings = [], propertyAccessorResultStrings = [];
2.1645 -
2.1646 - var keyValueEntry;
2.1647 - for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
2.1648 - if (resultStrings.length > 0)
2.1649 - resultStrings.push(",");
2.1650 -
2.1651 - if (keyValueEntry['key']) {
2.1652 - var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
2.1653 - resultStrings.push(quotedKey);
2.1654 - resultStrings.push(":");
2.1655 - resultStrings.push(val);
2.1656 -
2.1657 - if (val = getWriteableValue(ko.utils.stringTrim(val))) {
2.1658 - if (propertyAccessorResultStrings.length > 0)
2.1659 - propertyAccessorResultStrings.push(", ");
2.1660 - propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
2.1661 - }
2.1662 - } else if (keyValueEntry['unknown']) {
2.1663 - resultStrings.push(keyValueEntry['unknown']);
2.1664 - }
2.1665 - }
2.1666 -
2.1667 - var combinedResult = resultStrings.join("");
2.1668 - if (propertyAccessorResultStrings.length > 0) {
2.1669 - var allPropertyAccessors = propertyAccessorResultStrings.join("");
2.1670 - combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
2.1671 - }
2.1672 -
2.1673 - return combinedResult;
2.1674 - },
2.1675 -
2.1676 - keyValueArrayContainsKey: function(keyValueArray, key) {
2.1677 - for (var i = 0; i < keyValueArray.length; i++)
2.1678 - if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
2.1679 - return true;
2.1680 - return false;
2.1681 - },
2.1682 -
2.1683 - // Internal, private KO utility for updating model properties from within bindings
2.1684 - // property: If the property being updated is (or might be) an observable, pass it here
2.1685 - // If it turns out to be a writable observable, it will be written to directly
2.1686 - // allBindingsAccessor: All bindings in the current execution context.
2.1687 - // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
2.1688 - // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
2.1689 - // value: The value to be written
2.1690 - // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
2.1691 - // it is !== existing value on that writable observable
2.1692 - writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
2.1693 - if (!property || !ko.isWriteableObservable(property)) {
2.1694 - var propWriters = allBindingsAccessor()['_ko_property_writers'];
2.1695 - if (propWriters && propWriters[key])
2.1696 - propWriters[key](value);
2.1697 - } else if (!checkIfDifferent || property.peek() !== value) {
2.1698 - property(value);
2.1699 - }
2.1700 - }
2.1701 - };
2.1702 -})();
2.1703 -
2.1704 -ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
2.1705 -ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
2.1706 -ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
2.1707 -ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
2.1708 -
2.1709 -// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
2.1710 -// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
2.1711 -ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
2.1712 -ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);(function() {
2.1713 - // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
2.1714 - // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
2.1715 - // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
2.1716 - // of that virtual hierarchy
2.1717 - //
2.1718 - // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
2.1719 - // without having to scatter special cases all over the binding and templating code.
2.1720 -
2.1721 - // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
2.1722 - // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
2.1723 - // So, use node.text where available, and node.nodeValue elsewhere
2.1724 - var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
2.1725 -
2.1726 - var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*-->$/ : /^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/;
2.1727 - var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
2.1728 - var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
2.1729 -
2.1730 - function isStartComment(node) {
2.1731 - return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
2.1732 - }
2.1733 -
2.1734 - function isEndComment(node) {
2.1735 - return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
2.1736 - }
2.1737 -
2.1738 - function getVirtualChildren(startComment, allowUnbalanced) {
2.1739 - var currentNode = startComment;
2.1740 - var depth = 1;
2.1741 - var children = [];
2.1742 - while (currentNode = currentNode.nextSibling) {
2.1743 - if (isEndComment(currentNode)) {
2.1744 - depth--;
2.1745 - if (depth === 0)
2.1746 - return children;
2.1747 - }
2.1748 -
2.1749 - children.push(currentNode);
2.1750 -
2.1751 - if (isStartComment(currentNode))
2.1752 - depth++;
2.1753 - }
2.1754 - if (!allowUnbalanced)
2.1755 - throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
2.1756 - return null;
2.1757 - }
2.1758 -
2.1759 - function getMatchingEndComment(startComment, allowUnbalanced) {
2.1760 - var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
2.1761 - if (allVirtualChildren) {
2.1762 - if (allVirtualChildren.length > 0)
2.1763 - return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
2.1764 - return startComment.nextSibling;
2.1765 - } else
2.1766 - return null; // Must have no matching end comment, and allowUnbalanced is true
2.1767 - }
2.1768 -
2.1769 - function getUnbalancedChildTags(node) {
2.1770 - // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
2.1771 - // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
2.1772 - var childNode = node.firstChild, captureRemaining = null;
2.1773 - if (childNode) {
2.1774 - do {
2.1775 - if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
2.1776 - captureRemaining.push(childNode);
2.1777 - else if (isStartComment(childNode)) {
2.1778 - var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
2.1779 - if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
2.1780 - childNode = matchingEndComment;
2.1781 - else
2.1782 - captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
2.1783 - } else if (isEndComment(childNode)) {
2.1784 - captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
2.1785 - }
2.1786 - } while (childNode = childNode.nextSibling);
2.1787 - }
2.1788 - return captureRemaining;
2.1789 - }
2.1790 -
2.1791 - ko.virtualElements = {
2.1792 - allowedBindings: {},
2.1793 -
2.1794 - childNodes: function(node) {
2.1795 - return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
2.1796 - },
2.1797 -
2.1798 - emptyNode: function(node) {
2.1799 - if (!isStartComment(node))
2.1800 - ko.utils.emptyDomNode(node);
2.1801 - else {
2.1802 - var virtualChildren = ko.virtualElements.childNodes(node);
2.1803 - for (var i = 0, j = virtualChildren.length; i < j; i++)
2.1804 - ko.removeNode(virtualChildren[i]);
2.1805 - }
2.1806 - },
2.1807 -
2.1808 - setDomNodeChildren: function(node, childNodes) {
2.1809 - if (!isStartComment(node))
2.1810 - ko.utils.setDomNodeChildren(node, childNodes);
2.1811 - else {
2.1812 - ko.virtualElements.emptyNode(node);
2.1813 - var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
2.1814 - for (var i = 0, j = childNodes.length; i < j; i++)
2.1815 - endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
2.1816 - }
2.1817 - },
2.1818 -
2.1819 - prepend: function(containerNode, nodeToPrepend) {
2.1820 - if (!isStartComment(containerNode)) {
2.1821 - if (containerNode.firstChild)
2.1822 - containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
2.1823 - else
2.1824 - containerNode.appendChild(nodeToPrepend);
2.1825 - } else {
2.1826 - // Start comments must always have a parent and at least one following sibling (the end comment)
2.1827 - containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
2.1828 - }
2.1829 - },
2.1830 -
2.1831 - insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
2.1832 - if (!insertAfterNode) {
2.1833 - ko.virtualElements.prepend(containerNode, nodeToInsert);
2.1834 - } else if (!isStartComment(containerNode)) {
2.1835 - // Insert after insertion point
2.1836 - if (insertAfterNode.nextSibling)
2.1837 - containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
2.1838 - else
2.1839 - containerNode.appendChild(nodeToInsert);
2.1840 - } else {
2.1841 - // Children of start comments must always have a parent and at least one following sibling (the end comment)
2.1842 - containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
2.1843 - }
2.1844 - },
2.1845 -
2.1846 - firstChild: function(node) {
2.1847 - if (!isStartComment(node))
2.1848 - return node.firstChild;
2.1849 - if (!node.nextSibling || isEndComment(node.nextSibling))
2.1850 - return null;
2.1851 - return node.nextSibling;
2.1852 - },
2.1853 -
2.1854 - nextSibling: function(node) {
2.1855 - if (isStartComment(node))
2.1856 - node = getMatchingEndComment(node);
2.1857 - if (node.nextSibling && isEndComment(node.nextSibling))
2.1858 - return null;
2.1859 - return node.nextSibling;
2.1860 - },
2.1861 -
2.1862 - virtualNodeBindingValue: function(node) {
2.1863 - var regexMatch = isStartComment(node);
2.1864 - return regexMatch ? regexMatch[1] : null;
2.1865 - },
2.1866 -
2.1867 - normaliseVirtualElementDomStructure: function(elementVerified) {
2.1868 - // Workaround for https://github.com/SteveSanderson/knockout/issues/155
2.1869 - // (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.1870 - // that are direct descendants of <ul> into the preceding <li>)
2.1871 - if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
2.1872 - return;
2.1873 -
2.1874 - // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
2.1875 - // must be intended to appear *after* that child, so move them there.
2.1876 - var childNode = elementVerified.firstChild;
2.1877 - if (childNode) {
2.1878 - do {
2.1879 - if (childNode.nodeType === 1) {
2.1880 - var unbalancedTags = getUnbalancedChildTags(childNode);
2.1881 - if (unbalancedTags) {
2.1882 - // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
2.1883 - var nodeToInsertBefore = childNode.nextSibling;
2.1884 - for (var i = 0; i < unbalancedTags.length; i++) {
2.1885 - if (nodeToInsertBefore)
2.1886 - elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
2.1887 - else
2.1888 - elementVerified.appendChild(unbalancedTags[i]);
2.1889 - }
2.1890 - }
2.1891 - }
2.1892 - } while (childNode = childNode.nextSibling);
2.1893 - }
2.1894 - }
2.1895 - };
2.1896 -})();
2.1897 -ko.exportSymbol('virtualElements', ko.virtualElements);
2.1898 -ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
2.1899 -ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
2.1900 -//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
2.1901 -ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
2.1902 -//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
2.1903 -ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
2.1904 -ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
2.1905 -(function() {
2.1906 - var defaultBindingAttributeName = "data-bind";
2.1907 -
2.1908 - ko.bindingProvider = function() {
2.1909 - this.bindingCache = {};
2.1910 - };
2.1911 -
2.1912 - ko.utils.extend(ko.bindingProvider.prototype, {
2.1913 - 'nodeHasBindings': function(node) {
2.1914 - switch (node.nodeType) {
2.1915 - case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
2.1916 - case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
2.1917 - default: return false;
2.1918 - }
2.1919 - },
2.1920 -
2.1921 - 'getBindings': function(node, bindingContext) {
2.1922 - var bindingsString = this['getBindingsString'](node, bindingContext);
2.1923 - return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
2.1924 - },
2.1925 -
2.1926 - // The following function is only used internally by this default provider.
2.1927 - // It's not part of the interface definition for a general binding provider.
2.1928 - 'getBindingsString': function(node, bindingContext) {
2.1929 - switch (node.nodeType) {
2.1930 - case 1: return node.getAttribute(defaultBindingAttributeName); // Element
2.1931 - case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
2.1932 - default: return null;
2.1933 - }
2.1934 - },
2.1935 -
2.1936 - // The following function is only used internally by this default provider.
2.1937 - // It's not part of the interface definition for a general binding provider.
2.1938 - 'parseBindingsString': function(bindingsString, bindingContext, node) {
2.1939 - try {
2.1940 - var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
2.1941 - return bindingFunction(bindingContext, node);
2.1942 - } catch (ex) {
2.1943 - throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
2.1944 - }
2.1945 - }
2.1946 - });
2.1947 -
2.1948 - ko.bindingProvider['instance'] = new ko.bindingProvider();
2.1949 -
2.1950 - function createBindingsStringEvaluatorViaCache(bindingsString, cache) {
2.1951 - var cacheKey = bindingsString;
2.1952 - return cache[cacheKey]
2.1953 - || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString));
2.1954 - }
2.1955 -
2.1956 - function createBindingsStringEvaluator(bindingsString) {
2.1957 - // Build the source for a function that evaluates "expression"
2.1958 - // For each scope variable, add an extra level of "with" nesting
2.1959 - // Example result: with(sc1) { with(sc0) { return (expression) } }
2.1960 - var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString),
2.1961 - functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
2.1962 - return new Function("$context", "$element", functionBody);
2.1963 - }
2.1964 -})();
2.1965 -
2.1966 -ko.exportSymbol('bindingProvider', ko.bindingProvider);
2.1967 -(function () {
2.1968 - ko.bindingHandlers = {};
2.1969 -
2.1970 - ko.bindingContext = function(dataItem, parentBindingContext, dataItemAlias) {
2.1971 - if (parentBindingContext) {
2.1972 - ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
2.1973 - this['$parentContext'] = parentBindingContext;
2.1974 - this['$parent'] = parentBindingContext['$data'];
2.1975 - this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
2.1976 - this['$parents'].unshift(this['$parent']);
2.1977 - } else {
2.1978 - this['$parents'] = [];
2.1979 - this['$root'] = dataItem;
2.1980 - // Export 'ko' in the binding context so it will be available in bindings and templates
2.1981 - // even if 'ko' isn't exported as a global, such as when using an AMD loader.
2.1982 - // See https://github.com/SteveSanderson/knockout/issues/490
2.1983 - this['ko'] = ko;
2.1984 - }
2.1985 - this['$data'] = dataItem;
2.1986 - if (dataItemAlias)
2.1987 - this[dataItemAlias] = dataItem;
2.1988 - }
2.1989 - ko.bindingContext.prototype['createChildContext'] = function (dataItem, dataItemAlias) {
2.1990 - return new ko.bindingContext(dataItem, this, dataItemAlias);
2.1991 - };
2.1992 - ko.bindingContext.prototype['extend'] = function(properties) {
2.1993 - var clone = ko.utils.extend(new ko.bindingContext(), this);
2.1994 - return ko.utils.extend(clone, properties);
2.1995 - };
2.1996 -
2.1997 - function validateThatBindingIsAllowedForVirtualElements(bindingName) {
2.1998 - var validator = ko.virtualElements.allowedBindings[bindingName];
2.1999 - if (!validator)
2.2000 - throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
2.2001 - }
2.2002 -
2.2003 - function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
2.2004 - var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
2.2005 - while (currentChild = nextInQueue) {
2.2006 - // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
2.2007 - nextInQueue = ko.virtualElements.nextSibling(currentChild);
2.2008 - applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
2.2009 - }
2.2010 - }
2.2011 -
2.2012 - function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
2.2013 - var shouldBindDescendants = true;
2.2014 -
2.2015 - // Perf optimisation: Apply bindings only if...
2.2016 - // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
2.2017 - // 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.2018 - // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
2.2019 - var isElement = (nodeVerified.nodeType === 1);
2.2020 - if (isElement) // Workaround IE <= 8 HTML parsing weirdness
2.2021 - ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
2.2022 -
2.2023 - var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
2.2024 - || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
2.2025 - if (shouldApplyBindings)
2.2026 - shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
2.2027 -
2.2028 - if (shouldBindDescendants) {
2.2029 - // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
2.2030 - // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
2.2031 - // hence bindingContextsMayDifferFromDomParentElement is false
2.2032 - // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
2.2033 - // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
2.2034 - // hence bindingContextsMayDifferFromDomParentElement is true
2.2035 - applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
2.2036 - }
2.2037 - }
2.2038 -
2.2039 - function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
2.2040 - // Need to be sure that inits are only run once, and updates never run until all the inits have been run
2.2041 - var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
2.2042 -
2.2043 - // Each time the dependentObservable is evaluated (after data changes),
2.2044 - // the binding attribute is reparsed so that it can pick out the correct
2.2045 - // model properties in the context of the changed data.
2.2046 - // DOM event callbacks need to be able to access this changed data,
2.2047 - // so we need a single parsedBindings variable (shared by all callbacks
2.2048 - // associated with this node's bindings) that all the closures can access.
2.2049 - var parsedBindings;
2.2050 - function makeValueAccessor(bindingKey) {
2.2051 - return function () { return parsedBindings[bindingKey] }
2.2052 - }
2.2053 - function parsedBindingsAccessor() {
2.2054 - return parsedBindings;
2.2055 - }
2.2056 -
2.2057 - var bindingHandlerThatControlsDescendantBindings;
2.2058 - ko.dependentObservable(
2.2059 - function () {
2.2060 - // Ensure we have a nonnull binding context to work with
2.2061 - var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
2.2062 - ? viewModelOrBindingContext
2.2063 - : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
2.2064 - var viewModel = bindingContextInstance['$data'];
2.2065 -
2.2066 - // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
2.2067 - // we can easily recover it just by scanning up the node's ancestors in the DOM
2.2068 - // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
2.2069 - if (bindingContextMayDifferFromDomParentElement)
2.2070 - ko.storedBindingContextForNode(node, bindingContextInstance);
2.2071 -
2.2072 - // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
2.2073 - var evaluatedBindings = (typeof bindings == "function") ? bindings(bindingContextInstance, node) : bindings;
2.2074 - parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
2.2075 -
2.2076 - if (parsedBindings) {
2.2077 - // First run all the inits, so bindings can register for notification on changes
2.2078 - if (initPhase === 0) {
2.2079 - initPhase = 1;
2.2080 - for (var bindingKey in parsedBindings) {
2.2081 - var binding = ko.bindingHandlers[bindingKey];
2.2082 - if (binding && node.nodeType === 8)
2.2083 - validateThatBindingIsAllowedForVirtualElements(bindingKey);
2.2084 -
2.2085 - if (binding && typeof binding["init"] == "function") {
2.2086 - var handlerInitFn = binding["init"];
2.2087 - var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
2.2088 -
2.2089 - // If this binding handler claims to control descendant bindings, make a note of this
2.2090 - if (initResult && initResult['controlsDescendantBindings']) {
2.2091 - if (bindingHandlerThatControlsDescendantBindings !== undefined)
2.2092 - 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.2093 - bindingHandlerThatControlsDescendantBindings = bindingKey;
2.2094 - }
2.2095 - }
2.2096 - }
2.2097 - initPhase = 2;
2.2098 - }
2.2099 -
2.2100 - // ... then run all the updates, which might trigger changes even on the first evaluation
2.2101 - if (initPhase === 2) {
2.2102 - for (var bindingKey in parsedBindings) {
2.2103 - var binding = ko.bindingHandlers[bindingKey];
2.2104 - if (binding && typeof binding["update"] == "function") {
2.2105 - var handlerUpdateFn = binding["update"];
2.2106 - handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
2.2107 - }
2.2108 - }
2.2109 - }
2.2110 - }
2.2111 - },
2.2112 - null,
2.2113 - { disposeWhenNodeIsRemoved : node }
2.2114 - );
2.2115 -
2.2116 - return {
2.2117 - shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
2.2118 - };
2.2119 - };
2.2120 -
2.2121 - var storedBindingContextDomDataKey = "__ko_bindingContext__";
2.2122 - ko.storedBindingContextForNode = function (node, bindingContext) {
2.2123 - if (arguments.length == 2)
2.2124 - ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
2.2125 - else
2.2126 - return ko.utils.domData.get(node, storedBindingContextDomDataKey);
2.2127 - }
2.2128 -
2.2129 - ko.applyBindingsToNode = function (node, bindings, viewModel) {
2.2130 - if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
2.2131 - ko.virtualElements.normaliseVirtualElementDomStructure(node);
2.2132 - return applyBindingsToNodeInternal(node, bindings, viewModel, true);
2.2133 - };
2.2134 -
2.2135 - ko.applyBindingsToDescendants = function(viewModel, rootNode) {
2.2136 - if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
2.2137 - applyBindingsToDescendantsInternal(viewModel, rootNode, true);
2.2138 - };
2.2139 -
2.2140 - ko.applyBindings = function (viewModel, rootNode) {
2.2141 - if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
2.2142 - throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
2.2143 - rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
2.2144 -
2.2145 - applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
2.2146 - };
2.2147 -
2.2148 - // Retrieving binding context from arbitrary nodes
2.2149 - ko.contextFor = function(node) {
2.2150 - // 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.2151 - switch (node.nodeType) {
2.2152 - case 1:
2.2153 - case 8:
2.2154 - var context = ko.storedBindingContextForNode(node);
2.2155 - if (context) return context;
2.2156 - if (node.parentNode) return ko.contextFor(node.parentNode);
2.2157 - break;
2.2158 - }
2.2159 - return undefined;
2.2160 - };
2.2161 - ko.dataFor = function(node) {
2.2162 - var context = ko.contextFor(node);
2.2163 - return context ? context['$data'] : undefined;
2.2164 - };
2.2165 -
2.2166 - ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
2.2167 - ko.exportSymbol('applyBindings', ko.applyBindings);
2.2168 - ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
2.2169 - ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
2.2170 - ko.exportSymbol('contextFor', ko.contextFor);
2.2171 - ko.exportSymbol('dataFor', ko.dataFor);
2.2172 -})();
2.2173 -var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
2.2174 -ko.bindingHandlers['attr'] = {
2.2175 - 'update': function(element, valueAccessor, allBindingsAccessor) {
2.2176 - var value = ko.utils.unwrapObservable(valueAccessor()) || {};
2.2177 - for (var attrName in value) {
2.2178 - if (typeof attrName == "string") {
2.2179 - var attrValue = ko.utils.unwrapObservable(value[attrName]);
2.2180 -
2.2181 - // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
2.2182 - // when someProp is a "no value"-like value (strictly null, false, or undefined)
2.2183 - // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
2.2184 - var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
2.2185 - if (toRemove)
2.2186 - element.removeAttribute(attrName);
2.2187 -
2.2188 - // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
2.2189 - // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
2.2190 - // but instead of figuring out the mode, we'll just set the attribute through the Javascript
2.2191 - // property for IE <= 8.
2.2192 - if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
2.2193 - attrName = attrHtmlToJavascriptMap[attrName];
2.2194 - if (toRemove)
2.2195 - element.removeAttribute(attrName);
2.2196 - else
2.2197 - element[attrName] = attrValue;
2.2198 - } else if (!toRemove) {
2.2199 - try {
2.2200 - element.setAttribute(attrName, attrValue.toString());
2.2201 - } catch (err) {
2.2202 - // ignore for now
2.2203 - if (console) {
2.2204 - console.log("Can't set attribute " + attrName + " to " + attrValue + " error: " + err);
2.2205 - }
2.2206 - }
2.2207 - }
2.2208 -
2.2209 - // Treat "name" specially - although you can think of it as an attribute, it also needs
2.2210 - // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
2.2211 - // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
2.2212 - // entirely, and there's no strong reason to allow for such casing in HTML.
2.2213 - if (attrName === "name") {
2.2214 - ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
2.2215 - }
2.2216 - }
2.2217 - }
2.2218 - }
2.2219 -};
2.2220 -ko.bindingHandlers['checked'] = {
2.2221 - 'init': function (element, valueAccessor, allBindingsAccessor) {
2.2222 - var updateHandler = function() {
2.2223 - var valueToWrite;
2.2224 - if (element.type == "checkbox") {
2.2225 - valueToWrite = element.checked;
2.2226 - } else if ((element.type == "radio") && (element.checked)) {
2.2227 - valueToWrite = element.value;
2.2228 - } else {
2.2229 - return; // "checked" binding only responds to checkboxes and selected radio buttons
2.2230 - }
2.2231 -
2.2232 - var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
2.2233 - if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
2.2234 - // For checkboxes bound to an array, we add/remove the checkbox value to that array
2.2235 - // This works for both observable and non-observable arrays
2.2236 - var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
2.2237 - if (element.checked && (existingEntryIndex < 0))
2.2238 - modelValue.push(element.value);
2.2239 - else if ((!element.checked) && (existingEntryIndex >= 0))
2.2240 - modelValue.splice(existingEntryIndex, 1);
2.2241 - } else {
2.2242 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
2.2243 - }
2.2244 - };
2.2245 - ko.utils.registerEventHandler(element, "click", updateHandler);
2.2246 -
2.2247 - // IE 6 won't allow radio buttons to be selected unless they have a name
2.2248 - if ((element.type == "radio") && !element.name)
2.2249 - ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
2.2250 - },
2.2251 - 'update': function (element, valueAccessor) {
2.2252 - var value = ko.utils.unwrapObservable(valueAccessor());
2.2253 -
2.2254 - if (element.type == "checkbox") {
2.2255 - if (value instanceof Array) {
2.2256 - // When bound to an array, the checkbox being checked represents its value being present in that array
2.2257 - element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
2.2258 - } else {
2.2259 - // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
2.2260 - element.checked = value;
2.2261 - }
2.2262 - } else if (element.type == "radio") {
2.2263 - element.checked = (element.value == value);
2.2264 - }
2.2265 - }
2.2266 -};
2.2267 -var classesWrittenByBindingKey = '__ko__cssValue';
2.2268 -ko.bindingHandlers['css'] = {
2.2269 - 'update': function (element, valueAccessor) {
2.2270 - var value = ko.utils.unwrapObservable(valueAccessor());
2.2271 - if (typeof value == "object") {
2.2272 - for (var className in value) {
2.2273 - var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
2.2274 - ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
2.2275 - }
2.2276 - } else {
2.2277 - value = String(value || ''); // Make sure we don't try to store or set a non-string value
2.2278 - ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
2.2279 - element[classesWrittenByBindingKey] = value;
2.2280 - ko.utils.toggleDomNodeCssClass(element, value, true);
2.2281 - }
2.2282 - }
2.2283 -};
2.2284 -ko.bindingHandlers['enable'] = {
2.2285 - 'update': function (element, valueAccessor) {
2.2286 - var value = ko.utils.unwrapObservable(valueAccessor());
2.2287 - if (value && element.disabled)
2.2288 - element.removeAttribute("disabled");
2.2289 - else if ((!value) && (!element.disabled))
2.2290 - element.disabled = true;
2.2291 - }
2.2292 -};
2.2293 -
2.2294 -ko.bindingHandlers['disable'] = {
2.2295 - 'update': function (element, valueAccessor) {
2.2296 - ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
2.2297 - }
2.2298 -};
2.2299 -// For certain common events (currently just 'click'), allow a simplified data-binding syntax
2.2300 -// e.g. click:handler instead of the usual full-length event:{click:handler}
2.2301 -function makeEventHandlerShortcut(eventName) {
2.2302 - ko.bindingHandlers[eventName] = {
2.2303 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
2.2304 - var newValueAccessor = function () {
2.2305 - var result = {};
2.2306 - result[eventName] = valueAccessor();
2.2307 - return result;
2.2308 - };
2.2309 - return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
2.2310 - }
2.2311 - }
2.2312 -}
2.2313 -
2.2314 -ko.bindingHandlers['event'] = {
2.2315 - 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
2.2316 - var eventsToHandle = valueAccessor() || {};
2.2317 - for(var eventNameOutsideClosure in eventsToHandle) {
2.2318 - (function() {
2.2319 - var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
2.2320 - if (typeof eventName == "string") {
2.2321 - ko.utils.registerEventHandler(element, eventName, function (event) {
2.2322 - var handlerReturnValue;
2.2323 - var handlerFunction = valueAccessor()[eventName];
2.2324 - if (!handlerFunction)
2.2325 - return;
2.2326 - var allBindings = allBindingsAccessor();
2.2327 -
2.2328 - try {
2.2329 - // Take all the event args, and prefix with the viewmodel
2.2330 - var argsForHandler = ko.utils.makeArray(arguments);
2.2331 - argsForHandler.unshift(viewModel);
2.2332 - handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
2.2333 - } finally {
2.2334 - if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
2.2335 - if (event.preventDefault)
2.2336 - event.preventDefault();
2.2337 - else
2.2338 - event.returnValue = false;
2.2339 - }
2.2340 - }
2.2341 -
2.2342 - var bubble = allBindings[eventName + 'Bubble'] !== false;
2.2343 - if (!bubble) {
2.2344 - event.cancelBubble = true;
2.2345 - if (event.stopPropagation)
2.2346 - event.stopPropagation();
2.2347 - }
2.2348 - });
2.2349 - }
2.2350 - })();
2.2351 - }
2.2352 - }
2.2353 -};
2.2354 -// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
2.2355 -// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
2.2356 -ko.bindingHandlers['foreach'] = {
2.2357 - makeTemplateValueAccessor: function(valueAccessor) {
2.2358 - return function() {
2.2359 - var modelValue = valueAccessor(),
2.2360 - unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
2.2361 -
2.2362 - // If unwrappedValue is the array, pass in the wrapped value on its own
2.2363 - // The value will be unwrapped and tracked within the template binding
2.2364 - // (See https://github.com/SteveSanderson/knockout/issues/523)
2.2365 - if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
2.2366 - return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
2.2367 -
2.2368 - // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
2.2369 - ko.utils.unwrapObservable(modelValue);
2.2370 - return {
2.2371 - 'foreach': unwrappedValue['data'],
2.2372 - 'as': unwrappedValue['as'],
2.2373 - 'includeDestroyed': unwrappedValue['includeDestroyed'],
2.2374 - 'afterAdd': unwrappedValue['afterAdd'],
2.2375 - 'beforeRemove': unwrappedValue['beforeRemove'],
2.2376 - 'afterRender': unwrappedValue['afterRender'],
2.2377 - 'beforeMove': unwrappedValue['beforeMove'],
2.2378 - 'afterMove': unwrappedValue['afterMove'],
2.2379 - 'templateEngine': ko.nativeTemplateEngine.instance
2.2380 - };
2.2381 - };
2.2382 - },
2.2383 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.2384 - return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
2.2385 - },
2.2386 - 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.2387 - return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
2.2388 - }
2.2389 -};
2.2390 -ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
2.2391 -ko.virtualElements.allowedBindings['foreach'] = true;
2.2392 -var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
2.2393 -ko.bindingHandlers['hasfocus'] = {
2.2394 - 'init': function(element, valueAccessor, allBindingsAccessor) {
2.2395 - var handleElementFocusChange = function(isFocused) {
2.2396 - // Where possible, ignore which event was raised and determine focus state using activeElement,
2.2397 - // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
2.2398 - // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
2.2399 - // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
2.2400 - // from calling 'blur()' on the element when it loses focus.
2.2401 - // Discussion at https://github.com/SteveSanderson/knockout/pull/352
2.2402 - element[hasfocusUpdatingProperty] = true;
2.2403 - var ownerDoc = element.ownerDocument;
2.2404 - if ("activeElement" in ownerDoc) {
2.2405 - isFocused = (ownerDoc.activeElement === element);
2.2406 - }
2.2407 - var modelValue = valueAccessor();
2.2408 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true);
2.2409 - element[hasfocusUpdatingProperty] = false;
2.2410 - };
2.2411 - var handleElementFocusIn = handleElementFocusChange.bind(null, true);
2.2412 - var handleElementFocusOut = handleElementFocusChange.bind(null, false);
2.2413 -
2.2414 - ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
2.2415 - ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
2.2416 - ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
2.2417 - ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
2.2418 - },
2.2419 - 'update': function(element, valueAccessor) {
2.2420 - var value = ko.utils.unwrapObservable(valueAccessor());
2.2421 - if (!element[hasfocusUpdatingProperty]) {
2.2422 - value ? element.focus() : element.blur();
2.2423 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
2.2424 - }
2.2425 - }
2.2426 -};
2.2427 -ko.bindingHandlers['html'] = {
2.2428 - 'init': function() {
2.2429 - // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
2.2430 - return { 'controlsDescendantBindings': true };
2.2431 - },
2.2432 - 'update': function (element, valueAccessor) {
2.2433 - // setHtml will unwrap the value if needed
2.2434 - ko.utils.setHtml(element, valueAccessor());
2.2435 - }
2.2436 -};
2.2437 -var withIfDomDataKey = '__ko_withIfBindingData';
2.2438 -// Makes a binding like with or if
2.2439 -function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
2.2440 - ko.bindingHandlers[bindingKey] = {
2.2441 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.2442 - ko.utils.domData.set(element, withIfDomDataKey, {});
2.2443 - return { 'controlsDescendantBindings': true };
2.2444 - },
2.2445 - 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.2446 - var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
2.2447 - dataValue = ko.utils.unwrapObservable(valueAccessor()),
2.2448 - shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
2.2449 - isFirstRender = !withIfData.savedNodes,
2.2450 - needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
2.2451 -
2.2452 - if (needsRefresh) {
2.2453 - if (isFirstRender) {
2.2454 - withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
2.2455 - }
2.2456 -
2.2457 - if (shouldDisplay) {
2.2458 - if (!isFirstRender) {
2.2459 - ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
2.2460 - }
2.2461 - ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
2.2462 - } else {
2.2463 - ko.virtualElements.emptyNode(element);
2.2464 - }
2.2465 -
2.2466 - withIfData.didDisplayOnLastUpdate = shouldDisplay;
2.2467 - }
2.2468 - }
2.2469 - };
2.2470 - ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
2.2471 - ko.virtualElements.allowedBindings[bindingKey] = true;
2.2472 -}
2.2473 -
2.2474 -// Construct the actual binding handlers
2.2475 -makeWithIfBinding('if');
2.2476 -makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
2.2477 -makeWithIfBinding('with', true /* isWith */, false /* isNot */,
2.2478 - function(bindingContext, dataValue) {
2.2479 - return bindingContext['createChildContext'](dataValue);
2.2480 - }
2.2481 -);
2.2482 -function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
2.2483 - if (preferModelValue) {
2.2484 - if (modelValue !== ko.selectExtensions.readValue(element))
2.2485 - ko.selectExtensions.writeValue(element, modelValue);
2.2486 - }
2.2487 -
2.2488 - // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
2.2489 - // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
2.2490 - // change the model value to match the dropdown.
2.2491 - if (modelValue !== ko.selectExtensions.readValue(element))
2.2492 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
2.2493 -};
2.2494 -
2.2495 -ko.bindingHandlers['options'] = {
2.2496 - 'update': function (element, valueAccessor, allBindingsAccessor) {
2.2497 - if (ko.utils.tagNameLower(element) !== "select")
2.2498 - throw new Error("options binding applies only to SELECT elements");
2.2499 -
2.2500 - var selectWasPreviouslyEmpty = element.length == 0;
2.2501 - var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
2.2502 - return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
2.2503 - }), function (node) {
2.2504 - return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
2.2505 - });
2.2506 - var previousScrollTop = element.scrollTop;
2.2507 -
2.2508 - var value = ko.utils.unwrapObservable(valueAccessor());
2.2509 - var selectedValue = element.value;
2.2510 -
2.2511 - // Remove all existing <option>s.
2.2512 - // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
2.2513 - while (element.length > 0) {
2.2514 - ko.cleanNode(element.options[0]);
2.2515 - element.remove(0);
2.2516 - }
2.2517 -
2.2518 - if (value) {
2.2519 - var allBindings = allBindingsAccessor(),
2.2520 - includeDestroyed = allBindings['optionsIncludeDestroyed'];
2.2521 -
2.2522 - if (typeof value.length != "number")
2.2523 - value = [value];
2.2524 - if (allBindings['optionsCaption']) {
2.2525 - var option = document.createElement("option");
2.2526 - ko.utils.setHtml(option, allBindings['optionsCaption']);
2.2527 - ko.selectExtensions.writeValue(option, undefined);
2.2528 - element.appendChild(option);
2.2529 - }
2.2530 -
2.2531 - for (var i = 0, j = value.length; i < j; i++) {
2.2532 - // Skip destroyed items
2.2533 - var arrayEntry = value[i];
2.2534 - if (arrayEntry && arrayEntry['_destroy'] && !includeDestroyed)
2.2535 - continue;
2.2536 -
2.2537 - var option = document.createElement("option");
2.2538 -
2.2539 - function applyToObject(object, predicate, defaultValue) {
2.2540 - var predicateType = typeof predicate;
2.2541 - if (predicateType == "function") // Given a function; run it against the data value
2.2542 - return predicate(object);
2.2543 - else if (predicateType == "string") // Given a string; treat it as a property name on the data value
2.2544 - return object[predicate];
2.2545 - else // Given no optionsText arg; use the data value itself
2.2546 - return defaultValue;
2.2547 - }
2.2548 -
2.2549 - // Apply a value to the option element
2.2550 - var optionValue = applyToObject(arrayEntry, allBindings['optionsValue'], arrayEntry);
2.2551 - ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
2.2552 -
2.2553 - // Apply some text to the option element
2.2554 - var optionText = applyToObject(arrayEntry, allBindings['optionsText'], optionValue);
2.2555 - ko.utils.setTextContent(option, optionText);
2.2556 -
2.2557 - element.appendChild(option);
2.2558 - }
2.2559 -
2.2560 - // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
2.2561 - // That's why we first added them without selection. Now it's time to set the selection.
2.2562 - var newOptions = element.getElementsByTagName("option");
2.2563 - var countSelectionsRetained = 0;
2.2564 - for (var i = 0, j = newOptions.length; i < j; i++) {
2.2565 - if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
2.2566 - ko.utils.setOptionNodeSelectionState(newOptions[i], true);
2.2567 - countSelectionsRetained++;
2.2568 - }
2.2569 - }
2.2570 -
2.2571 - element.scrollTop = previousScrollTop;
2.2572 -
2.2573 - if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
2.2574 - // Ensure consistency between model value and selected option.
2.2575 - // If the dropdown is being populated for the first time here (or was otherwise previously empty),
2.2576 - // the dropdown selection state is meaningless, so we preserve the model value.
2.2577 - ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.peekObservable(allBindings['value']), /* preferModelValue */ true);
2.2578 - }
2.2579 -
2.2580 - // Workaround for IE9 bug
2.2581 - ko.utils.ensureSelectElementIsRenderedCorrectly(element);
2.2582 - }
2.2583 - }
2.2584 -};
2.2585 -ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
2.2586 -ko.bindingHandlers['selectedOptions'] = {
2.2587 - 'init': function (element, valueAccessor, allBindingsAccessor) {
2.2588 - ko.utils.registerEventHandler(element, "change", function () {
2.2589 - var value = valueAccessor(), valueToWrite = [];
2.2590 - ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
2.2591 - if (node.selected)
2.2592 - valueToWrite.push(ko.selectExtensions.readValue(node));
2.2593 - });
2.2594 - ko.expressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
2.2595 - });
2.2596 - },
2.2597 - 'update': function (element, valueAccessor) {
2.2598 - if (ko.utils.tagNameLower(element) != "select")
2.2599 - throw new Error("values binding applies only to SELECT elements");
2.2600 -
2.2601 - var newValue = ko.utils.unwrapObservable(valueAccessor());
2.2602 - if (newValue && typeof newValue.length == "number") {
2.2603 - ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
2.2604 - var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
2.2605 - ko.utils.setOptionNodeSelectionState(node, isSelected);
2.2606 - });
2.2607 - }
2.2608 - }
2.2609 -};
2.2610 -ko.bindingHandlers['style'] = {
2.2611 - 'update': function (element, valueAccessor) {
2.2612 - var value = ko.utils.unwrapObservable(valueAccessor() || {});
2.2613 - for (var styleName in value) {
2.2614 - if (typeof styleName == "string") {
2.2615 - var styleValue = ko.utils.unwrapObservable(value[styleName]);
2.2616 - element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
2.2617 - }
2.2618 - }
2.2619 - }
2.2620 -};
2.2621 -ko.bindingHandlers['submit'] = {
2.2622 - 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
2.2623 - if (typeof valueAccessor() != "function")
2.2624 - throw new Error("The value for a submit binding must be a function");
2.2625 - ko.utils.registerEventHandler(element, "submit", function (event) {
2.2626 - var handlerReturnValue;
2.2627 - var value = valueAccessor();
2.2628 - try { handlerReturnValue = value.call(viewModel, element); }
2.2629 - finally {
2.2630 - if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
2.2631 - if (event.preventDefault)
2.2632 - event.preventDefault();
2.2633 - else
2.2634 - event.returnValue = false;
2.2635 - }
2.2636 - }
2.2637 - });
2.2638 - }
2.2639 -};
2.2640 -ko.bindingHandlers['text'] = {
2.2641 - 'update': function (element, valueAccessor) {
2.2642 - ko.utils.setTextContent(element, valueAccessor());
2.2643 - }
2.2644 -};
2.2645 -ko.virtualElements.allowedBindings['text'] = true;
2.2646 -ko.bindingHandlers['uniqueName'] = {
2.2647 - 'init': function (element, valueAccessor) {
2.2648 - if (valueAccessor()) {
2.2649 - var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
2.2650 - ko.utils.setElementName(element, name);
2.2651 - }
2.2652 - }
2.2653 -};
2.2654 -ko.bindingHandlers['uniqueName'].currentIndex = 0;
2.2655 -ko.bindingHandlers['value'] = {
2.2656 - 'init': function (element, valueAccessor, allBindingsAccessor) {
2.2657 - // Always catch "change" event; possibly other events too if asked
2.2658 - var eventsToCatch = ["change"];
2.2659 - var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
2.2660 - var propertyChangedFired = false;
2.2661 - if (requestedEventsToCatch) {
2.2662 - if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
2.2663 - requestedEventsToCatch = [requestedEventsToCatch];
2.2664 - ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
2.2665 - eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
2.2666 - }
2.2667 -
2.2668 - var valueUpdateHandler = function() {
2.2669 - propertyChangedFired = false;
2.2670 - var modelValue = valueAccessor();
2.2671 - var elementValue = ko.selectExtensions.readValue(element);
2.2672 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
2.2673 - }
2.2674 -
2.2675 - // Workaround for https://github.com/SteveSanderson/knockout/issues/122
2.2676 - // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
2.2677 - var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
2.2678 - && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
2.2679 - if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
2.2680 - ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
2.2681 - ko.utils.registerEventHandler(element, "blur", function() {
2.2682 - if (propertyChangedFired) {
2.2683 - valueUpdateHandler();
2.2684 - }
2.2685 - });
2.2686 - }
2.2687 -
2.2688 - ko.utils.arrayForEach(eventsToCatch, function(eventName) {
2.2689 - // The syntax "after<eventname>" means "run the handler asynchronously after the event"
2.2690 - // This is useful, for example, to catch "keydown" events after the browser has updated the control
2.2691 - // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
2.2692 - var handler = valueUpdateHandler;
2.2693 - if (ko.utils.stringStartsWith(eventName, "after")) {
2.2694 - handler = function() { setTimeout(valueUpdateHandler, 0) };
2.2695 - eventName = eventName.substring("after".length);
2.2696 - }
2.2697 - ko.utils.registerEventHandler(element, eventName, handler);
2.2698 - });
2.2699 - },
2.2700 - 'update': function (element, valueAccessor) {
2.2701 - var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
2.2702 - var newValue = ko.utils.unwrapObservable(valueAccessor());
2.2703 - var elementValue = ko.selectExtensions.readValue(element);
2.2704 - var valueHasChanged = (newValue != elementValue);
2.2705 -
2.2706 - // 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.2707 - // 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.2708 - if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
2.2709 - valueHasChanged = true;
2.2710 -
2.2711 - if (valueHasChanged) {
2.2712 - var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
2.2713 - applyValueAction();
2.2714 -
2.2715 - // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
2.2716 - // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
2.2717 - // to apply the value as well.
2.2718 - var alsoApplyAsynchronously = valueIsSelectOption;
2.2719 - if (alsoApplyAsynchronously)
2.2720 - setTimeout(applyValueAction, 0);
2.2721 - }
2.2722 -
2.2723 - // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
2.2724 - // because you're not allowed to have a model value that disagrees with a visible UI selection.
2.2725 - if (valueIsSelectOption && (element.length > 0))
2.2726 - ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
2.2727 - }
2.2728 -};
2.2729 -ko.bindingHandlers['visible'] = {
2.2730 - 'update': function (element, valueAccessor) {
2.2731 - var value = ko.utils.unwrapObservable(valueAccessor());
2.2732 - var isCurrentlyVisible = !(element.style.display == "none");
2.2733 - if (value && !isCurrentlyVisible)
2.2734 - element.style.display = "";
2.2735 - else if ((!value) && isCurrentlyVisible)
2.2736 - element.style.display = "none";
2.2737 - }
2.2738 -};
2.2739 -// 'click' is just a shorthand for the usual full-length event:{click:handler}
2.2740 -makeEventHandlerShortcut('click');
2.2741 -// If you want to make a custom template engine,
2.2742 -//
2.2743 -// [1] Inherit from this class (like ko.nativeTemplateEngine does)
2.2744 -// [2] Override 'renderTemplateSource', supplying a function with this signature:
2.2745 -//
2.2746 -// function (templateSource, bindingContext, options) {
2.2747 -// // - templateSource.text() is the text of the template you should render
2.2748 -// // - bindingContext.$data is the data you should pass into the template
2.2749 -// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
2.2750 -// // and bindingContext.$root available in the template too
2.2751 -// // - options gives you access to any other properties set on "data-bind: { template: options }"
2.2752 -// //
2.2753 -// // Return value: an array of DOM nodes
2.2754 -// }
2.2755 -//
2.2756 -// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
2.2757 -//
2.2758 -// function (script) {
2.2759 -// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
2.2760 -// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
2.2761 -// }
2.2762 -//
2.2763 -// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
2.2764 -// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
2.2765 -// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
2.2766 -
2.2767 -ko.templateEngine = function () { };
2.2768 -
2.2769 -ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
2.2770 - throw new Error("Override renderTemplateSource");
2.2771 -};
2.2772 -
2.2773 -ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
2.2774 - throw new Error("Override createJavaScriptEvaluatorBlock");
2.2775 -};
2.2776 -
2.2777 -ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
2.2778 - // Named template
2.2779 - if (typeof template == "string") {
2.2780 - templateDocument = templateDocument || document;
2.2781 - var elem = templateDocument.getElementById(template);
2.2782 - if (!elem)
2.2783 - throw new Error("Cannot find template with ID " + template);
2.2784 - return new ko.templateSources.domElement(elem);
2.2785 - } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
2.2786 - // Anonymous template
2.2787 - return new ko.templateSources.anonymousTemplate(template);
2.2788 - } else
2.2789 - throw new Error("Unknown template type: " + template);
2.2790 -};
2.2791 -
2.2792 -ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
2.2793 - var templateSource = this['makeTemplateSource'](template, templateDocument);
2.2794 - return this['renderTemplateSource'](templateSource, bindingContext, options);
2.2795 -};
2.2796 -
2.2797 -ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
2.2798 - // Skip rewriting if requested
2.2799 - if (this['allowTemplateRewriting'] === false)
2.2800 - return true;
2.2801 - return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
2.2802 -};
2.2803 -
2.2804 -ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
2.2805 - var templateSource = this['makeTemplateSource'](template, templateDocument);
2.2806 - var rewritten = rewriterCallback(templateSource['text']());
2.2807 - templateSource['text'](rewritten);
2.2808 - templateSource['data']("isRewritten", true);
2.2809 -};
2.2810 -
2.2811 -ko.exportSymbol('templateEngine', ko.templateEngine);
2.2812 -
2.2813 -ko.templateRewriting = (function () {
2.2814 - var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
2.2815 - var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
2.2816 -
2.2817 - function validateDataBindValuesForRewriting(keyValueArray) {
2.2818 - var allValidators = ko.expressionRewriting.bindingRewriteValidators;
2.2819 - for (var i = 0; i < keyValueArray.length; i++) {
2.2820 - var key = keyValueArray[i]['key'];
2.2821 - if (allValidators.hasOwnProperty(key)) {
2.2822 - var validator = allValidators[key];
2.2823 -
2.2824 - if (typeof validator === "function") {
2.2825 - var possibleErrorMessage = validator(keyValueArray[i]['value']);
2.2826 - if (possibleErrorMessage)
2.2827 - throw new Error(possibleErrorMessage);
2.2828 - } else if (!validator) {
2.2829 - throw new Error("This template engine does not support the '" + key + "' binding within its templates");
2.2830 - }
2.2831 - }
2.2832 - }
2.2833 - }
2.2834 -
2.2835 - function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
2.2836 - var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
2.2837 - validateDataBindValuesForRewriting(dataBindKeyValueArray);
2.2838 - var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray);
2.2839 -
2.2840 - // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
2.2841 - // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
2.2842 - // extra indirection.
2.2843 - var applyBindingsToNextSiblingScript =
2.2844 - "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()})";
2.2845 - return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
2.2846 - }
2.2847 -
2.2848 - return {
2.2849 - ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
2.2850 - if (!templateEngine['isTemplateRewritten'](template, templateDocument))
2.2851 - templateEngine['rewriteTemplate'](template, function (htmlString) {
2.2852 - return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
2.2853 - }, templateDocument);
2.2854 - },
2.2855 -
2.2856 - memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
2.2857 - return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
2.2858 - return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
2.2859 - }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
2.2860 - return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
2.2861 - });
2.2862 - },
2.2863 -
2.2864 - applyMemoizedBindingsToNextSibling: function (bindings) {
2.2865 - return ko.memoization.memoize(function (domNode, bindingContext) {
2.2866 - if (domNode.nextSibling)
2.2867 - ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
2.2868 - });
2.2869 - }
2.2870 - }
2.2871 -})();
2.2872 -
2.2873 -
2.2874 -// Exported only because it has to be referenced by string lookup from within rewritten template
2.2875 -ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
2.2876 -(function() {
2.2877 - // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
2.2878 - // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
2.2879 - //
2.2880 - // Two are provided by default:
2.2881 - // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
2.2882 - // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
2.2883 - // without reading/writing the actual element text content, since it will be overwritten
2.2884 - // with the rendered template output.
2.2885 - // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
2.2886 - // Template sources need to have the following functions:
2.2887 - // text() - returns the template text from your storage location
2.2888 - // text(value) - writes the supplied template text to your storage location
2.2889 - // data(key) - reads values stored using data(key, value) - see below
2.2890 - // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
2.2891 - //
2.2892 - // Optionally, template sources can also have the following functions:
2.2893 - // nodes() - returns a DOM element containing the nodes of this template, where available
2.2894 - // nodes(value) - writes the given DOM element to your storage location
2.2895 - // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
2.2896 - // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
2.2897 - //
2.2898 - // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
2.2899 - // using and overriding "makeTemplateSource" to return an instance of your custom template source.
2.2900 -
2.2901 - ko.templateSources = {};
2.2902 -
2.2903 - // ---- ko.templateSources.domElement -----
2.2904 -
2.2905 - ko.templateSources.domElement = function(element) {
2.2906 - this.domElement = element;
2.2907 - }
2.2908 -
2.2909 - ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
2.2910 - var tagNameLower = ko.utils.tagNameLower(this.domElement),
2.2911 - elemContentsProperty = tagNameLower === "script" ? "text"
2.2912 - : tagNameLower === "textarea" ? "value"
2.2913 - : "innerHTML";
2.2914 -
2.2915 - if (arguments.length == 0) {
2.2916 - return this.domElement[elemContentsProperty];
2.2917 - } else {
2.2918 - var valueToWrite = arguments[0];
2.2919 - if (elemContentsProperty === "innerHTML")
2.2920 - ko.utils.setHtml(this.domElement, valueToWrite);
2.2921 - else
2.2922 - this.domElement[elemContentsProperty] = valueToWrite;
2.2923 - }
2.2924 - };
2.2925 -
2.2926 - ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
2.2927 - if (arguments.length === 1) {
2.2928 - return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
2.2929 - } else {
2.2930 - ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
2.2931 - }
2.2932 - };
2.2933 -
2.2934 - // ---- ko.templateSources.anonymousTemplate -----
2.2935 - // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
2.2936 - // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
2.2937 - // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
2.2938 -
2.2939 - var anonymousTemplatesDomDataKey = "__ko_anon_template__";
2.2940 - ko.templateSources.anonymousTemplate = function(element) {
2.2941 - this.domElement = element;
2.2942 - }
2.2943 - ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
2.2944 - ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
2.2945 - if (arguments.length == 0) {
2.2946 - var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
2.2947 - if (templateData.textData === undefined && templateData.containerData)
2.2948 - templateData.textData = templateData.containerData.innerHTML;
2.2949 - return templateData.textData;
2.2950 - } else {
2.2951 - var valueToWrite = arguments[0];
2.2952 - ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
2.2953 - }
2.2954 - };
2.2955 - ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
2.2956 - if (arguments.length == 0) {
2.2957 - var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
2.2958 - return templateData.containerData;
2.2959 - } else {
2.2960 - var valueToWrite = arguments[0];
2.2961 - ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
2.2962 - }
2.2963 - };
2.2964 -
2.2965 - ko.exportSymbol('templateSources', ko.templateSources);
2.2966 - ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
2.2967 - ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
2.2968 -})();
2.2969 -(function () {
2.2970 - var _templateEngine;
2.2971 - ko.setTemplateEngine = function (templateEngine) {
2.2972 - if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
2.2973 - throw new Error("templateEngine must inherit from ko.templateEngine");
2.2974 - _templateEngine = templateEngine;
2.2975 - }
2.2976 -
2.2977 - function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
2.2978 - var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
2.2979 - while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
2.2980 - nextInQueue = ko.virtualElements.nextSibling(node);
2.2981 - if (node.nodeType === 1 || node.nodeType === 8)
2.2982 - action(node);
2.2983 - }
2.2984 - }
2.2985 -
2.2986 - function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
2.2987 - // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
2.2988 - // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
2.2989 - // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
2.2990 - // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
2.2991 - // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
2.2992 -
2.2993 - if (continuousNodeArray.length) {
2.2994 - var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
2.2995 -
2.2996 - // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
2.2997 - // whereas a regular applyBindings won't introduce new memoized nodes
2.2998 - invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
2.2999 - ko.applyBindings(bindingContext, node);
2.3000 - });
2.3001 - invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
2.3002 - ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
2.3003 - });
2.3004 - }
2.3005 - }
2.3006 -
2.3007 - function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
2.3008 - return nodeOrNodeArray.nodeType ? nodeOrNodeArray
2.3009 - : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
2.3010 - : null;
2.3011 - }
2.3012 -
2.3013 - function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
2.3014 - options = options || {};
2.3015 - var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
2.3016 - var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
2.3017 - var templateEngineToUse = (options['templateEngine'] || _templateEngine);
2.3018 - ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
2.3019 - var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
2.3020 -
2.3021 - // Loosely check result is an array of DOM nodes
2.3022 - if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
2.3023 - throw new Error("Template engine must return an array of DOM nodes");
2.3024 -
2.3025 - var haveAddedNodesToParent = false;
2.3026 - switch (renderMode) {
2.3027 - case "replaceChildren":
2.3028 - ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
2.3029 - haveAddedNodesToParent = true;
2.3030 - break;
2.3031 - case "replaceNode":
2.3032 - ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
2.3033 - haveAddedNodesToParent = true;
2.3034 - break;
2.3035 - case "ignoreTargetNode": break;
2.3036 - default:
2.3037 - throw new Error("Unknown renderMode: " + renderMode);
2.3038 - }
2.3039 -
2.3040 - if (haveAddedNodesToParent) {
2.3041 - activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
2.3042 - if (options['afterRender'])
2.3043 - ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
2.3044 - }
2.3045 -
2.3046 - return renderedNodesArray;
2.3047 - }
2.3048 -
2.3049 - ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
2.3050 - options = options || {};
2.3051 - if ((options['templateEngine'] || _templateEngine) == undefined)
2.3052 - throw new Error("Set a template engine before calling renderTemplate");
2.3053 - renderMode = renderMode || "replaceChildren";
2.3054 -
2.3055 - if (targetNodeOrNodeArray) {
2.3056 - var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
2.3057 -
2.3058 - var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
2.3059 - var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
2.3060 -
2.3061 - return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
2.3062 - function () {
2.3063 - // Ensure we've got a proper binding context to work with
2.3064 - var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
2.3065 - ? dataOrBindingContext
2.3066 - : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
2.3067 -
2.3068 - // Support selecting template as a function of the data being rendered
2.3069 - var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
2.3070 -
2.3071 - var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
2.3072 - if (renderMode == "replaceNode") {
2.3073 - targetNodeOrNodeArray = renderedNodesArray;
2.3074 - firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
2.3075 - }
2.3076 - },
2.3077 - null,
2.3078 - { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
2.3079 - );
2.3080 - } else {
2.3081 - // 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.3082 - return ko.memoization.memoize(function (domNode) {
2.3083 - ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
2.3084 - });
2.3085 - }
2.3086 - };
2.3087 -
2.3088 - ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
2.3089 - // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
2.3090 - // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
2.3091 - var arrayItemContext;
2.3092 -
2.3093 - // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
2.3094 - var executeTemplateForArrayItem = function (arrayValue, index) {
2.3095 - // Support selecting template as a function of the data being rendered
2.3096 - arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue), options['as']);
2.3097 - arrayItemContext['$index'] = index;
2.3098 - var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
2.3099 - return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
2.3100 - }
2.3101 -
2.3102 - // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
2.3103 - var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
2.3104 - activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
2.3105 - if (options['afterRender'])
2.3106 - options['afterRender'](addedNodesArray, arrayValue);
2.3107 - };
2.3108 -
2.3109 - return ko.dependentObservable(function () {
2.3110 - var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
2.3111 - if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
2.3112 - unwrappedArray = [unwrappedArray];
2.3113 -
2.3114 - // Filter out any entries marked as destroyed
2.3115 - var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
2.3116 - return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
2.3117 - });
2.3118 -
2.3119 - // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
2.3120 - // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
2.3121 - ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
2.3122 -
2.3123 - }, null, { disposeWhenNodeIsRemoved: targetNode });
2.3124 - };
2.3125 -
2.3126 - var templateComputedDomDataKey = '__ko__templateComputedDomDataKey__';
2.3127 - function disposeOldComputedAndStoreNewOne(element, newComputed) {
2.3128 - var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
2.3129 - if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
2.3130 - oldComputed.dispose();
2.3131 - ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
2.3132 - }
2.3133 -
2.3134 - ko.bindingHandlers['template'] = {
2.3135 - 'init': function(element, valueAccessor) {
2.3136 - // Support anonymous templates
2.3137 - var bindingValue = ko.utils.unwrapObservable(valueAccessor());
2.3138 - if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
2.3139 - // It's an anonymous template - store the element contents, then clear the element
2.3140 - var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
2.3141 - container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
2.3142 - new ko.templateSources.anonymousTemplate(element)['nodes'](container);
2.3143 - }
2.3144 - return { 'controlsDescendantBindings': true };
2.3145 - },
2.3146 - 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.3147 - var templateName = ko.utils.unwrapObservable(valueAccessor()),
2.3148 - options = {},
2.3149 - shouldDisplay = true,
2.3150 - dataValue,
2.3151 - templateComputed = null;
2.3152 -
2.3153 - if (typeof templateName != "string") {
2.3154 - options = templateName;
2.3155 - templateName = options['name'];
2.3156 -
2.3157 - // Support "if"/"ifnot" conditions
2.3158 - if ('if' in options)
2.3159 - shouldDisplay = ko.utils.unwrapObservable(options['if']);
2.3160 - if (shouldDisplay && 'ifnot' in options)
2.3161 - shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
2.3162 -
2.3163 - dataValue = ko.utils.unwrapObservable(options['data']);
2.3164 - }
2.3165 -
2.3166 - if ('foreach' in options) {
2.3167 - // Render once for each data point (treating data set as empty if shouldDisplay==false)
2.3168 - var dataArray = (shouldDisplay && options['foreach']) || [];
2.3169 - templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
2.3170 - } else if (!shouldDisplay) {
2.3171 - ko.virtualElements.emptyNode(element);
2.3172 - } else {
2.3173 - // Render once for this single data point (or use the viewModel if no data was provided)
2.3174 - var innerBindingContext = ('data' in options) ?
2.3175 - bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
2.3176 - bindingContext; // Given no explicit 'data' value, we retain the same binding context
2.3177 - templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
2.3178 - }
2.3179 -
2.3180 - // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
2.3181 - disposeOldComputedAndStoreNewOne(element, templateComputed);
2.3182 - }
2.3183 - };
2.3184 -
2.3185 - // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
2.3186 - ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
2.3187 - var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
2.3188 -
2.3189 - if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
2.3190 - 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.3191 -
2.3192 - if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
2.3193 - return null; // Named templates can be rewritten, so return "no error"
2.3194 - return "This template engine does not support anonymous templates nested within its templates";
2.3195 - };
2.3196 -
2.3197 - ko.virtualElements.allowedBindings['template'] = true;
2.3198 -})();
2.3199 -
2.3200 -ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
2.3201 -ko.exportSymbol('renderTemplate', ko.renderTemplate);
2.3202 -
2.3203 -ko.utils.compareArrays = (function () {
2.3204 - var statusNotInOld = 'added', statusNotInNew = 'deleted';
2.3205 -
2.3206 - // Simple calculation based on Levenshtein distance.
2.3207 - function compareArrays(oldArray, newArray, dontLimitMoves) {
2.3208 - oldArray = oldArray || [];
2.3209 - newArray = newArray || [];
2.3210 -
2.3211 - if (oldArray.length <= newArray.length)
2.3212 - return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, dontLimitMoves);
2.3213 - else
2.3214 - return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, dontLimitMoves);
2.3215 - }
2.3216 -
2.3217 - function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, dontLimitMoves) {
2.3218 - var myMin = Math.min,
2.3219 - myMax = Math.max,
2.3220 - editDistanceMatrix = [],
2.3221 - smlIndex, smlIndexMax = smlArray.length,
2.3222 - bigIndex, bigIndexMax = bigArray.length,
2.3223 - compareRange = (bigIndexMax - smlIndexMax) || 1,
2.3224 - maxDistance = smlIndexMax + bigIndexMax + 1,
2.3225 - thisRow, lastRow,
2.3226 - bigIndexMaxForRow, bigIndexMinForRow;
2.3227 -
2.3228 - for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
2.3229 - lastRow = thisRow;
2.3230 - editDistanceMatrix.push(thisRow = []);
2.3231 - bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
2.3232 - bigIndexMinForRow = myMax(0, smlIndex - 1);
2.3233 - for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
2.3234 - if (!bigIndex)
2.3235 - thisRow[bigIndex] = smlIndex + 1;
2.3236 - else if (!smlIndex) // Top row - transform empty array into new array via additions
2.3237 - thisRow[bigIndex] = bigIndex + 1;
2.3238 - else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
2.3239 - thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
2.3240 - else {
2.3241 - var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
2.3242 - var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
2.3243 - thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
2.3244 - }
2.3245 - }
2.3246 - }
2.3247 -
2.3248 - var editScript = [], meMinusOne, notInSml = [], notInBig = [];
2.3249 - for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
2.3250 - meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
2.3251 - if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
2.3252 - notInSml.push(editScript[editScript.length] = { // added
2.3253 - 'status': statusNotInSml,
2.3254 - 'value': bigArray[--bigIndex],
2.3255 - 'index': bigIndex });
2.3256 - } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
2.3257 - notInBig.push(editScript[editScript.length] = { // deleted
2.3258 - 'status': statusNotInBig,
2.3259 - 'value': smlArray[--smlIndex],
2.3260 - 'index': smlIndex });
2.3261 - } else {
2.3262 - editScript.push({
2.3263 - 'status': "retained",
2.3264 - 'value': bigArray[--bigIndex] });
2.3265 - --smlIndex;
2.3266 - }
2.3267 - }
2.3268 -
2.3269 - if (notInSml.length && notInBig.length) {
2.3270 - // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
2.3271 - // smlIndexMax keeps the time complexity of this algorithm linear.
2.3272 - var limitFailedCompares = smlIndexMax * 10, failedCompares,
2.3273 - a, d, notInSmlItem, notInBigItem;
2.3274 - // Go through the items that have been added and deleted and try to find matches between them.
2.3275 - for (failedCompares = a = 0; (dontLimitMoves || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
2.3276 - for (d = 0; notInBigItem = notInBig[d]; d++) {
2.3277 - if (notInSmlItem['value'] === notInBigItem['value']) {
2.3278 - notInSmlItem['moved'] = notInBigItem['index'];
2.3279 - notInBigItem['moved'] = notInSmlItem['index'];
2.3280 - notInBig.splice(d,1); // This item is marked as moved; so remove it from notInBig list
2.3281 - failedCompares = d = 0; // Reset failed compares count because we're checking for consecutive failures
2.3282 - break;
2.3283 - }
2.3284 - }
2.3285 - failedCompares += d;
2.3286 - }
2.3287 - }
2.3288 - return editScript.reverse();
2.3289 - }
2.3290 -
2.3291 - return compareArrays;
2.3292 -})();
2.3293 -
2.3294 -ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
2.3295 -
2.3296 -(function () {
2.3297 - // Objective:
2.3298 - // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
2.3299 - // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
2.3300 - // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
2.3301 - // 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.3302 - // previously mapped - retain those nodes, and just insert/delete other ones
2.3303 -
2.3304 - // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
2.3305 - // You can use this, for example, to activate bindings on those nodes.
2.3306 -
2.3307 - function fixUpNodesToBeMovedOrRemoved(contiguousNodeArray) {
2.3308 - // Before moving, deleting, or replacing a set of nodes that were previously outputted by the "map" function, we have to reconcile
2.3309 - // 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.3310 - // or that new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
2.3311 - // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
2.3312 - // So, this function translates the old "map" output array into its best guess of what set of current DOM nodes should be removed.
2.3313 - //
2.3314 - // Rules:
2.3315 - // [A] Any leading nodes that aren't in the document any more should be ignored
2.3316 - // These most likely correspond to memoization nodes that were already removed during binding
2.3317 - // See https://github.com/SteveSanderson/knockout/pull/440
2.3318 - // [B] We want to output a contiguous series of nodes that are still in the document. So, ignore any nodes that
2.3319 - // have already been removed, and include any nodes that have been inserted among the previous collection
2.3320 -
2.3321 - // Rule [A]
2.3322 - while (contiguousNodeArray.length && !ko.utils.domNodeIsAttachedToDocument(contiguousNodeArray[0]))
2.3323 - contiguousNodeArray.splice(0, 1);
2.3324 -
2.3325 - // Rule [B]
2.3326 - if (contiguousNodeArray.length > 1) {
2.3327 - // Build up the actual new contiguous node set
2.3328 - var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
2.3329 - while (current !== last) {
2.3330 - current = current.nextSibling;
2.3331 - if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
2.3332 - return;
2.3333 - newContiguousSet.push(current);
2.3334 - }
2.3335 -
2.3336 - // ... then mutate the input array to match this.
2.3337 - // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
2.3338 - Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
2.3339 - }
2.3340 - return contiguousNodeArray;
2.3341 - }
2.3342 -
2.3343 - function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
2.3344 - // Map this array value inside a dependentObservable so we re-map when any dependency changes
2.3345 - var mappedNodes = [];
2.3346 - var dependentObservable = ko.dependentObservable(function() {
2.3347 - var newMappedNodes = mapping(valueToMap, index) || [];
2.3348 -
2.3349 - // On subsequent evaluations, just replace the previously-inserted DOM nodes
2.3350 - if (mappedNodes.length > 0) {
2.3351 - ko.utils.replaceDomNodes(fixUpNodesToBeMovedOrRemoved(mappedNodes), newMappedNodes);
2.3352 - if (callbackAfterAddingNodes)
2.3353 - ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
2.3354 - }
2.3355 -
2.3356 - // Replace the contents of the mappedNodes array, thereby updating the record
2.3357 - // of which nodes would be deleted if valueToMap was itself later removed
2.3358 - mappedNodes.splice(0, mappedNodes.length);
2.3359 - ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
2.3360 - }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
2.3361 - return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
2.3362 - }
2.3363 -
2.3364 - var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
2.3365 -
2.3366 - ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
2.3367 - // Compare the provided array against the previous one
2.3368 - array = array || [];
2.3369 - options = options || {};
2.3370 - var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
2.3371 - var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
2.3372 - var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
2.3373 - var editScript = ko.utils.compareArrays(lastArray, array);
2.3374 -
2.3375 - // Build the new mapping result
2.3376 - var newMappingResult = [];
2.3377 - var lastMappingResultIndex = 0;
2.3378 - var newMappingResultIndex = 0;
2.3379 -
2.3380 - var nodesToDelete = [];
2.3381 - var itemsToProcess = [];
2.3382 - var itemsForBeforeRemoveCallbacks = [];
2.3383 - var itemsForMoveCallbacks = [];
2.3384 - var itemsForAfterAddCallbacks = [];
2.3385 - var mapData;
2.3386 -
2.3387 - function itemMovedOrRetained(editScriptIndex, oldPosition) {
2.3388 - mapData = lastMappingResult[oldPosition];
2.3389 - if (newMappingResultIndex !== oldPosition)
2.3390 - itemsForMoveCallbacks[editScriptIndex] = mapData;
2.3391 - // Since updating the index might change the nodes, do so before calling fixUpNodesToBeMovedOrRemoved
2.3392 - mapData.indexObservable(newMappingResultIndex++);
2.3393 - fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes);
2.3394 - newMappingResult.push(mapData);
2.3395 - itemsToProcess.push(mapData);
2.3396 - }
2.3397 -
2.3398 - function callCallback(callback, items) {
2.3399 - if (callback) {
2.3400 - for (var i = 0, n = items.length; i < n; i++) {
2.3401 - if (items[i]) {
2.3402 - ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
2.3403 - callback(node, i, items[i].arrayEntry);
2.3404 - });
2.3405 - }
2.3406 - }
2.3407 - }
2.3408 - }
2.3409 -
2.3410 - for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
2.3411 - movedIndex = editScriptItem['moved'];
2.3412 - switch (editScriptItem['status']) {
2.3413 - case "deleted":
2.3414 - if (movedIndex === undefined) {
2.3415 - mapData = lastMappingResult[lastMappingResultIndex];
2.3416 -
2.3417 - // Stop tracking changes to the mapping for these nodes
2.3418 - if (mapData.dependentObservable)
2.3419 - mapData.dependentObservable.dispose();
2.3420 -
2.3421 - // Queue these nodes for later removal
2.3422 - nodesToDelete.push.apply(nodesToDelete, fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes));
2.3423 - if (options['beforeRemove']) {
2.3424 - itemsForBeforeRemoveCallbacks[i] = mapData;
2.3425 - itemsToProcess.push(mapData);
2.3426 - }
2.3427 - }
2.3428 - lastMappingResultIndex++;
2.3429 - break;
2.3430 -
2.3431 - case "retained":
2.3432 - itemMovedOrRetained(i, lastMappingResultIndex++);
2.3433 - break;
2.3434 -
2.3435 - case "added":
2.3436 - if (movedIndex !== undefined) {
2.3437 - itemMovedOrRetained(i, movedIndex);
2.3438 - } else {
2.3439 - mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
2.3440 - newMappingResult.push(mapData);
2.3441 - itemsToProcess.push(mapData);
2.3442 - if (!isFirstExecution)
2.3443 - itemsForAfterAddCallbacks[i] = mapData;
2.3444 - }
2.3445 - break;
2.3446 - }
2.3447 - }
2.3448 -
2.3449 - // Call beforeMove first before any changes have been made to the DOM
2.3450 - callCallback(options['beforeMove'], itemsForMoveCallbacks);
2.3451 -
2.3452 - // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
2.3453 - ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
2.3454 -
2.3455 - // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
2.3456 - for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
2.3457 - // Get nodes for newly added items
2.3458 - if (!mapData.mappedNodes)
2.3459 - ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
2.3460 -
2.3461 - // Put nodes in the right place if they aren't there already
2.3462 - for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
2.3463 - if (node !== nextNode)
2.3464 - ko.virtualElements.insertAfter(domNode, node, lastNode);
2.3465 - }
2.3466 -
2.3467 - // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
2.3468 - if (!mapData.initialized && callbackAfterAddingNodes) {
2.3469 - callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
2.3470 - mapData.initialized = true;
2.3471 - }
2.3472 - }
2.3473 -
2.3474 - // If there's a beforeRemove callback, call it after reordering.
2.3475 - // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
2.3476 - // some sort of animation, which is why we first reorder the nodes that will be removed. If the
2.3477 - // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
2.3478 - // Perhaps we'll make that change in the future if this scenario becomes more common.
2.3479 - callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
2.3480 -
2.3481 - // Finally call afterMove and afterAdd callbacks
2.3482 - callCallback(options['afterMove'], itemsForMoveCallbacks);
2.3483 - callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
2.3484 -
2.3485 - // Store a copy of the array items we just considered so we can difference it next time
2.3486 - ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
2.3487 - }
2.3488 -})();
2.3489 -
2.3490 -ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
2.3491 -ko.nativeTemplateEngine = function () {
2.3492 - this['allowTemplateRewriting'] = false;
2.3493 -}
2.3494 -
2.3495 -ko.nativeTemplateEngine.prototype = new ko.templateEngine();
2.3496 -ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
2.3497 - var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
2.3498 - templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
2.3499 - templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
2.3500 -
2.3501 - if (templateNodes) {
2.3502 - return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
2.3503 - } else {
2.3504 - var templateText = templateSource['text']();
2.3505 - return ko.utils.parseHtmlFragment(templateText);
2.3506 - }
2.3507 -};
2.3508 -
2.3509 -ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
2.3510 -ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
2.3511 -
2.3512 -ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
2.3513 -(function() {
2.3514 - ko.jqueryTmplTemplateEngine = function () {
2.3515 - // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
2.3516 - // doesn't expose a version number, so we have to infer it.
2.3517 - // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
2.3518 - // which KO internally refers to as version "2", so older versions are no longer detected.
2.3519 - var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
2.3520 - if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
2.3521 - return 0;
2.3522 - // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
2.3523 - try {
2.3524 - if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
2.3525 - // Since 1.0.0pre, custom tags should append markup to an array called "__"
2.3526 - return 2; // Final version of jquery.tmpl
2.3527 - }
2.3528 - } catch(ex) { /* Apparently not the version we were looking for */ }
2.3529 -
2.3530 - return 1; // Any older version that we don't support
2.3531 - })();
2.3532 -
2.3533 - function ensureHasReferencedJQueryTemplates() {
2.3534 - if (jQueryTmplVersion < 2)
2.3535 - throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
2.3536 - }
2.3537 -
2.3538 - function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
2.3539 - return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
2.3540 - }
2.3541 -
2.3542 - this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
2.3543 - options = options || {};
2.3544 - ensureHasReferencedJQueryTemplates();
2.3545 -
2.3546 - // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
2.3547 - var precompiled = templateSource['data']('precompiled');
2.3548 - if (!precompiled) {
2.3549 - var templateText = templateSource['text']() || "";
2.3550 - // Wrap in "with($whatever.koBindingContext) { ... }"
2.3551 - templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
2.3552 -
2.3553 - precompiled = jQuery['template'](null, templateText);
2.3554 - templateSource['data']('precompiled', precompiled);
2.3555 - }
2.3556 -
2.3557 - var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
2.3558 - var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
2.3559 -
2.3560 - var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
2.3561 - resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
2.3562 -
2.3563 - jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
2.3564 - return resultNodes;
2.3565 - };
2.3566 -
2.3567 - this['createJavaScriptEvaluatorBlock'] = function(script) {
2.3568 - return "{{ko_code ((function() { return " + script + " })()) }}";
2.3569 - };
2.3570 -
2.3571 - this['addTemplate'] = function(templateName, templateMarkup) {
2.3572 - document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
2.3573 - };
2.3574 -
2.3575 - if (jQueryTmplVersion > 0) {
2.3576 - jQuery['tmpl']['tag']['ko_code'] = {
2.3577 - open: "__.push($1 || '');"
2.3578 - };
2.3579 - jQuery['tmpl']['tag']['ko_with'] = {
2.3580 - open: "with($1) {",
2.3581 - close: "} "
2.3582 - };
2.3583 - }
2.3584 - };
2.3585 -
2.3586 - ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
2.3587 -
2.3588 - // Use this one by default *only if jquery.tmpl is referenced*
2.3589 - var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
2.3590 - if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
2.3591 - ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
2.3592 -
2.3593 - ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
2.3594 -})();
2.3595 -});
2.3596 -})(window,document,navigator,window["jQuery"]);
2.3597 -})();
2.3598 \ No newline at end of file