1.1 --- a/ko4j/src/main/resources/org/netbeans/html/ko4j/knockout-3.2.0.debug.js Sun Dec 13 21:33:32 2015 +0100
1.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
1.3 @@ -1,5342 +0,0 @@
1.4 -/*
1.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
1.6 - *
1.7 - * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
1.8 - *
1.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
1.10 - * Other names may be trademarks of their respective owners.
1.11 - *
1.12 - * The contents of this file are subject to the terms of either the GNU
1.13 - * General Public License Version 2 only ("GPL") or the Common
1.14 - * Development and Distribution License("CDDL") (collectively, the
1.15 - * "License"). You may not use this file except in compliance with the
1.16 - * License. You can obtain a copy of the License at
1.17 - * http://www.netbeans.org/cddl-gplv2.html
1.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
1.19 - * specific language governing permissions and limitations under the
1.20 - * License. When distributing the software, include this License Header
1.21 - * Notice in each file and include the License file at
1.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
1.23 - * particular file as subject to the "Classpath" exception as provided
1.24 - * by Oracle in the GPL Version 2 section of the License file that
1.25 - * accompanied this code. If applicable, add the following below the
1.26 - * License Header, with the fields enclosed by brackets [] replaced by
1.27 - * your own identifying information:
1.28 - * "Portions Copyrighted [year] [name of copyright owner]"
1.29 - *
1.30 - * Contributor(s):
1.31 - *
1.32 - * The Original Software is NetBeans. The Initial Developer of the Original
1.33 - * Software is Oracle. Portions Copyright 2013-2014 Oracle. All Rights Reserved.
1.34 - *
1.35 - * If you wish your version of this file to be governed by only the CDDL
1.36 - * or only the GPL Version 2, indicate your decision by adding
1.37 - * "[Contributor] elects to include this software in this distribution
1.38 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
1.39 - * single choice of license, a recipient has the option to distribute
1.40 - * your version of this file under either the CDDL, the GPL Version 2 or
1.41 - * to extend the choice of license to its licensees as provided above.
1.42 - * However, if you add GPL Version 2 code and therefore, elected the GPL
1.43 - * Version 2 license, then the option applies only if the new code is
1.44 - * made subject to such option by the copyright holder.
1.45 - */
1.46 -
1.47 -/*!
1.48 - * Knockout JavaScript library v3.2.0
1.49 - * (c) Steven Sanderson - http://knockoutjs.com/
1.50 - * License: MIT (http://www.opensource.org/licenses/mit-license.php)
1.51 - */
1.52 -
1.53 -(function(){
1.54 -var DEBUG=false;
1.55 -(function(undefined){
1.56 - // (0, eval)('this') is a robust way of getting a reference to the global object
1.57 - // For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023
1.58 - var window = this || (0, eval)('this'),
1.59 - document = window['document'],
1.60 - navigator = window['navigator'],
1.61 - jQueryInstance = window["jQuery"],
1.62 - JSON = window["JSON"];
1.63 -(function(factory) {
1.64 - // Support three module loading scenarios
1.65 - if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
1.66 - // [1] CommonJS/Node.js
1.67 - var target = module['exports'] || exports; // module.exports is for Node.js
1.68 - factory(target, require);
1.69 - } else if (typeof define === 'function' && define['amd']) {
1.70 - // [2] AMD anonymous module
1.71 - define(['exports', 'require'], factory);
1.72 - } else {
1.73 - // [3] No module loader (plain <script> tag) - put directly in global namespace
1.74 - factory(window['ko'] = {});
1.75 - }
1.76 -}(function(koExports, require){
1.77 -// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
1.78 -// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
1.79 -var ko = typeof koExports !== 'undefined' ? koExports : {};
1.80 -// Google Closure Compiler helpers (used only to make the minified file smaller)
1.81 -ko.exportSymbol = function(koPath, object) {
1.82 - var tokens = koPath.split(".");
1.83 -
1.84 - // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
1.85 - // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
1.86 - var target = ko;
1.87 -
1.88 - for (var i = 0; i < tokens.length - 1; i++)
1.89 - target = target[tokens[i]];
1.90 - target[tokens[tokens.length - 1]] = object;
1.91 -};
1.92 -ko.exportProperty = function(owner, publicName, object) {
1.93 - owner[publicName] = object;
1.94 -};
1.95 -ko.version = "3.2.0";
1.96 -
1.97 -ko.exportSymbol('version', ko.version);
1.98 -ko.utils = (function () {
1.99 - function objectForEach(obj, action) {
1.100 - for (var prop in obj) {
1.101 - if (obj.hasOwnProperty(prop)) {
1.102 - action(prop, obj[prop]);
1.103 - }
1.104 - }
1.105 - }
1.106 -
1.107 - function extend(target, source) {
1.108 - if (source) {
1.109 - for(var prop in source) {
1.110 - if(source.hasOwnProperty(prop)) {
1.111 - target[prop] = source[prop];
1.112 - }
1.113 - }
1.114 - }
1.115 - return target;
1.116 - }
1.117 -
1.118 - function setPrototypeOf(obj, proto) {
1.119 - obj.__proto__ = proto;
1.120 - return obj;
1.121 - }
1.122 -
1.123 - var canSetPrototype = ({ __proto__: [] } instanceof Array);
1.124 -
1.125 - // 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.126 - var knownEvents = {}, knownEventTypesByEventName = {};
1.127 - var keyEventTypeName = (navigator && /Firefox\/2/i.test(navigator.userAgent)) ? 'KeyboardEvent' : 'UIEvents';
1.128 - knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
1.129 - knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
1.130 - objectForEach(knownEvents, function(eventType, knownEventsForType) {
1.131 - if (knownEventsForType.length) {
1.132 - for (var i = 0, j = knownEventsForType.length; i < j; i++)
1.133 - knownEventTypesByEventName[knownEventsForType[i]] = eventType;
1.134 - }
1.135 - });
1.136 - var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
1.137 -
1.138 - // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
1.139 - // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
1.140 - // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
1.141 - // If there is a future need to detect specific versions of IE10+, we will amend this.
1.142 - var ieVersion = document && (function() {
1.143 - var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
1.144 -
1.145 - // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
1.146 - while (
1.147 - div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
1.148 - iElems[0]
1.149 - ) {}
1.150 - return version > 4 ? version : undefined;
1.151 - }());
1.152 - var isIe6 = ieVersion === 6,
1.153 - isIe7 = ieVersion === 7;
1.154 -
1.155 - function isClickOnCheckableElement(element, eventType) {
1.156 - if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
1.157 - if (eventType.toLowerCase() != "click") return false;
1.158 - var inputType = element.type;
1.159 - return (inputType == "checkbox") || (inputType == "radio");
1.160 - }
1.161 -
1.162 - return {
1.163 - fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
1.164 -
1.165 - arrayForEach: function (array, action) {
1.166 - for (var i = 0, j = array.length; i < j; i++)
1.167 - action(array[i], i);
1.168 - },
1.169 -
1.170 - arrayIndexOf: function (array, item) {
1.171 - if (typeof Array.prototype.indexOf == "function")
1.172 - return Array.prototype.indexOf.call(array, item);
1.173 - for (var i = 0, j = array.length; i < j; i++)
1.174 - if (array[i] === item)
1.175 - return i;
1.176 - return -1;
1.177 - },
1.178 -
1.179 - arrayFirst: function (array, predicate, predicateOwner) {
1.180 - for (var i = 0, j = array.length; i < j; i++)
1.181 - if (predicate.call(predicateOwner, array[i], i))
1.182 - return array[i];
1.183 - return null;
1.184 - },
1.185 -
1.186 - arrayRemoveItem: function (array, itemToRemove) {
1.187 - var index = ko.utils.arrayIndexOf(array, itemToRemove);
1.188 - if (index > 0) {
1.189 - array.splice(index, 1);
1.190 - }
1.191 - else if (index === 0) {
1.192 - array.shift();
1.193 - }
1.194 - },
1.195 -
1.196 - arrayGetDistinctValues: function (array) {
1.197 - array = array || [];
1.198 - var result = [];
1.199 - for (var i = 0, j = array.length; i < j; i++) {
1.200 - if (ko.utils.arrayIndexOf(result, array[i]) < 0)
1.201 - result.push(array[i]);
1.202 - }
1.203 - return result;
1.204 - },
1.205 -
1.206 - arrayMap: function (array, mapping) {
1.207 - array = array || [];
1.208 - var result = [];
1.209 - for (var i = 0, j = array.length; i < j; i++)
1.210 - result.push(mapping(array[i], i));
1.211 - return result;
1.212 - },
1.213 -
1.214 - arrayFilter: function (array, predicate) {
1.215 - array = array || [];
1.216 - var result = [];
1.217 - for (var i = 0, j = array.length; i < j; i++)
1.218 - if (predicate(array[i], i))
1.219 - result.push(array[i]);
1.220 - return result;
1.221 - },
1.222 -
1.223 - arrayPushAll: function (array, valuesToPush) {
1.224 - if (valuesToPush instanceof Array)
1.225 - array.push.apply(array, valuesToPush);
1.226 - else
1.227 - for (var i = 0, j = valuesToPush.length; i < j; i++)
1.228 - array.push(valuesToPush[i]);
1.229 - return array;
1.230 - },
1.231 -
1.232 - addOrRemoveItem: function(array, value, included) {
1.233 - var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.peekObservable(array), value);
1.234 - if (existingEntryIndex < 0) {
1.235 - if (included)
1.236 - array.push(value);
1.237 - } else {
1.238 - if (!included)
1.239 - array.splice(existingEntryIndex, 1);
1.240 - }
1.241 - },
1.242 -
1.243 - canSetPrototype: canSetPrototype,
1.244 -
1.245 - extend: extend,
1.246 -
1.247 - setPrototypeOf: setPrototypeOf,
1.248 -
1.249 - setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : extend,
1.250 -
1.251 - objectForEach: objectForEach,
1.252 -
1.253 - objectMap: function(source, mapping) {
1.254 - if (!source)
1.255 - return source;
1.256 - var target = {};
1.257 - for (var prop in source) {
1.258 - if (source.hasOwnProperty(prop)) {
1.259 - target[prop] = mapping(source[prop], prop, source);
1.260 - }
1.261 - }
1.262 - return target;
1.263 - },
1.264 -
1.265 - emptyDomNode: function (domNode) {
1.266 - while (domNode.firstChild) {
1.267 - ko.removeNode(domNode.firstChild);
1.268 - }
1.269 - },
1.270 -
1.271 - moveCleanedNodesToContainerElement: function(nodes) {
1.272 - // Ensure it's a real array, as we're about to reparent the nodes and
1.273 - // we don't want the underlying collection to change while we're doing that.
1.274 - var nodesArray = ko.utils.makeArray(nodes);
1.275 -
1.276 - var container = document.createElement('div');
1.277 - for (var i = 0, j = nodesArray.length; i < j; i++) {
1.278 - container.appendChild(ko.cleanNode(nodesArray[i]));
1.279 - }
1.280 - return container;
1.281 - },
1.282 -
1.283 - cloneNodes: function (nodesArray, shouldCleanNodes) {
1.284 - for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
1.285 - var clonedNode = nodesArray[i].cloneNode(true);
1.286 - newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
1.287 - }
1.288 - return newNodesArray;
1.289 - },
1.290 -
1.291 - setDomNodeChildren: function (domNode, childNodes) {
1.292 - ko.utils.emptyDomNode(domNode);
1.293 - if (childNodes) {
1.294 - for (var i = 0, j = childNodes.length; i < j; i++)
1.295 - domNode.appendChild(childNodes[i]);
1.296 - }
1.297 - },
1.298 -
1.299 - replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
1.300 - var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
1.301 - if (nodesToReplaceArray.length > 0) {
1.302 - var insertionPoint = nodesToReplaceArray[0];
1.303 - var parent = insertionPoint.parentNode;
1.304 - for (var i = 0, j = newNodesArray.length; i < j; i++)
1.305 - parent.insertBefore(newNodesArray[i], insertionPoint);
1.306 - for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
1.307 - ko.removeNode(nodesToReplaceArray[i]);
1.308 - }
1.309 - }
1.310 - },
1.311 -
1.312 - fixUpContinuousNodeArray: function(continuousNodeArray, parentNode) {
1.313 - // Before acting on a set of nodes that were previously outputted by a template function, we have to reconcile
1.314 - // them against what is in the DOM right now. It may be that some of the nodes have already been removed, or that
1.315 - // new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
1.316 - // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
1.317 - // So, this function translates the old "map" output array into its best guess of the set of current DOM nodes.
1.318 - //
1.319 - // Rules:
1.320 - // [A] Any leading nodes that have been removed should be ignored
1.321 - // These most likely correspond to memoization nodes that were already removed during binding
1.322 - // See https://github.com/SteveSanderson/knockout/pull/440
1.323 - // [B] We want to output a continuous series of nodes. So, ignore any nodes that have already been removed,
1.324 - // and include any nodes that have been inserted among the previous collection
1.325 -
1.326 - if (continuousNodeArray.length) {
1.327 - // The parent node can be a virtual element; so get the real parent node
1.328 - parentNode = (parentNode.nodeType === 8 && parentNode.parentNode) || parentNode;
1.329 -
1.330 - // Rule [A]
1.331 - while (continuousNodeArray.length && continuousNodeArray[0].parentNode !== parentNode)
1.332 - continuousNodeArray.shift();
1.333 -
1.334 - // Rule [B]
1.335 - if (continuousNodeArray.length > 1) {
1.336 - var current = continuousNodeArray[0], last = continuousNodeArray[continuousNodeArray.length - 1];
1.337 - // Replace with the actual new continuous node set
1.338 - continuousNodeArray.length = 0;
1.339 - while (current !== last) {
1.340 - continuousNodeArray.push(current);
1.341 - current = current.nextSibling;
1.342 - if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
1.343 - return;
1.344 - }
1.345 - continuousNodeArray.push(last);
1.346 - }
1.347 - }
1.348 - return continuousNodeArray;
1.349 - },
1.350 -
1.351 - setOptionNodeSelectionState: function (optionNode, isSelected) {
1.352 - // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
1.353 - if (ieVersion < 7)
1.354 - optionNode.setAttribute("selected", isSelected);
1.355 - else
1.356 - optionNode.selected = isSelected;
1.357 - },
1.358 -
1.359 - stringTrim: function (string) {
1.360 - return string === null || string === undefined ? '' :
1.361 - string.trim ?
1.362 - string.trim() :
1.363 - string.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
1.364 - },
1.365 -
1.366 - stringStartsWith: function (string, startsWith) {
1.367 - string = string || "";
1.368 - if (startsWith.length > string.length)
1.369 - return false;
1.370 - return string.substring(0, startsWith.length) === startsWith;
1.371 - },
1.372 -
1.373 - domNodeIsContainedBy: function (node, containedByNode) {
1.374 - if (node === containedByNode)
1.375 - return true;
1.376 - if (node.nodeType === 11)
1.377 - return false; // Fixes issue #1162 - can't use node.contains for document fragments on IE8
1.378 - if (containedByNode.contains)
1.379 - return containedByNode.contains(node.nodeType === 3 ? node.parentNode : node);
1.380 - if (containedByNode.compareDocumentPosition)
1.381 - return (containedByNode.compareDocumentPosition(node) & 16) == 16;
1.382 - while (node && node != containedByNode) {
1.383 - node = node.parentNode;
1.384 - }
1.385 - return !!node;
1.386 - },
1.387 -
1.388 - domNodeIsAttachedToDocument: function (node) {
1.389 - return ko.utils.domNodeIsContainedBy(node, node.ownerDocument.documentElement);
1.390 - },
1.391 -
1.392 - anyDomNodeIsAttachedToDocument: function(nodes) {
1.393 - return !!ko.utils.arrayFirst(nodes, ko.utils.domNodeIsAttachedToDocument);
1.394 - },
1.395 -
1.396 - tagNameLower: function(element) {
1.397 - // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
1.398 - // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
1.399 - // we don't need to do the .toLowerCase() as it will always be lower case anyway.
1.400 - return element && element.tagName && element.tagName.toLowerCase();
1.401 - },
1.402 -
1.403 - registerEventHandler: function (element, eventType, handler) {
1.404 - var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
1.405 - if (!mustUseAttachEvent && jQueryInstance) {
1.406 - jQueryInstance(element)['bind'](eventType, handler);
1.407 - } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
1.408 - element.addEventListener(eventType, handler, false);
1.409 - else if (typeof element.attachEvent != "undefined") {
1.410 - var attachEventHandler = function (event) { handler.call(element, event); },
1.411 - attachEventName = "on" + eventType;
1.412 - element.attachEvent(attachEventName, attachEventHandler);
1.413 -
1.414 - // IE does not dispose attachEvent handlers automatically (unlike with addEventListener)
1.415 - // so to avoid leaks, we have to remove them manually. See bug #856
1.416 - ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
1.417 - element.detachEvent(attachEventName, attachEventHandler);
1.418 - });
1.419 - } else
1.420 - throw new Error("Browser doesn't support addEventListener or attachEvent");
1.421 - },
1.422 -
1.423 - triggerEvent: function (element, eventType) {
1.424 - if (!(element && element.nodeType))
1.425 - throw new Error("element must be a DOM node when calling triggerEvent");
1.426 -
1.427 - // For click events on checkboxes and radio buttons, jQuery toggles the element checked state *after* the
1.428 - // event handler runs instead of *before*. (This was fixed in 1.9 for checkboxes but not for radio buttons.)
1.429 - // IE doesn't change the checked state when you trigger the click event using "fireEvent".
1.430 - // In both cases, we'll use the click method instead.
1.431 - var useClickWorkaround = isClickOnCheckableElement(element, eventType);
1.432 -
1.433 - if (jQueryInstance && !useClickWorkaround) {
1.434 - jQueryInstance(element)['trigger'](eventType);
1.435 - } else if (typeof document.createEvent == "function") {
1.436 - if (typeof element.dispatchEvent == "function") {
1.437 - var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
1.438 - var event = document.createEvent(eventCategory);
1.439 - event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
1.440 - element.dispatchEvent(event);
1.441 - }
1.442 - else
1.443 - throw new Error("The supplied element doesn't support dispatchEvent");
1.444 - } else if (useClickWorkaround && element.click) {
1.445 - element.click();
1.446 - } else if (typeof element.fireEvent != "undefined") {
1.447 - element.fireEvent("on" + eventType);
1.448 - } else {
1.449 - throw new Error("Browser doesn't support triggering events");
1.450 - }
1.451 - },
1.452 -
1.453 - unwrapObservable: function (value) {
1.454 - return ko.isObservable(value) ? value() : value;
1.455 - },
1.456 -
1.457 - peekObservable: function (value) {
1.458 - return ko.isObservable(value) ? value.peek() : value;
1.459 - },
1.460 -
1.461 - toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
1.462 - if (classNames) {
1.463 - var cssClassNameRegex = /\S+/g,
1.464 - currentClassNames = node.className.match(cssClassNameRegex) || [];
1.465 - ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
1.466 - ko.utils.addOrRemoveItem(currentClassNames, className, shouldHaveClass);
1.467 - });
1.468 - node.className = currentClassNames.join(" ");
1.469 - }
1.470 - },
1.471 -
1.472 - setTextContent: function(element, textContent) {
1.473 - var value = ko.utils.unwrapObservable(textContent);
1.474 - if ((value === null) || (value === undefined))
1.475 - value = "";
1.476 -
1.477 - // We need there to be exactly one child: a text node.
1.478 - // If there are no children, more than one, or if it's not a text node,
1.479 - // we'll clear everything and create a single text node.
1.480 - var innerTextNode = ko.virtualElements.firstChild(element);
1.481 - if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
1.482 - ko.virtualElements.setDomNodeChildren(element, [element.ownerDocument.createTextNode(value)]);
1.483 - } else {
1.484 - innerTextNode.data = value;
1.485 - }
1.486 -
1.487 - ko.utils.forceRefresh(element);
1.488 - },
1.489 -
1.490 - setElementName: function(element, name) {
1.491 - element.name = name;
1.492 -
1.493 - // Workaround IE 6/7 issue
1.494 - // - https://github.com/SteveSanderson/knockout/issues/197
1.495 - // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
1.496 - if (ieVersion <= 7) {
1.497 - try {
1.498 - element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
1.499 - }
1.500 - catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
1.501 - }
1.502 - },
1.503 -
1.504 - forceRefresh: function(node) {
1.505 - // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
1.506 - if (ieVersion >= 9) {
1.507 - // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
1.508 - var elem = node.nodeType == 1 ? node : node.parentNode;
1.509 - if (elem.style)
1.510 - elem.style.zoom = elem.style.zoom;
1.511 - }
1.512 - },
1.513 -
1.514 - ensureSelectElementIsRenderedCorrectly: function(selectElement) {
1.515 - // 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.516 - // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
1.517 - // Also fixes IE7 and IE8 bug that causes selects to be zero width if enclosed by 'if' or 'with'. (See issue #839)
1.518 - if (ieVersion) {
1.519 - var originalWidth = selectElement.style.width;
1.520 - selectElement.style.width = 0;
1.521 - selectElement.style.width = originalWidth;
1.522 - }
1.523 - },
1.524 -
1.525 - range: function (min, max) {
1.526 - min = ko.utils.unwrapObservable(min);
1.527 - max = ko.utils.unwrapObservable(max);
1.528 - var result = [];
1.529 - for (var i = min; i <= max; i++)
1.530 - result.push(i);
1.531 - return result;
1.532 - },
1.533 -
1.534 - makeArray: function(arrayLikeObject) {
1.535 - var result = [];
1.536 - for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
1.537 - result.push(arrayLikeObject[i]);
1.538 - };
1.539 - return result;
1.540 - },
1.541 -
1.542 - isIe6 : isIe6,
1.543 - isIe7 : isIe7,
1.544 - ieVersion : ieVersion,
1.545 -
1.546 - getFormFields: function(form, fieldName) {
1.547 - var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
1.548 - var isMatchingField = (typeof fieldName == 'string')
1.549 - ? function(field) { return field.name === fieldName }
1.550 - : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
1.551 - var matches = [];
1.552 - for (var i = fields.length - 1; i >= 0; i--) {
1.553 - if (isMatchingField(fields[i]))
1.554 - matches.push(fields[i]);
1.555 - };
1.556 - return matches;
1.557 - },
1.558 -
1.559 - parseJson: function (jsonString) {
1.560 - if (typeof jsonString == "string") {
1.561 - jsonString = ko.utils.stringTrim(jsonString);
1.562 - if (jsonString) {
1.563 - if (JSON && JSON.parse) // Use native parsing where available
1.564 - return JSON.parse(jsonString);
1.565 - return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
1.566 - }
1.567 - }
1.568 - return null;
1.569 - },
1.570 -
1.571 - stringifyJson: function (data, replacer, space) { // replacer and space are optional
1.572 - if (!JSON || !JSON.stringify)
1.573 - 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.574 - return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
1.575 - },
1.576 -
1.577 - postJson: function (urlOrForm, data, options) {
1.578 - options = options || {};
1.579 - var params = options['params'] || {};
1.580 - var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
1.581 - var url = urlOrForm;
1.582 -
1.583 - // If we were given a form, use its 'action' URL and pick out any requested field values
1.584 - if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
1.585 - var originalForm = urlOrForm;
1.586 - url = originalForm.action;
1.587 - for (var i = includeFields.length - 1; i >= 0; i--) {
1.588 - var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
1.589 - for (var j = fields.length - 1; j >= 0; j--)
1.590 - params[fields[j].name] = fields[j].value;
1.591 - }
1.592 - }
1.593 -
1.594 - data = ko.utils.unwrapObservable(data);
1.595 - var form = document.createElement("form");
1.596 - form.style.display = "none";
1.597 - form.action = url;
1.598 - form.method = "post";
1.599 - for (var key in data) {
1.600 - // Since 'data' this is a model object, we include all properties including those inherited from its prototype
1.601 - var input = document.createElement("input");
1.602 - input.type = "hidden";
1.603 - input.name = key;
1.604 - input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
1.605 - form.appendChild(input);
1.606 - }
1.607 - objectForEach(params, function(key, value) {
1.608 - var input = document.createElement("input");
1.609 - input.type = "hidden";
1.610 - input.name = key;
1.611 - input.value = value;
1.612 - form.appendChild(input);
1.613 - });
1.614 - document.body.appendChild(form);
1.615 - options['submitter'] ? options['submitter'](form) : form.submit();
1.616 - setTimeout(function () { form.parentNode.removeChild(form); }, 0);
1.617 - }
1.618 - }
1.619 -}());
1.620 -
1.621 -ko.exportSymbol('utils', ko.utils);
1.622 -ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
1.623 -ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
1.624 -ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
1.625 -ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
1.626 -ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
1.627 -ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
1.628 -ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
1.629 -ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
1.630 -ko.exportSymbol('utils.extend', ko.utils.extend);
1.631 -ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
1.632 -ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
1.633 -ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
1.634 -ko.exportSymbol('utils.postJson', ko.utils.postJson);
1.635 -ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
1.636 -ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
1.637 -ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
1.638 -ko.exportSymbol('utils.range', ko.utils.range);
1.639 -ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
1.640 -ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
1.641 -ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
1.642 -ko.exportSymbol('utils.objectForEach', ko.utils.objectForEach);
1.643 -ko.exportSymbol('utils.addOrRemoveItem', ko.utils.addOrRemoveItem);
1.644 -ko.exportSymbol('unwrap', ko.utils.unwrapObservable); // Convenient shorthand, because this is used so commonly
1.645 -
1.646 -if (!Function.prototype['bind']) {
1.647 - // 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.648 - // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
1.649 - Function.prototype['bind'] = function (object) {
1.650 - var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
1.651 - return function () {
1.652 - return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
1.653 - };
1.654 - };
1.655 -}
1.656 -
1.657 -ko.utils.domData = new (function () {
1.658 - var uniqueId = 0;
1.659 - var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
1.660 - var dataStore = {};
1.661 -
1.662 - function getAll(node, createIfNotFound) {
1.663 - var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
1.664 - var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
1.665 - if (!hasExistingDataStore) {
1.666 - if (!createIfNotFound)
1.667 - return undefined;
1.668 - dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
1.669 - dataStore[dataStoreKey] = {};
1.670 - }
1.671 - return dataStore[dataStoreKey];
1.672 - }
1.673 -
1.674 - return {
1.675 - get: function (node, key) {
1.676 - var allDataForNode = getAll(node, false);
1.677 - return allDataForNode === undefined ? undefined : allDataForNode[key];
1.678 - },
1.679 - set: function (node, key, value) {
1.680 - if (value === undefined) {
1.681 - // Make sure we don't actually create a new domData key if we are actually deleting a value
1.682 - if (getAll(node, false) === undefined)
1.683 - return;
1.684 - }
1.685 - var allDataForNode = getAll(node, true);
1.686 - allDataForNode[key] = value;
1.687 - },
1.688 - clear: function (node) {
1.689 - var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
1.690 - if (dataStoreKey) {
1.691 - delete dataStore[dataStoreKey];
1.692 - node[dataStoreKeyExpandoPropertyName] = null;
1.693 - return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
1.694 - }
1.695 - return false;
1.696 - },
1.697 -
1.698 - nextKey: function () {
1.699 - return (uniqueId++) + dataStoreKeyExpandoPropertyName;
1.700 - }
1.701 - };
1.702 -})();
1.703 -
1.704 -ko.exportSymbol('utils.domData', ko.utils.domData);
1.705 -ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
1.706 -
1.707 -ko.utils.domNodeDisposal = new (function () {
1.708 - var domDataKey = ko.utils.domData.nextKey();
1.709 - var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
1.710 - var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
1.711 -
1.712 - function getDisposeCallbacksCollection(node, createIfNotFound) {
1.713 - var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
1.714 - if ((allDisposeCallbacks === undefined) && createIfNotFound) {
1.715 - allDisposeCallbacks = [];
1.716 - ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
1.717 - }
1.718 - return allDisposeCallbacks;
1.719 - }
1.720 - function destroyCallbacksCollection(node) {
1.721 - ko.utils.domData.set(node, domDataKey, undefined);
1.722 - }
1.723 -
1.724 - function cleanSingleNode(node) {
1.725 - // Run all the dispose callbacks
1.726 - var callbacks = getDisposeCallbacksCollection(node, false);
1.727 - if (callbacks) {
1.728 - callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
1.729 - for (var i = 0; i < callbacks.length; i++)
1.730 - callbacks[i](node);
1.731 - }
1.732 -
1.733 - // Erase the DOM data
1.734 - ko.utils.domData.clear(node);
1.735 -
1.736 - // Perform cleanup needed by external libraries (currently only jQuery, but can be extended)
1.737 - ko.utils.domNodeDisposal["cleanExternalData"](node);
1.738 -
1.739 - // Clear any immediate-child comment nodes, as these wouldn't have been found by
1.740 - // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
1.741 - if (cleanableNodeTypesWithDescendants[node.nodeType])
1.742 - cleanImmediateCommentTypeChildren(node);
1.743 - }
1.744 -
1.745 - function cleanImmediateCommentTypeChildren(nodeWithChildren) {
1.746 - var child, nextChild = nodeWithChildren.firstChild;
1.747 - while (child = nextChild) {
1.748 - nextChild = child.nextSibling;
1.749 - if (child.nodeType === 8)
1.750 - cleanSingleNode(child);
1.751 - }
1.752 - }
1.753 -
1.754 - return {
1.755 - addDisposeCallback : function(node, callback) {
1.756 - if (typeof callback != "function")
1.757 - throw new Error("Callback must be a function");
1.758 - getDisposeCallbacksCollection(node, true).push(callback);
1.759 - },
1.760 -
1.761 - removeDisposeCallback : function(node, callback) {
1.762 - var callbacksCollection = getDisposeCallbacksCollection(node, false);
1.763 - if (callbacksCollection) {
1.764 - ko.utils.arrayRemoveItem(callbacksCollection, callback);
1.765 - if (callbacksCollection.length == 0)
1.766 - destroyCallbacksCollection(node);
1.767 - }
1.768 - },
1.769 -
1.770 - cleanNode : function(node) {
1.771 - // First clean this node, where applicable
1.772 - if (cleanableNodeTypes[node.nodeType]) {
1.773 - cleanSingleNode(node);
1.774 -
1.775 - // ... then its descendants, where applicable
1.776 - if (cleanableNodeTypesWithDescendants[node.nodeType]) {
1.777 - // Clone the descendants list in case it changes during iteration
1.778 - var descendants = [];
1.779 - ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
1.780 - for (var i = 0, j = descendants.length; i < j; i++)
1.781 - cleanSingleNode(descendants[i]);
1.782 - }
1.783 - }
1.784 - return node;
1.785 - },
1.786 -
1.787 - removeNode : function(node) {
1.788 - ko.cleanNode(node);
1.789 - if (node.parentNode)
1.790 - node.parentNode.removeChild(node);
1.791 - },
1.792 -
1.793 - "cleanExternalData" : function (node) {
1.794 - // Special support for jQuery here because it's so commonly used.
1.795 - // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
1.796 - // so notify it to tear down any resources associated with the node & descendants here.
1.797 - if (jQueryInstance && (typeof jQueryInstance['cleanData'] == "function"))
1.798 - jQueryInstance['cleanData']([node]);
1.799 - }
1.800 - }
1.801 -})();
1.802 -ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
1.803 -ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
1.804 -ko.exportSymbol('cleanNode', ko.cleanNode);
1.805 -ko.exportSymbol('removeNode', ko.removeNode);
1.806 -ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
1.807 -ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
1.808 -ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
1.809 -(function () {
1.810 - var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
1.811 -
1.812 - function simpleHtmlParse(html) {
1.813 - // Based on jQuery's "clean" function, but only accounting for table-related elements.
1.814 - // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
1.815 -
1.816 - // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
1.817 - // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
1.818 - // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
1.819 - // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
1.820 -
1.821 - // Trim whitespace, otherwise indexOf won't work as expected
1.822 - var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
1.823 -
1.824 - // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
1.825 - var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
1.826 - !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
1.827 - (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
1.828 - /* anything else */ [0, "", ""];
1.829 -
1.830 - // Go to html and back, then peel off extra wrappers
1.831 - // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
1.832 - var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
1.833 - if (typeof window['innerShiv'] == "function") {
1.834 - div.appendChild(window['innerShiv'](markup));
1.835 - } else {
1.836 - div.innerHTML = markup;
1.837 - }
1.838 -
1.839 - // Move to the right depth
1.840 - while (wrap[0]--)
1.841 - div = div.lastChild;
1.842 -
1.843 - return ko.utils.makeArray(div.lastChild.childNodes);
1.844 - }
1.845 -
1.846 - function jQueryHtmlParse(html) {
1.847 - // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
1.848 - if (jQueryInstance['parseHTML']) {
1.849 - return jQueryInstance['parseHTML'](html) || []; // Ensure we always return an array and never null
1.850 - } else {
1.851 - // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
1.852 - var elems = jQueryInstance['clean']([html]);
1.853 -
1.854 - // 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.855 - // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
1.856 - // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
1.857 - if (elems && elems[0]) {
1.858 - // Find the top-most parent element that's a direct child of a document fragment
1.859 - var elem = elems[0];
1.860 - while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
1.861 - elem = elem.parentNode;
1.862 - // ... then detach it
1.863 - if (elem.parentNode)
1.864 - elem.parentNode.removeChild(elem);
1.865 - }
1.866 -
1.867 - return elems;
1.868 - }
1.869 - }
1.870 -
1.871 - ko.utils.parseHtmlFragment = function(html) {
1.872 - return jQueryInstance ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
1.873 - : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
1.874 - };
1.875 -
1.876 - ko.utils.setHtml = function(node, html) {
1.877 - ko.utils.emptyDomNode(node);
1.878 -
1.879 - // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
1.880 - html = ko.utils.unwrapObservable(html);
1.881 -
1.882 - if ((html !== null) && (html !== undefined)) {
1.883 - if (typeof html != 'string')
1.884 - html = html.toString();
1.885 -
1.886 - // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
1.887 - // for example <tr> elements which are not normally allowed to exist on their own.
1.888 - // If you've referenced jQuery we'll use that rather than duplicating its code.
1.889 - if (jQueryInstance) {
1.890 - jQueryInstance(node)['html'](html);
1.891 - } else {
1.892 - // ... otherwise, use KO's own parsing logic.
1.893 - var parsedNodes = ko.utils.parseHtmlFragment(html);
1.894 - for (var i = 0; i < parsedNodes.length; i++)
1.895 - node.appendChild(parsedNodes[i]);
1.896 - }
1.897 - }
1.898 - };
1.899 -})();
1.900 -
1.901 -ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
1.902 -ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
1.903 -
1.904 -ko.memoization = (function () {
1.905 - var memos = {};
1.906 -
1.907 - function randomMax8HexChars() {
1.908 - return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
1.909 - }
1.910 - function generateRandomId() {
1.911 - return randomMax8HexChars() + randomMax8HexChars();
1.912 - }
1.913 - function findMemoNodes(rootNode, appendToArray) {
1.914 - if (!rootNode)
1.915 - return;
1.916 - if (rootNode.nodeType == 8) {
1.917 - var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
1.918 - if (memoId != null)
1.919 - appendToArray.push({ domNode: rootNode, memoId: memoId });
1.920 - } else if (rootNode.nodeType == 1) {
1.921 - for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
1.922 - findMemoNodes(childNodes[i], appendToArray);
1.923 - }
1.924 - }
1.925 -
1.926 - return {
1.927 - memoize: function (callback) {
1.928 - if (typeof callback != "function")
1.929 - throw new Error("You can only pass a function to ko.memoization.memoize()");
1.930 - var memoId = generateRandomId();
1.931 - memos[memoId] = callback;
1.932 - return "<!--[ko_memo:" + memoId + "]-->";
1.933 - },
1.934 -
1.935 - unmemoize: function (memoId, callbackParams) {
1.936 - var callback = memos[memoId];
1.937 - if (callback === undefined)
1.938 - throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
1.939 - try {
1.940 - callback.apply(null, callbackParams || []);
1.941 - return true;
1.942 - }
1.943 - finally { delete memos[memoId]; }
1.944 - },
1.945 -
1.946 - unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
1.947 - var memos = [];
1.948 - findMemoNodes(domNode, memos);
1.949 - for (var i = 0, j = memos.length; i < j; i++) {
1.950 - var node = memos[i].domNode;
1.951 - var combinedParams = [node];
1.952 - if (extraCallbackParamsArray)
1.953 - ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
1.954 - ko.memoization.unmemoize(memos[i].memoId, combinedParams);
1.955 - node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
1.956 - if (node.parentNode)
1.957 - 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.958 - }
1.959 - },
1.960 -
1.961 - parseMemoText: function (memoText) {
1.962 - var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
1.963 - return match ? match[1] : null;
1.964 - }
1.965 - };
1.966 -})();
1.967 -
1.968 -ko.exportSymbol('memoization', ko.memoization);
1.969 -ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
1.970 -ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
1.971 -ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
1.972 -ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
1.973 -ko.extenders = {
1.974 - 'throttle': function(target, timeout) {
1.975 - // Throttling means two things:
1.976 -
1.977 - // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
1.978 - // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
1.979 - target['throttleEvaluation'] = timeout;
1.980 -
1.981 - // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
1.982 - // so the target cannot change value synchronously or faster than a certain rate
1.983 - var writeTimeoutInstance = null;
1.984 - return ko.dependentObservable({
1.985 - 'read': target,
1.986 - 'write': function(value) {
1.987 - clearTimeout(writeTimeoutInstance);
1.988 - writeTimeoutInstance = setTimeout(function() {
1.989 - target(value);
1.990 - }, timeout);
1.991 - }
1.992 - });
1.993 - },
1.994 -
1.995 - 'rateLimit': function(target, options) {
1.996 - var timeout, method, limitFunction;
1.997 -
1.998 - if (typeof options == 'number') {
1.999 - timeout = options;
1.1000 - } else {
1.1001 - timeout = options['timeout'];
1.1002 - method = options['method'];
1.1003 - }
1.1004 -
1.1005 - limitFunction = method == 'notifyWhenChangesStop' ? debounce : throttle;
1.1006 - target.limit(function(callback) {
1.1007 - return limitFunction(callback, timeout);
1.1008 - });
1.1009 - },
1.1010 -
1.1011 - 'notify': function(target, notifyWhen) {
1.1012 - target["equalityComparer"] = notifyWhen == "always" ?
1.1013 - null : // null equalityComparer means to always notify
1.1014 - valuesArePrimitiveAndEqual;
1.1015 - }
1.1016 -};
1.1017 -
1.1018 -var primitiveTypes = { 'undefined':1, 'boolean':1, 'number':1, 'string':1 };
1.1019 -function valuesArePrimitiveAndEqual(a, b) {
1.1020 - var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
1.1021 - return oldValueIsPrimitive ? (a === b) : false;
1.1022 -}
1.1023 -
1.1024 -function throttle(callback, timeout) {
1.1025 - var timeoutInstance;
1.1026 - return function () {
1.1027 - if (!timeoutInstance) {
1.1028 - timeoutInstance = setTimeout(function() {
1.1029 - timeoutInstance = undefined;
1.1030 - callback();
1.1031 - }, timeout);
1.1032 - }
1.1033 - };
1.1034 -}
1.1035 -
1.1036 -function debounce(callback, timeout) {
1.1037 - var timeoutInstance;
1.1038 - return function () {
1.1039 - clearTimeout(timeoutInstance);
1.1040 - timeoutInstance = setTimeout(callback, timeout);
1.1041 - };
1.1042 -}
1.1043 -
1.1044 -function applyExtenders(requestedExtenders) {
1.1045 - var target = this;
1.1046 - if (requestedExtenders) {
1.1047 - ko.utils.objectForEach(requestedExtenders, function(key, value) {
1.1048 - var extenderHandler = ko.extenders[key];
1.1049 - if (typeof extenderHandler == 'function') {
1.1050 - target = extenderHandler(target, value) || target;
1.1051 - }
1.1052 - });
1.1053 - }
1.1054 - return target;
1.1055 -}
1.1056 -
1.1057 -ko.exportSymbol('extenders', ko.extenders);
1.1058 -
1.1059 -ko.subscription = function (target, callback, disposeCallback) {
1.1060 - this.target = target;
1.1061 - this.callback = callback;
1.1062 - this.disposeCallback = disposeCallback;
1.1063 - this.isDisposed = false;
1.1064 - ko.exportProperty(this, 'dispose', this.dispose);
1.1065 -};
1.1066 -ko.subscription.prototype.dispose = function () {
1.1067 - this.isDisposed = true;
1.1068 - this.disposeCallback();
1.1069 -};
1.1070 -
1.1071 -ko.subscribable = function () {
1.1072 - ko.utils.setPrototypeOfOrExtend(this, ko.subscribable['fn']);
1.1073 - this._subscriptions = {};
1.1074 -}
1.1075 -
1.1076 -var defaultEvent = "change";
1.1077 -
1.1078 -var ko_subscribable_fn = {
1.1079 - subscribe: function (callback, callbackTarget, event) {
1.1080 - var self = this;
1.1081 -
1.1082 - event = event || defaultEvent;
1.1083 - var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
1.1084 -
1.1085 - var subscription = new ko.subscription(self, boundCallback, function () {
1.1086 - ko.utils.arrayRemoveItem(self._subscriptions[event], subscription);
1.1087 - if (self.afterSubscriptionRemove)
1.1088 - self.afterSubscriptionRemove(event);
1.1089 - });
1.1090 -
1.1091 - if (self.beforeSubscriptionAdd)
1.1092 - self.beforeSubscriptionAdd(event);
1.1093 -
1.1094 - if (!self._subscriptions[event])
1.1095 - self._subscriptions[event] = [];
1.1096 - self._subscriptions[event].push(subscription);
1.1097 -
1.1098 - return subscription;
1.1099 - },
1.1100 -
1.1101 - "notifySubscribers": function (valueToNotify, event) {
1.1102 - event = event || defaultEvent;
1.1103 - if (this.hasSubscriptionsForEvent(event)) {
1.1104 - try {
1.1105 - ko.dependencyDetection.begin(); // Begin suppressing dependency detection (by setting the top frame to undefined)
1.1106 - for (var a = this._subscriptions[event].slice(0), i = 0, subscription; subscription = a[i]; ++i) {
1.1107 - // In case a subscription was disposed during the arrayForEach cycle, check
1.1108 - // for isDisposed on each subscription before invoking its callback
1.1109 - if (!subscription.isDisposed)
1.1110 - subscription.callback(valueToNotify);
1.1111 - }
1.1112 - } finally {
1.1113 - ko.dependencyDetection.end(); // End suppressing dependency detection
1.1114 - }
1.1115 - }
1.1116 - },
1.1117 -
1.1118 - limit: function(limitFunction) {
1.1119 - var self = this, selfIsObservable = ko.isObservable(self),
1.1120 - isPending, previousValue, pendingValue, beforeChange = 'beforeChange';
1.1121 -
1.1122 - if (!self._origNotifySubscribers) {
1.1123 - self._origNotifySubscribers = self["notifySubscribers"];
1.1124 - self["notifySubscribers"] = function(value, event) {
1.1125 - if (!event || event === defaultEvent) {
1.1126 - self._rateLimitedChange(value);
1.1127 - } else if (event === beforeChange) {
1.1128 - self._rateLimitedBeforeChange(value);
1.1129 - } else {
1.1130 - self._origNotifySubscribers(value, event);
1.1131 - }
1.1132 - };
1.1133 - }
1.1134 -
1.1135 - var finish = limitFunction(function() {
1.1136 - // If an observable provided a reference to itself, access it to get the latest value.
1.1137 - // This allows computed observables to delay calculating their value until needed.
1.1138 - if (selfIsObservable && pendingValue === self) {
1.1139 - pendingValue = self();
1.1140 - }
1.1141 - isPending = false;
1.1142 - if (self.isDifferent(previousValue, pendingValue)) {
1.1143 - self._origNotifySubscribers(previousValue = pendingValue);
1.1144 - }
1.1145 - });
1.1146 -
1.1147 - self._rateLimitedChange = function(value) {
1.1148 - isPending = true;
1.1149 - pendingValue = value;
1.1150 - finish();
1.1151 - };
1.1152 - self._rateLimitedBeforeChange = function(value) {
1.1153 - if (!isPending) {
1.1154 - previousValue = value;
1.1155 - self._origNotifySubscribers(value, beforeChange);
1.1156 - }
1.1157 - };
1.1158 - },
1.1159 -
1.1160 - hasSubscriptionsForEvent: function(event) {
1.1161 - return this._subscriptions[event] && this._subscriptions[event].length;
1.1162 - },
1.1163 -
1.1164 - getSubscriptionsCount: function () {
1.1165 - var total = 0;
1.1166 - ko.utils.objectForEach(this._subscriptions, function(eventName, subscriptions) {
1.1167 - total += subscriptions.length;
1.1168 - });
1.1169 - return total;
1.1170 - },
1.1171 -
1.1172 - isDifferent: function(oldValue, newValue) {
1.1173 - return !this['equalityComparer'] || !this['equalityComparer'](oldValue, newValue);
1.1174 - },
1.1175 -
1.1176 - extend: applyExtenders
1.1177 -};
1.1178 -
1.1179 -ko.exportProperty(ko_subscribable_fn, 'subscribe', ko_subscribable_fn.subscribe);
1.1180 -ko.exportProperty(ko_subscribable_fn, 'extend', ko_subscribable_fn.extend);
1.1181 -ko.exportProperty(ko_subscribable_fn, 'getSubscriptionsCount', ko_subscribable_fn.getSubscriptionsCount);
1.1182 -
1.1183 -// For browsers that support proto assignment, we overwrite the prototype of each
1.1184 -// observable instance. Since observables are functions, we need Function.prototype
1.1185 -// to still be in the prototype chain.
1.1186 -if (ko.utils.canSetPrototype) {
1.1187 - ko.utils.setPrototypeOf(ko_subscribable_fn, Function.prototype);
1.1188 -}
1.1189 -
1.1190 -ko.subscribable['fn'] = ko_subscribable_fn;
1.1191 -
1.1192 -
1.1193 -ko.isSubscribable = function (instance) {
1.1194 - return instance != null && typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
1.1195 -};
1.1196 -
1.1197 -ko.exportSymbol('subscribable', ko.subscribable);
1.1198 -ko.exportSymbol('isSubscribable', ko.isSubscribable);
1.1199 -
1.1200 -ko.computedContext = ko.dependencyDetection = (function () {
1.1201 - var outerFrames = [],
1.1202 - currentFrame,
1.1203 - lastId = 0;
1.1204 -
1.1205 - // Return a unique ID that can be assigned to an observable for dependency tracking.
1.1206 - // Theoretically, you could eventually overflow the number storage size, resulting
1.1207 - // in duplicate IDs. But in JavaScript, the largest exact integral value is 2^53
1.1208 - // or 9,007,199,254,740,992. If you created 1,000,000 IDs per second, it would
1.1209 - // take over 285 years to reach that number.
1.1210 - // Reference http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html
1.1211 - function getId() {
1.1212 - return ++lastId;
1.1213 - }
1.1214 -
1.1215 - function begin(options) {
1.1216 - outerFrames.push(currentFrame);
1.1217 - currentFrame = options;
1.1218 - }
1.1219 -
1.1220 - function end() {
1.1221 - currentFrame = outerFrames.pop();
1.1222 - }
1.1223 -
1.1224 - return {
1.1225 - begin: begin,
1.1226 -
1.1227 - end: end,
1.1228 -
1.1229 - registerDependency: function (subscribable) {
1.1230 - if (currentFrame) {
1.1231 - if (!ko.isSubscribable(subscribable))
1.1232 - throw new Error("Only subscribable things can act as dependencies");
1.1233 - currentFrame.callback(subscribable, subscribable._id || (subscribable._id = getId()));
1.1234 - }
1.1235 - },
1.1236 -
1.1237 - ignore: function (callback, callbackTarget, callbackArgs) {
1.1238 - try {
1.1239 - begin();
1.1240 - return callback.apply(callbackTarget, callbackArgs || []);
1.1241 - } finally {
1.1242 - end();
1.1243 - }
1.1244 - },
1.1245 -
1.1246 - getDependenciesCount: function () {
1.1247 - if (currentFrame)
1.1248 - return currentFrame.computed.getDependenciesCount();
1.1249 - },
1.1250 -
1.1251 - isInitial: function() {
1.1252 - if (currentFrame)
1.1253 - return currentFrame.isInitial;
1.1254 - }
1.1255 - };
1.1256 -})();
1.1257 -
1.1258 -ko.exportSymbol('computedContext', ko.computedContext);
1.1259 -ko.exportSymbol('computedContext.getDependenciesCount', ko.computedContext.getDependenciesCount);
1.1260 -ko.exportSymbol('computedContext.isInitial', ko.computedContext.isInitial);
1.1261 -ko.exportSymbol('computedContext.isSleeping', ko.computedContext.isSleeping);
1.1262 -ko.observable = function (initialValue) {
1.1263 - var _latestValue = initialValue;
1.1264 -
1.1265 - function observable() {
1.1266 - if (arguments.length > 0) {
1.1267 - // Write
1.1268 -
1.1269 - // Ignore writes if the value hasn't changed
1.1270 - if (observable.isDifferent(_latestValue, arguments[0])) {
1.1271 - observable.valueWillMutate();
1.1272 - _latestValue = arguments[0];
1.1273 - if (DEBUG) observable._latestValue = _latestValue;
1.1274 - observable.valueHasMutated();
1.1275 - }
1.1276 - return this; // Permits chained assignments
1.1277 - }
1.1278 - else {
1.1279 - // Read
1.1280 - ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
1.1281 - return _latestValue;
1.1282 - }
1.1283 - }
1.1284 - ko.subscribable.call(observable);
1.1285 - ko.utils.setPrototypeOfOrExtend(observable, ko.observable['fn']);
1.1286 -
1.1287 - if (DEBUG) observable._latestValue = _latestValue;
1.1288 - observable.peek = function() { return _latestValue };
1.1289 - observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
1.1290 - observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
1.1291 -
1.1292 - ko.exportProperty(observable, 'peek', observable.peek);
1.1293 - ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
1.1294 - ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
1.1295 -
1.1296 - return observable;
1.1297 -}
1.1298 -
1.1299 -ko.observable['fn'] = {
1.1300 - "equalityComparer": valuesArePrimitiveAndEqual
1.1301 -};
1.1302 -
1.1303 -var protoProperty = ko.observable.protoProperty = "__ko_proto__";
1.1304 -ko.observable['fn'][protoProperty] = ko.observable;
1.1305 -
1.1306 -// Note that for browsers that don't support proto assignment, the
1.1307 -// inheritance chain is created manually in the ko.observable constructor
1.1308 -if (ko.utils.canSetPrototype) {
1.1309 - ko.utils.setPrototypeOf(ko.observable['fn'], ko.subscribable['fn']);
1.1310 -}
1.1311 -
1.1312 -ko.hasPrototype = function(instance, prototype) {
1.1313 - if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
1.1314 - if (instance[protoProperty] === prototype) return true;
1.1315 - return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
1.1316 -};
1.1317 -
1.1318 -ko.isObservable = function (instance) {
1.1319 - return ko.hasPrototype(instance, ko.observable);
1.1320 -}
1.1321 -ko.isWriteableObservable = function (instance) {
1.1322 - // Observable
1.1323 - if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
1.1324 - return true;
1.1325 - // Writeable dependent observable
1.1326 - if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
1.1327 - return true;
1.1328 - // Anything else
1.1329 - return false;
1.1330 -}
1.1331 -
1.1332 -
1.1333 -ko.exportSymbol('observable', ko.observable);
1.1334 -ko.exportSymbol('isObservable', ko.isObservable);
1.1335 -ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
1.1336 -ko.exportSymbol('isWritableObservable', ko.isWriteableObservable);
1.1337 -ko.observableArray = function (initialValues) {
1.1338 - initialValues = initialValues || [];
1.1339 -
1.1340 - if (typeof initialValues != 'object' || !('length' in initialValues))
1.1341 - throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
1.1342 -
1.1343 - var result = ko.observable(initialValues);
1.1344 - ko.utils.setPrototypeOfOrExtend(result, ko.observableArray['fn']);
1.1345 - return result.extend({'trackArrayChanges':true});
1.1346 -};
1.1347 -
1.1348 -ko.observableArray['fn'] = {
1.1349 - 'remove': function (valueOrPredicate) {
1.1350 - var underlyingArray = this.peek();
1.1351 - var removedValues = [];
1.1352 - var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
1.1353 - for (var i = 0; i < underlyingArray.length; i++) {
1.1354 - var value = underlyingArray[i];
1.1355 - if (predicate(value)) {
1.1356 - if (removedValues.length === 0) {
1.1357 - this.valueWillMutate();
1.1358 - }
1.1359 - removedValues.push(value);
1.1360 - underlyingArray.splice(i, 1);
1.1361 - i--;
1.1362 - }
1.1363 - }
1.1364 - if (removedValues.length) {
1.1365 - this.valueHasMutated();
1.1366 - }
1.1367 - return removedValues;
1.1368 - },
1.1369 -
1.1370 - 'removeAll': function (arrayOfValues) {
1.1371 - // If you passed zero args, we remove everything
1.1372 - if (arrayOfValues === undefined) {
1.1373 - var underlyingArray = this.peek();
1.1374 - var allValues = underlyingArray.slice(0);
1.1375 - this.valueWillMutate();
1.1376 - underlyingArray.splice(0, underlyingArray.length);
1.1377 - this.valueHasMutated();
1.1378 - return allValues;
1.1379 - }
1.1380 - // If you passed an arg, we interpret it as an array of entries to remove
1.1381 - if (!arrayOfValues)
1.1382 - return [];
1.1383 - return this['remove'](function (value) {
1.1384 - return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
1.1385 - });
1.1386 - },
1.1387 -
1.1388 - 'destroy': function (valueOrPredicate) {
1.1389 - var underlyingArray = this.peek();
1.1390 - var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
1.1391 - this.valueWillMutate();
1.1392 - for (var i = underlyingArray.length - 1; i >= 0; i--) {
1.1393 - var value = underlyingArray[i];
1.1394 - if (predicate(value))
1.1395 - underlyingArray[i]["_destroy"] = true;
1.1396 - }
1.1397 - this.valueHasMutated();
1.1398 - },
1.1399 -
1.1400 - 'destroyAll': function (arrayOfValues) {
1.1401 - // If you passed zero args, we destroy everything
1.1402 - if (arrayOfValues === undefined)
1.1403 - return this['destroy'](function() { return true });
1.1404 -
1.1405 - // If you passed an arg, we interpret it as an array of entries to destroy
1.1406 - if (!arrayOfValues)
1.1407 - return [];
1.1408 - return this['destroy'](function (value) {
1.1409 - return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
1.1410 - });
1.1411 - },
1.1412 -
1.1413 - 'indexOf': function (item) {
1.1414 - var underlyingArray = this();
1.1415 - return ko.utils.arrayIndexOf(underlyingArray, item);
1.1416 - },
1.1417 -
1.1418 - 'replace': function(oldItem, newItem) {
1.1419 - var index = this['indexOf'](oldItem);
1.1420 - if (index >= 0) {
1.1421 - this.valueWillMutate();
1.1422 - this.peek()[index] = newItem;
1.1423 - this.valueHasMutated();
1.1424 - }
1.1425 - }
1.1426 -};
1.1427 -
1.1428 -// Populate ko.observableArray.fn with read/write functions from native arrays
1.1429 -// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
1.1430 -// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
1.1431 -ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
1.1432 - ko.observableArray['fn'][methodName] = function () {
1.1433 - // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
1.1434 - // (for consistency with mutating regular observables)
1.1435 - var underlyingArray = this.peek();
1.1436 - this.valueWillMutate();
1.1437 - this.cacheDiffForKnownOperation(underlyingArray, methodName, arguments);
1.1438 - var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
1.1439 - this.valueHasMutated();
1.1440 - return methodCallResult;
1.1441 - };
1.1442 -});
1.1443 -
1.1444 -// Populate ko.observableArray.fn with read-only functions from native arrays
1.1445 -ko.utils.arrayForEach(["slice"], function (methodName) {
1.1446 - ko.observableArray['fn'][methodName] = function () {
1.1447 - var underlyingArray = this();
1.1448 - return underlyingArray[methodName].apply(underlyingArray, arguments);
1.1449 - };
1.1450 -});
1.1451 -
1.1452 -// Note that for browsers that don't support proto assignment, the
1.1453 -// inheritance chain is created manually in the ko.observableArray constructor
1.1454 -if (ko.utils.canSetPrototype) {
1.1455 - ko.utils.setPrototypeOf(ko.observableArray['fn'], ko.observable['fn']);
1.1456 -}
1.1457 -
1.1458 -ko.exportSymbol('observableArray', ko.observableArray);
1.1459 -var arrayChangeEventName = 'arrayChange';
1.1460 -ko.extenders['trackArrayChanges'] = function(target) {
1.1461 - // Only modify the target observable once
1.1462 - if (target.cacheDiffForKnownOperation) {
1.1463 - return;
1.1464 - }
1.1465 - var trackingChanges = false,
1.1466 - cachedDiff = null,
1.1467 - pendingNotifications = 0,
1.1468 - underlyingSubscribeFunction = target.subscribe;
1.1469 -
1.1470 - // Intercept "subscribe" calls, and for array change events, ensure change tracking is enabled
1.1471 - target.subscribe = target['subscribe'] = function(callback, callbackTarget, event) {
1.1472 - if (event === arrayChangeEventName) {
1.1473 - trackChanges();
1.1474 - }
1.1475 - return underlyingSubscribeFunction.apply(this, arguments);
1.1476 - };
1.1477 -
1.1478 - function trackChanges() {
1.1479 - // Calling 'trackChanges' multiple times is the same as calling it once
1.1480 - if (trackingChanges) {
1.1481 - return;
1.1482 - }
1.1483 -
1.1484 - trackingChanges = true;
1.1485 -
1.1486 - // Intercept "notifySubscribers" to track how many times it was called.
1.1487 - var underlyingNotifySubscribersFunction = target['notifySubscribers'];
1.1488 - target['notifySubscribers'] = function(valueToNotify, event) {
1.1489 - if (!event || event === defaultEvent) {
1.1490 - ++pendingNotifications;
1.1491 - }
1.1492 - return underlyingNotifySubscribersFunction.apply(this, arguments);
1.1493 - };
1.1494 -
1.1495 - // Each time the array changes value, capture a clone so that on the next
1.1496 - // change it's possible to produce a diff
1.1497 - var previousContents = [].concat(target.peek() || []);
1.1498 - cachedDiff = null;
1.1499 - target.subscribe(function(currentContents) {
1.1500 - // Make a copy of the current contents and ensure it's an array
1.1501 - currentContents = [].concat(currentContents || []);
1.1502 -
1.1503 - // Compute the diff and issue notifications, but only if someone is listening
1.1504 - if (target.hasSubscriptionsForEvent(arrayChangeEventName)) {
1.1505 - var changes = getChanges(previousContents, currentContents);
1.1506 - if (changes.length) {
1.1507 - target['notifySubscribers'](changes, arrayChangeEventName);
1.1508 - }
1.1509 - }
1.1510 -
1.1511 - // Eliminate references to the old, removed items, so they can be GCed
1.1512 - previousContents = currentContents;
1.1513 - cachedDiff = null;
1.1514 - pendingNotifications = 0;
1.1515 - });
1.1516 - }
1.1517 -
1.1518 - function getChanges(previousContents, currentContents) {
1.1519 - // We try to re-use cached diffs.
1.1520 - // The scenarios where pendingNotifications > 1 are when using rate-limiting or the Deferred Updates
1.1521 - // plugin, which without this check would not be compatible with arrayChange notifications. Normally,
1.1522 - // notifications are issued immediately so we wouldn't be queueing up more than one.
1.1523 - if (!cachedDiff || pendingNotifications > 1) {
1.1524 - cachedDiff = ko.utils.compareArrays(previousContents, currentContents, { 'sparse': true });
1.1525 - }
1.1526 -
1.1527 - return cachedDiff;
1.1528 - }
1.1529 -
1.1530 - target.cacheDiffForKnownOperation = function(rawArray, operationName, args) {
1.1531 - // Only run if we're currently tracking changes for this observable array
1.1532 - // and there aren't any pending deferred notifications.
1.1533 - if (!trackingChanges || pendingNotifications) {
1.1534 - return;
1.1535 - }
1.1536 - var diff = [],
1.1537 - arrayLength = rawArray.length,
1.1538 - argsLength = args.length,
1.1539 - offset = 0;
1.1540 -
1.1541 - function pushDiff(status, value, index) {
1.1542 - return diff[diff.length] = { 'status': status, 'value': value, 'index': index };
1.1543 - }
1.1544 - switch (operationName) {
1.1545 - case 'push':
1.1546 - offset = arrayLength;
1.1547 - case 'unshift':
1.1548 - for (var index = 0; index < argsLength; index++) {
1.1549 - pushDiff('added', args[index], offset + index);
1.1550 - }
1.1551 - break;
1.1552 -
1.1553 - case 'pop':
1.1554 - offset = arrayLength - 1;
1.1555 - case 'shift':
1.1556 - if (arrayLength) {
1.1557 - pushDiff('deleted', rawArray[offset], offset);
1.1558 - }
1.1559 - break;
1.1560 -
1.1561 - case 'splice':
1.1562 - // Negative start index means 'from end of array'. After that we clamp to [0...arrayLength].
1.1563 - // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
1.1564 - var startIndex = Math.min(Math.max(0, args[0] < 0 ? arrayLength + args[0] : args[0]), arrayLength),
1.1565 - endDeleteIndex = argsLength === 1 ? arrayLength : Math.min(startIndex + (args[1] || 0), arrayLength),
1.1566 - endAddIndex = startIndex + argsLength - 2,
1.1567 - endIndex = Math.max(endDeleteIndex, endAddIndex),
1.1568 - additions = [], deletions = [];
1.1569 - for (var index = startIndex, argsIndex = 2; index < endIndex; ++index, ++argsIndex) {
1.1570 - if (index < endDeleteIndex)
1.1571 - deletions.push(pushDiff('deleted', rawArray[index], index));
1.1572 - if (index < endAddIndex)
1.1573 - additions.push(pushDiff('added', args[argsIndex], index));
1.1574 - }
1.1575 - ko.utils.findMovesInArrayComparison(deletions, additions);
1.1576 - break;
1.1577 -
1.1578 - default:
1.1579 - return;
1.1580 - }
1.1581 - cachedDiff = diff;
1.1582 - };
1.1583 -};
1.1584 -ko.computed = ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
1.1585 - var _latestValue,
1.1586 - _needsEvaluation = true,
1.1587 - _isBeingEvaluated = false,
1.1588 - _suppressDisposalUntilDisposeWhenReturnsFalse = false,
1.1589 - _isDisposed = false,
1.1590 - readFunction = evaluatorFunctionOrOptions,
1.1591 - pure = false,
1.1592 - isSleeping = false;
1.1593 -
1.1594 - if (readFunction && typeof readFunction == "object") {
1.1595 - // Single-parameter syntax - everything is on this "options" param
1.1596 - options = readFunction;
1.1597 - readFunction = options["read"];
1.1598 - } else {
1.1599 - // Multi-parameter syntax - construct the options according to the params passed
1.1600 - options = options || {};
1.1601 - if (!readFunction)
1.1602 - readFunction = options["read"];
1.1603 - }
1.1604 - if (typeof readFunction != "function")
1.1605 - throw new Error("Pass a function that returns the value of the ko.computed");
1.1606 -
1.1607 - function addSubscriptionToDependency(subscribable, id) {
1.1608 - if (!_subscriptionsToDependencies[id]) {
1.1609 - _subscriptionsToDependencies[id] = subscribable.subscribe(evaluatePossiblyAsync);
1.1610 - ++_dependenciesCount;
1.1611 - }
1.1612 - }
1.1613 -
1.1614 - function disposeAllSubscriptionsToDependencies() {
1.1615 - ko.utils.objectForEach(_subscriptionsToDependencies, function (id, subscription) {
1.1616 - subscription.dispose();
1.1617 - });
1.1618 - _subscriptionsToDependencies = {};
1.1619 - }
1.1620 -
1.1621 - function disposeComputed() {
1.1622 - disposeAllSubscriptionsToDependencies();
1.1623 - _dependenciesCount = 0;
1.1624 - _isDisposed = true;
1.1625 - _needsEvaluation = false;
1.1626 - }
1.1627 -
1.1628 - function evaluatePossiblyAsync() {
1.1629 - var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
1.1630 - if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
1.1631 - clearTimeout(evaluationTimeoutInstance);
1.1632 - evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
1.1633 - } else if (dependentObservable._evalRateLimited) {
1.1634 - dependentObservable._evalRateLimited();
1.1635 - } else {
1.1636 - evaluateImmediate();
1.1637 - }
1.1638 - }
1.1639 -
1.1640 - function evaluateImmediate(suppressChangeNotification) {
1.1641 - if (_isBeingEvaluated) {
1.1642 - if (pure) {
1.1643 - throw Error("A 'pure' computed must not be called recursively");
1.1644 - }
1.1645 - // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
1.1646 - // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
1.1647 - // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
1.1648 - // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
1.1649 - return;
1.1650 - }
1.1651 -
1.1652 - // Do not evaluate (and possibly capture new dependencies) if disposed
1.1653 - if (_isDisposed) {
1.1654 - return;
1.1655 - }
1.1656 -
1.1657 - if (disposeWhen && disposeWhen()) {
1.1658 - // See comment below about _suppressDisposalUntilDisposeWhenReturnsFalse
1.1659 - if (!_suppressDisposalUntilDisposeWhenReturnsFalse) {
1.1660 - dispose();
1.1661 - return;
1.1662 - }
1.1663 - } else {
1.1664 - // It just did return false, so we can stop suppressing now
1.1665 - _suppressDisposalUntilDisposeWhenReturnsFalse = false;
1.1666 - }
1.1667 -
1.1668 - _isBeingEvaluated = true;
1.1669 -
1.1670 - // When sleeping, recalculate the value and return.
1.1671 - if (isSleeping) {
1.1672 - try {
1.1673 - var dependencyTracking = {};
1.1674 - ko.dependencyDetection.begin({
1.1675 - callback: function (subscribable, id) {
1.1676 - if (!dependencyTracking[id]) {
1.1677 - dependencyTracking[id] = 1;
1.1678 - ++_dependenciesCount;
1.1679 - }
1.1680 - },
1.1681 - computed: dependentObservable,
1.1682 - isInitial: undefined
1.1683 - });
1.1684 - _dependenciesCount = 0;
1.1685 - _latestValue = readFunction.call(evaluatorFunctionTarget);
1.1686 - } finally {
1.1687 - ko.dependencyDetection.end();
1.1688 - _isBeingEvaluated = false;
1.1689 - }
1.1690 - } else {
1.1691 - try {
1.1692 - // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
1.1693 - // Then, during evaluation, we cross off any that are in fact still being used.
1.1694 - var disposalCandidates = _subscriptionsToDependencies, disposalCount = _dependenciesCount;
1.1695 - ko.dependencyDetection.begin({
1.1696 - callback: function(subscribable, id) {
1.1697 - if (!_isDisposed) {
1.1698 - if (disposalCount && disposalCandidates[id]) {
1.1699 - // Don't want to dispose this subscription, as it's still being used
1.1700 - _subscriptionsToDependencies[id] = disposalCandidates[id];
1.1701 - ++_dependenciesCount;
1.1702 - delete disposalCandidates[id];
1.1703 - --disposalCount;
1.1704 - } else {
1.1705 - // Brand new subscription - add it
1.1706 - addSubscriptionToDependency(subscribable, id);
1.1707 - }
1.1708 - }
1.1709 - },
1.1710 - computed: dependentObservable,
1.1711 - isInitial: pure ? undefined : !_dependenciesCount // If we're evaluating when there are no previous dependencies, it must be the first time
1.1712 - });
1.1713 -
1.1714 - _subscriptionsToDependencies = {};
1.1715 - _dependenciesCount = 0;
1.1716 -
1.1717 - try {
1.1718 - var newValue = evaluatorFunctionTarget ? readFunction.call(evaluatorFunctionTarget) : readFunction();
1.1719 -
1.1720 - } finally {
1.1721 - ko.dependencyDetection.end();
1.1722 -
1.1723 - // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
1.1724 - if (disposalCount) {
1.1725 - ko.utils.objectForEach(disposalCandidates, function(id, toDispose) {
1.1726 - toDispose.dispose();
1.1727 - });
1.1728 - }
1.1729 -
1.1730 - _needsEvaluation = false;
1.1731 - }
1.1732 -
1.1733 - if (dependentObservable.isDifferent(_latestValue, newValue)) {
1.1734 - dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
1.1735 -
1.1736 - _latestValue = newValue;
1.1737 - if (DEBUG) dependentObservable._latestValue = _latestValue;
1.1738 -
1.1739 - if (suppressChangeNotification !== true) { // Check for strict true value since setTimeout in Firefox passes a numeric value to the function
1.1740 - dependentObservable["notifySubscribers"](_latestValue);
1.1741 - }
1.1742 - }
1.1743 - } finally {
1.1744 - _isBeingEvaluated = false;
1.1745 - }
1.1746 - }
1.1747 -
1.1748 - if (!_dependenciesCount)
1.1749 - dispose();
1.1750 - }
1.1751 -
1.1752 - function dependentObservable() {
1.1753 - if (arguments.length > 0) {
1.1754 - if (typeof writeFunction === "function") {
1.1755 - // Writing a value
1.1756 - writeFunction.apply(evaluatorFunctionTarget, arguments);
1.1757 - } else {
1.1758 - 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.1759 - }
1.1760 - return this; // Permits chained assignments
1.1761 - } else {
1.1762 - // Reading the value
1.1763 - ko.dependencyDetection.registerDependency(dependentObservable);
1.1764 - if (_needsEvaluation)
1.1765 - evaluateImmediate(true /* suppressChangeNotification */);
1.1766 - return _latestValue;
1.1767 - }
1.1768 - }
1.1769 -
1.1770 - function peek() {
1.1771 - // Peek won't re-evaluate, except to get the initial value when "deferEvaluation" is set, or while the computed is sleeping.
1.1772 - // Those are the only times that both of these conditions will be satisfied.
1.1773 - if (_needsEvaluation && !_dependenciesCount)
1.1774 - evaluateImmediate(true /* suppressChangeNotification */);
1.1775 - return _latestValue;
1.1776 - }
1.1777 -
1.1778 - function isActive() {
1.1779 - return _needsEvaluation || _dependenciesCount > 0;
1.1780 - }
1.1781 -
1.1782 - // By here, "options" is always non-null
1.1783 - var writeFunction = options["write"],
1.1784 - disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
1.1785 - disposeWhenOption = options["disposeWhen"] || options.disposeWhen,
1.1786 - disposeWhen = disposeWhenOption,
1.1787 - dispose = disposeComputed,
1.1788 - _subscriptionsToDependencies = {},
1.1789 - _dependenciesCount = 0,
1.1790 - evaluationTimeoutInstance = null;
1.1791 -
1.1792 - if (!evaluatorFunctionTarget)
1.1793 - evaluatorFunctionTarget = options["owner"];
1.1794 -
1.1795 - ko.subscribable.call(dependentObservable);
1.1796 - ko.utils.setPrototypeOfOrExtend(dependentObservable, ko.dependentObservable['fn']);
1.1797 -
1.1798 - dependentObservable.peek = peek;
1.1799 - dependentObservable.getDependenciesCount = function () { return _dependenciesCount; };
1.1800 - dependentObservable.hasWriteFunction = typeof options["write"] === "function";
1.1801 - dependentObservable.dispose = function () { dispose(); };
1.1802 - dependentObservable.isActive = isActive;
1.1803 -
1.1804 - // Replace the limit function with one that delays evaluation as well.
1.1805 - var originalLimit = dependentObservable.limit;
1.1806 - dependentObservable.limit = function(limitFunction) {
1.1807 - originalLimit.call(dependentObservable, limitFunction);
1.1808 - dependentObservable._evalRateLimited = function() {
1.1809 - dependentObservable._rateLimitedBeforeChange(_latestValue);
1.1810 -
1.1811 - _needsEvaluation = true; // Mark as dirty
1.1812 -
1.1813 - // Pass the observable to the rate-limit code, which will access it when
1.1814 - // it's time to do the notification.
1.1815 - dependentObservable._rateLimitedChange(dependentObservable);
1.1816 - }
1.1817 - };
1.1818 -
1.1819 - if (options['pure']) {
1.1820 - pure = true;
1.1821 - isSleeping = true; // Starts off sleeping; will awake on the first subscription
1.1822 - dependentObservable.beforeSubscriptionAdd = function () {
1.1823 - // If asleep, wake up the computed and evaluate to register any dependencies.
1.1824 - if (isSleeping) {
1.1825 - isSleeping = false;
1.1826 - evaluateImmediate(true /* suppressChangeNotification */);
1.1827 - }
1.1828 - }
1.1829 - dependentObservable.afterSubscriptionRemove = function () {
1.1830 - if (!dependentObservable.getSubscriptionsCount()) {
1.1831 - disposeAllSubscriptionsToDependencies();
1.1832 - isSleeping = _needsEvaluation = true;
1.1833 - }
1.1834 - }
1.1835 - } else if (options['deferEvaluation']) {
1.1836 - // This will force a computed with deferEvaluation to evaluate when the first subscriptions is registered.
1.1837 - dependentObservable.beforeSubscriptionAdd = function () {
1.1838 - peek();
1.1839 - delete dependentObservable.beforeSubscriptionAdd;
1.1840 - }
1.1841 - }
1.1842 -
1.1843 - ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
1.1844 - ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
1.1845 - ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
1.1846 - ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
1.1847 -
1.1848 - // Add a "disposeWhen" callback that, on each evaluation, disposes if the node was removed without using ko.removeNode.
1.1849 - if (disposeWhenNodeIsRemoved) {
1.1850 - // Since this computed is associated with a DOM node, and we don't want to dispose the computed
1.1851 - // until the DOM node is *removed* from the document (as opposed to never having been in the document),
1.1852 - // we'll prevent disposal until "disposeWhen" first returns false.
1.1853 - _suppressDisposalUntilDisposeWhenReturnsFalse = true;
1.1854 -
1.1855 - // Only watch for the node's disposal if the value really is a node. It might not be,
1.1856 - // e.g., { disposeWhenNodeIsRemoved: true } can be used to opt into the "only dispose
1.1857 - // after first false result" behaviour even if there's no specific node to watch. This
1.1858 - // technique is intended for KO's internal use only and shouldn't be documented or used
1.1859 - // by application code, as it's likely to change in a future version of KO.
1.1860 - if (disposeWhenNodeIsRemoved.nodeType) {
1.1861 - disposeWhen = function () {
1.1862 - return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || (disposeWhenOption && disposeWhenOption());
1.1863 - };
1.1864 - }
1.1865 - }
1.1866 -
1.1867 - // Evaluate, unless sleeping or deferEvaluation is true
1.1868 - if (!isSleeping && !options['deferEvaluation'])
1.1869 - evaluateImmediate();
1.1870 -
1.1871 - // Attach a DOM node disposal callback so that the computed will be proactively disposed as soon as the node is
1.1872 - // removed using ko.removeNode. But skip if isActive is false (there will never be any dependencies to dispose).
1.1873 - if (disposeWhenNodeIsRemoved && isActive() && disposeWhenNodeIsRemoved.nodeType) {
1.1874 - dispose = function() {
1.1875 - ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, dispose);
1.1876 - disposeComputed();
1.1877 - };
1.1878 - ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
1.1879 - }
1.1880 -
1.1881 - return dependentObservable;
1.1882 -};
1.1883 -
1.1884 -ko.isComputed = function(instance) {
1.1885 - return ko.hasPrototype(instance, ko.dependentObservable);
1.1886 -};
1.1887 -
1.1888 -var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
1.1889 -ko.dependentObservable[protoProp] = ko.observable;
1.1890 -
1.1891 -ko.dependentObservable['fn'] = {
1.1892 - "equalityComparer": valuesArePrimitiveAndEqual
1.1893 -};
1.1894 -ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
1.1895 -
1.1896 -// Note that for browsers that don't support proto assignment, the
1.1897 -// inheritance chain is created manually in the ko.dependentObservable constructor
1.1898 -if (ko.utils.canSetPrototype) {
1.1899 - ko.utils.setPrototypeOf(ko.dependentObservable['fn'], ko.subscribable['fn']);
1.1900 -}
1.1901 -
1.1902 -ko.exportSymbol('dependentObservable', ko.dependentObservable);
1.1903 -ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
1.1904 -ko.exportSymbol('isComputed', ko.isComputed);
1.1905 -
1.1906 -ko.pureComputed = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget) {
1.1907 - if (typeof evaluatorFunctionOrOptions === 'function') {
1.1908 - return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget, {'pure':true});
1.1909 - } else {
1.1910 - evaluatorFunctionOrOptions = ko.utils.extend({}, evaluatorFunctionOrOptions); // make a copy of the parameter object
1.1911 - evaluatorFunctionOrOptions['pure'] = true;
1.1912 - return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget);
1.1913 - }
1.1914 -}
1.1915 -ko.exportSymbol('pureComputed', ko.pureComputed);
1.1916 -
1.1917 -(function() {
1.1918 - var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
1.1919 -
1.1920 - ko.toJS = function(rootObject) {
1.1921 - if (arguments.length == 0)
1.1922 - throw new Error("When calling ko.toJS, pass the object you want to convert.");
1.1923 -
1.1924 - // We just unwrap everything at every level in the object graph
1.1925 - return mapJsObjectGraph(rootObject, function(valueToMap) {
1.1926 - // Loop because an observable's value might in turn be another observable wrapper
1.1927 - for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
1.1928 - valueToMap = valueToMap();
1.1929 - return valueToMap;
1.1930 - });
1.1931 - };
1.1932 -
1.1933 - ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
1.1934 - var plainJavaScriptObject = ko.toJS(rootObject);
1.1935 - return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
1.1936 - };
1.1937 -
1.1938 - function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
1.1939 - visitedObjects = visitedObjects || new objectLookup();
1.1940 -
1.1941 - rootObject = mapInputCallback(rootObject);
1.1942 - var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date)) && (!(rootObject instanceof String)) && (!(rootObject instanceof Number)) && (!(rootObject instanceof Boolean));
1.1943 - if (!canHaveProperties)
1.1944 - return rootObject;
1.1945 -
1.1946 - var outputProperties = rootObject instanceof Array ? [] : {};
1.1947 - visitedObjects.save(rootObject, outputProperties);
1.1948 -
1.1949 - visitPropertiesOrArrayEntries(rootObject, function(indexer) {
1.1950 - var propertyValue = mapInputCallback(rootObject[indexer]);
1.1951 -
1.1952 - switch (typeof propertyValue) {
1.1953 - case "boolean":
1.1954 - case "number":
1.1955 - case "string":
1.1956 - case "function":
1.1957 - outputProperties[indexer] = propertyValue;
1.1958 - break;
1.1959 - case "object":
1.1960 - case "undefined":
1.1961 - var previouslyMappedValue = visitedObjects.get(propertyValue);
1.1962 - outputProperties[indexer] = (previouslyMappedValue !== undefined)
1.1963 - ? previouslyMappedValue
1.1964 - : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
1.1965 - break;
1.1966 - }
1.1967 - });
1.1968 -
1.1969 - return outputProperties;
1.1970 - }
1.1971 -
1.1972 - function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
1.1973 - if (rootObject instanceof Array) {
1.1974 - for (var i = 0; i < rootObject.length; i++)
1.1975 - visitorCallback(i);
1.1976 -
1.1977 - // For arrays, also respect toJSON property for custom mappings (fixes #278)
1.1978 - if (typeof rootObject['toJSON'] == 'function')
1.1979 - visitorCallback('toJSON');
1.1980 - } else {
1.1981 - for (var propertyName in rootObject) {
1.1982 - visitorCallback(propertyName);
1.1983 - }
1.1984 - }
1.1985 - };
1.1986 -
1.1987 - function objectLookup() {
1.1988 - this.keys = [];
1.1989 - this.values = [];
1.1990 - };
1.1991 -
1.1992 - objectLookup.prototype = {
1.1993 - constructor: objectLookup,
1.1994 - save: function(key, value) {
1.1995 - var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
1.1996 - if (existingIndex >= 0)
1.1997 - this.values[existingIndex] = value;
1.1998 - else {
1.1999 - this.keys.push(key);
1.2000 - this.values.push(value);
1.2001 - }
1.2002 - },
1.2003 - get: function(key) {
1.2004 - var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
1.2005 - return (existingIndex >= 0) ? this.values[existingIndex] : undefined;
1.2006 - }
1.2007 - };
1.2008 -})();
1.2009 -
1.2010 -ko.exportSymbol('toJS', ko.toJS);
1.2011 -ko.exportSymbol('toJSON', ko.toJSON);
1.2012 -(function () {
1.2013 - var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
1.2014 -
1.2015 - // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
1.2016 - // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
1.2017 - // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
1.2018 - ko.selectExtensions = {
1.2019 - readValue : function(element) {
1.2020 - switch (ko.utils.tagNameLower(element)) {
1.2021 - case 'option':
1.2022 - if (element[hasDomDataExpandoProperty] === true)
1.2023 - return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
1.2024 - return ko.utils.ieVersion <= 7
1.2025 - ? (element.getAttributeNode('value') && element.getAttributeNode('value').specified ? element.value : element.text)
1.2026 - : element.value;
1.2027 - case 'select':
1.2028 - return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
1.2029 - default:
1.2030 - return element.value;
1.2031 - }
1.2032 - },
1.2033 -
1.2034 - writeValue: function(element, value, allowUnset) {
1.2035 - switch (ko.utils.tagNameLower(element)) {
1.2036 - case 'option':
1.2037 - switch(typeof value) {
1.2038 - case "string":
1.2039 - ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
1.2040 - if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
1.2041 - delete element[hasDomDataExpandoProperty];
1.2042 - }
1.2043 - element.value = value;
1.2044 - break;
1.2045 - default:
1.2046 - // Store arbitrary object using DomData
1.2047 - ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
1.2048 - element[hasDomDataExpandoProperty] = true;
1.2049 -
1.2050 - // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
1.2051 - element.value = typeof value === "number" ? value : "";
1.2052 - break;
1.2053 - }
1.2054 - break;
1.2055 - case 'select':
1.2056 - if (value === "" || value === null) // A blank string or null value will select the caption
1.2057 - value = undefined;
1.2058 - var selection = -1;
1.2059 - for (var i = 0, n = element.options.length, optionValue; i < n; ++i) {
1.2060 - optionValue = ko.selectExtensions.readValue(element.options[i]);
1.2061 - // Include special check to handle selecting a caption with a blank string value
1.2062 - if (optionValue == value || (optionValue == "" && value === undefined)) {
1.2063 - selection = i;
1.2064 - break;
1.2065 - }
1.2066 - }
1.2067 - if (allowUnset || selection >= 0 || (value === undefined && element.size > 1)) {
1.2068 - element.selectedIndex = selection;
1.2069 - }
1.2070 - break;
1.2071 - default:
1.2072 - if ((value === null) || (value === undefined))
1.2073 - value = "";
1.2074 - element.value = value;
1.2075 - break;
1.2076 - }
1.2077 - }
1.2078 - };
1.2079 -})();
1.2080 -
1.2081 -ko.exportSymbol('selectExtensions', ko.selectExtensions);
1.2082 -ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
1.2083 -ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
1.2084 -ko.expressionRewriting = (function () {
1.2085 - var javaScriptReservedWords = ["true", "false", "null", "undefined"];
1.2086 -
1.2087 - // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
1.2088 - // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
1.2089 - // This also will not properly handle nested brackets (e.g., obj1[obj2['prop']]; see #911).
1.2090 - var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
1.2091 -
1.2092 - function getWriteableValue(expression) {
1.2093 - if (ko.utils.arrayIndexOf(javaScriptReservedWords, expression) >= 0)
1.2094 - return false;
1.2095 - var match = expression.match(javaScriptAssignmentTarget);
1.2096 - return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
1.2097 - }
1.2098 -
1.2099 - // The following regular expressions will be used to split an object-literal string into tokens
1.2100 -
1.2101 - // These two match strings, either with double quotes or single quotes
1.2102 - var stringDouble = '"(?:[^"\\\\]|\\\\.)*"',
1.2103 - stringSingle = "'(?:[^'\\\\]|\\\\.)*'",
1.2104 - // Matches a regular expression (text enclosed by slashes), but will also match sets of divisions
1.2105 - // as a regular expression (this is handled by the parsing loop below).
1.2106 - stringRegexp = '/(?:[^/\\\\]|\\\\.)*/\w*',
1.2107 - // These characters have special meaning to the parser and must not appear in the middle of a
1.2108 - // token, except as part of a string.
1.2109 - specials = ',"\'{}()/:[\\]',
1.2110 - // Match text (at least two characters) that does not contain any of the above special characters,
1.2111 - // although some of the special characters are allowed to start it (all but the colon and comma).
1.2112 - // The text can contain spaces, but leading or trailing spaces are skipped.
1.2113 - everyThingElse = '[^\\s:,/][^' + specials + ']*[^\\s' + specials + ']',
1.2114 - // Match any non-space character not matched already. This will match colons and commas, since they're
1.2115 - // not matched by "everyThingElse", but will also match any other single character that wasn't already
1.2116 - // matched (for example: in "a: 1, b: 2", each of the non-space characters will be matched by oneNotSpace).
1.2117 - oneNotSpace = '[^\\s]',
1.2118 -
1.2119 - // Create the actual regular expression by or-ing the above strings. The order is important.
1.2120 - bindingToken = RegExp(stringDouble + '|' + stringSingle + '|' + stringRegexp + '|' + everyThingElse + '|' + oneNotSpace, 'g'),
1.2121 -
1.2122 - // Match end of previous token to determine whether a slash is a division or regex.
1.2123 - divisionLookBehind = /[\])"'A-Za-z0-9_$]+$/,
1.2124 - keywordRegexLookBehind = {'in':1,'return':1,'typeof':1};
1.2125 -
1.2126 - function parseObjectLiteral(objectLiteralString) {
1.2127 - // Trim leading and trailing spaces from the string
1.2128 - var str = ko.utils.stringTrim(objectLiteralString);
1.2129 -
1.2130 - // Trim braces '{' surrounding the whole object literal
1.2131 - if (str.charCodeAt(0) === 123) str = str.slice(1, -1);
1.2132 -
1.2133 - // Split into tokens
1.2134 - var result = [], toks = str.match(bindingToken), key, values, depth = 0;
1.2135 -
1.2136 - if (toks) {
1.2137 - // Append a comma so that we don't need a separate code block to deal with the last item
1.2138 - toks.push(',');
1.2139 -
1.2140 - for (var i = 0, tok; tok = toks[i]; ++i) {
1.2141 - var c = tok.charCodeAt(0);
1.2142 - // A comma signals the end of a key/value pair if depth is zero
1.2143 - if (c === 44) { // ","
1.2144 - if (depth <= 0) {
1.2145 - if (key)
1.2146 - result.push(values ? {key: key, value: values.join('')} : {'unknown': key});
1.2147 - key = values = depth = 0;
1.2148 - continue;
1.2149 - }
1.2150 - // Simply skip the colon that separates the name and value
1.2151 - } else if (c === 58) { // ":"
1.2152 - if (!values)
1.2153 - continue;
1.2154 - // A set of slashes is initially matched as a regular expression, but could be division
1.2155 - } else if (c === 47 && i && tok.length > 1) { // "/"
1.2156 - // Look at the end of the previous token to determine if the slash is actually division
1.2157 - var match = toks[i-1].match(divisionLookBehind);
1.2158 - if (match && !keywordRegexLookBehind[match[0]]) {
1.2159 - // The slash is actually a division punctuator; re-parse the remainder of the string (not including the slash)
1.2160 - str = str.substr(str.indexOf(tok) + 1);
1.2161 - toks = str.match(bindingToken);
1.2162 - toks.push(',');
1.2163 - i = -1;
1.2164 - // Continue with just the slash
1.2165 - tok = '/';
1.2166 - }
1.2167 - // Increment depth for parentheses, braces, and brackets so that interior commas are ignored
1.2168 - } else if (c === 40 || c === 123 || c === 91) { // '(', '{', '['
1.2169 - ++depth;
1.2170 - } else if (c === 41 || c === 125 || c === 93) { // ')', '}', ']'
1.2171 - --depth;
1.2172 - // The key must be a single token; if it's a string, trim the quotes
1.2173 - } else if (!key && !values) {
1.2174 - key = (c === 34 || c === 39) /* '"', "'" */ ? tok.slice(1, -1) : tok;
1.2175 - continue;
1.2176 - }
1.2177 - if (values)
1.2178 - values.push(tok);
1.2179 - else
1.2180 - values = [tok];
1.2181 - }
1.2182 - }
1.2183 - return result;
1.2184 - }
1.2185 -
1.2186 - // Two-way bindings include a write function that allow the handler to update the value even if it's not an observable.
1.2187 - var twoWayBindings = {};
1.2188 -
1.2189 - function preProcessBindings(bindingsStringOrKeyValueArray, bindingOptions) {
1.2190 - bindingOptions = bindingOptions || {};
1.2191 -
1.2192 - function processKeyValue(key, val) {
1.2193 - var writableVal;
1.2194 - function callPreprocessHook(obj) {
1.2195 - return (obj && obj['preprocess']) ? (val = obj['preprocess'](val, key, processKeyValue)) : true;
1.2196 - }
1.2197 - if (!bindingParams) {
1.2198 - if (!callPreprocessHook(ko['getBindingHandler'](key)))
1.2199 - return;
1.2200 -
1.2201 - if (twoWayBindings[key] && (writableVal = getWriteableValue(val))) {
1.2202 - // For two-way bindings, provide a write method in case the value
1.2203 - // isn't a writable observable.
1.2204 - propertyAccessorResultStrings.push("'" + key + "':function(_z){" + writableVal + "=_z}");
1.2205 - }
1.2206 - }
1.2207 - // Values are wrapped in a function so that each value can be accessed independently
1.2208 - if (makeValueAccessors) {
1.2209 - val = 'function(){return ' + val + ' }';
1.2210 - }
1.2211 - resultStrings.push("'" + key + "':" + val);
1.2212 - }
1.2213 -
1.2214 - var resultStrings = [],
1.2215 - propertyAccessorResultStrings = [],
1.2216 - makeValueAccessors = bindingOptions['valueAccessors'],
1.2217 - bindingParams = bindingOptions['bindingParams'],
1.2218 - keyValueArray = typeof bindingsStringOrKeyValueArray === "string" ?
1.2219 - parseObjectLiteral(bindingsStringOrKeyValueArray) : bindingsStringOrKeyValueArray;
1.2220 -
1.2221 - ko.utils.arrayForEach(keyValueArray, function(keyValue) {
1.2222 - processKeyValue(keyValue.key || keyValue['unknown'], keyValue.value);
1.2223 - });
1.2224 -
1.2225 - if (propertyAccessorResultStrings.length)
1.2226 - processKeyValue('_ko_property_writers', "{" + propertyAccessorResultStrings.join(",") + " }");
1.2227 -
1.2228 - return resultStrings.join(",");
1.2229 - }
1.2230 -
1.2231 - return {
1.2232 - bindingRewriteValidators: [],
1.2233 -
1.2234 - twoWayBindings: twoWayBindings,
1.2235 -
1.2236 - parseObjectLiteral: parseObjectLiteral,
1.2237 -
1.2238 - preProcessBindings: preProcessBindings,
1.2239 -
1.2240 - keyValueArrayContainsKey: function(keyValueArray, key) {
1.2241 - for (var i = 0; i < keyValueArray.length; i++)
1.2242 - if (keyValueArray[i]['key'] == key)
1.2243 - return true;
1.2244 - return false;
1.2245 - },
1.2246 -
1.2247 - // Internal, private KO utility for updating model properties from within bindings
1.2248 - // property: If the property being updated is (or might be) an observable, pass it here
1.2249 - // If it turns out to be a writable observable, it will be written to directly
1.2250 - // allBindings: An object with a get method to retrieve bindings in the current execution context.
1.2251 - // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
1.2252 - // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
1.2253 - // value: The value to be written
1.2254 - // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
1.2255 - // it is !== existing value on that writable observable
1.2256 - writeValueToProperty: function(property, allBindings, key, value, checkIfDifferent) {
1.2257 - if (!property || !ko.isObservable(property)) {
1.2258 - var propWriters = allBindings.get('_ko_property_writers');
1.2259 - if (propWriters && propWriters[key])
1.2260 - propWriters[key](value);
1.2261 - } else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {
1.2262 - property(value);
1.2263 - }
1.2264 - }
1.2265 - };
1.2266 -})();
1.2267 -
1.2268 -ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
1.2269 -ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
1.2270 -ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
1.2271 -ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
1.2272 -
1.2273 -// Making bindings explicitly declare themselves as "two way" isn't ideal in the long term (it would be better if
1.2274 -// all bindings could use an official 'property writer' API without needing to declare that they might). However,
1.2275 -// since this is not, and has never been, a public API (_ko_property_writers was never documented), it's acceptable
1.2276 -// as an internal implementation detail in the short term.
1.2277 -// For those developers who rely on _ko_property_writers in their custom bindings, we expose _twoWayBindings as an
1.2278 -// undocumented feature that makes it relatively easy to upgrade to KO 3.0. However, this is still not an official
1.2279 -// public API, and we reserve the right to remove it at any time if we create a real public property writers API.
1.2280 -ko.exportSymbol('expressionRewriting._twoWayBindings', ko.expressionRewriting.twoWayBindings);
1.2281 -
1.2282 -// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
1.2283 -// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
1.2284 -ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
1.2285 -ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);
1.2286 -(function() {
1.2287 - // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
1.2288 - // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
1.2289 - // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
1.2290 - // of that virtual hierarchy
1.2291 - //
1.2292 - // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
1.2293 - // without having to scatter special cases all over the binding and templating code.
1.2294 -
1.2295 - // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
1.2296 - // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
1.2297 - // So, use node.text where available, and node.nodeValue elsewhere
1.2298 - var commentNodesHaveTextProperty = document && document.createComment("test").text === "<!--test-->";
1.2299 -
1.2300 - var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/;
1.2301 - var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
1.2302 - var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
1.2303 -
1.2304 - function isStartComment(node) {
1.2305 - return (node.nodeType == 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
1.2306 - }
1.2307 -
1.2308 - function isEndComment(node) {
1.2309 - return (node.nodeType == 8) && endCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
1.2310 - }
1.2311 -
1.2312 - function getVirtualChildren(startComment, allowUnbalanced) {
1.2313 - var currentNode = startComment;
1.2314 - var depth = 1;
1.2315 - var children = [];
1.2316 - while (currentNode = currentNode.nextSibling) {
1.2317 - if (isEndComment(currentNode)) {
1.2318 - depth--;
1.2319 - if (depth === 0)
1.2320 - return children;
1.2321 - }
1.2322 -
1.2323 - children.push(currentNode);
1.2324 -
1.2325 - if (isStartComment(currentNode))
1.2326 - depth++;
1.2327 - }
1.2328 - if (!allowUnbalanced)
1.2329 - throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
1.2330 - return null;
1.2331 - }
1.2332 -
1.2333 - function getMatchingEndComment(startComment, allowUnbalanced) {
1.2334 - var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
1.2335 - if (allVirtualChildren) {
1.2336 - if (allVirtualChildren.length > 0)
1.2337 - return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
1.2338 - return startComment.nextSibling;
1.2339 - } else
1.2340 - return null; // Must have no matching end comment, and allowUnbalanced is true
1.2341 - }
1.2342 -
1.2343 - function getUnbalancedChildTags(node) {
1.2344 - // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
1.2345 - // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
1.2346 - var childNode = node.firstChild, captureRemaining = null;
1.2347 - if (childNode) {
1.2348 - do {
1.2349 - if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
1.2350 - captureRemaining.push(childNode);
1.2351 - else if (isStartComment(childNode)) {
1.2352 - var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
1.2353 - if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
1.2354 - childNode = matchingEndComment;
1.2355 - else
1.2356 - captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
1.2357 - } else if (isEndComment(childNode)) {
1.2358 - captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
1.2359 - }
1.2360 - } while (childNode = childNode.nextSibling);
1.2361 - }
1.2362 - return captureRemaining;
1.2363 - }
1.2364 -
1.2365 - ko.virtualElements = {
1.2366 - allowedBindings: {},
1.2367 -
1.2368 - childNodes: function(node) {
1.2369 - return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
1.2370 - },
1.2371 -
1.2372 - emptyNode: function(node) {
1.2373 - if (!isStartComment(node))
1.2374 - ko.utils.emptyDomNode(node);
1.2375 - else {
1.2376 - var virtualChildren = ko.virtualElements.childNodes(node);
1.2377 - for (var i = 0, j = virtualChildren.length; i < j; i++)
1.2378 - ko.removeNode(virtualChildren[i]);
1.2379 - }
1.2380 - },
1.2381 -
1.2382 - setDomNodeChildren: function(node, childNodes) {
1.2383 - if (!isStartComment(node))
1.2384 - ko.utils.setDomNodeChildren(node, childNodes);
1.2385 - else {
1.2386 - ko.virtualElements.emptyNode(node);
1.2387 - var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
1.2388 - for (var i = 0, j = childNodes.length; i < j; i++)
1.2389 - endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
1.2390 - }
1.2391 - },
1.2392 -
1.2393 - prepend: function(containerNode, nodeToPrepend) {
1.2394 - if (!isStartComment(containerNode)) {
1.2395 - if (containerNode.firstChild)
1.2396 - containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
1.2397 - else
1.2398 - containerNode.appendChild(nodeToPrepend);
1.2399 - } else {
1.2400 - // Start comments must always have a parent and at least one following sibling (the end comment)
1.2401 - containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
1.2402 - }
1.2403 - },
1.2404 -
1.2405 - insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
1.2406 - if (!insertAfterNode) {
1.2407 - ko.virtualElements.prepend(containerNode, nodeToInsert);
1.2408 - } else if (!isStartComment(containerNode)) {
1.2409 - // Insert after insertion point
1.2410 - if (insertAfterNode.nextSibling)
1.2411 - containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
1.2412 - else
1.2413 - containerNode.appendChild(nodeToInsert);
1.2414 - } else {
1.2415 - // Children of start comments must always have a parent and at least one following sibling (the end comment)
1.2416 - containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
1.2417 - }
1.2418 - },
1.2419 -
1.2420 - firstChild: function(node) {
1.2421 - if (!isStartComment(node))
1.2422 - return node.firstChild;
1.2423 - if (!node.nextSibling || isEndComment(node.nextSibling))
1.2424 - return null;
1.2425 - return node.nextSibling;
1.2426 - },
1.2427 -
1.2428 - nextSibling: function(node) {
1.2429 - if (isStartComment(node))
1.2430 - node = getMatchingEndComment(node);
1.2431 - if (node.nextSibling && isEndComment(node.nextSibling))
1.2432 - return null;
1.2433 - return node.nextSibling;
1.2434 - },
1.2435 -
1.2436 - hasBindingValue: isStartComment,
1.2437 -
1.2438 - virtualNodeBindingValue: function(node) {
1.2439 - var regexMatch = (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
1.2440 - return regexMatch ? regexMatch[1] : null;
1.2441 - },
1.2442 -
1.2443 - normaliseVirtualElementDomStructure: function(elementVerified) {
1.2444 - // Workaround for https://github.com/SteveSanderson/knockout/issues/155
1.2445 - // (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.2446 - // that are direct descendants of <ul> into the preceding <li>)
1.2447 - if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
1.2448 - return;
1.2449 -
1.2450 - // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
1.2451 - // must be intended to appear *after* that child, so move them there.
1.2452 - var childNode = elementVerified.firstChild;
1.2453 - if (childNode) {
1.2454 - do {
1.2455 - if (childNode.nodeType === 1) {
1.2456 - var unbalancedTags = getUnbalancedChildTags(childNode);
1.2457 - if (unbalancedTags) {
1.2458 - // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
1.2459 - var nodeToInsertBefore = childNode.nextSibling;
1.2460 - for (var i = 0; i < unbalancedTags.length; i++) {
1.2461 - if (nodeToInsertBefore)
1.2462 - elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
1.2463 - else
1.2464 - elementVerified.appendChild(unbalancedTags[i]);
1.2465 - }
1.2466 - }
1.2467 - }
1.2468 - } while (childNode = childNode.nextSibling);
1.2469 - }
1.2470 - }
1.2471 - };
1.2472 -})();
1.2473 -ko.exportSymbol('virtualElements', ko.virtualElements);
1.2474 -ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
1.2475 -ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
1.2476 -//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
1.2477 -ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
1.2478 -//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
1.2479 -ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
1.2480 -ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
1.2481 -(function() {
1.2482 - var defaultBindingAttributeName = "data-bind";
1.2483 -
1.2484 - ko.bindingProvider = function() {
1.2485 - this.bindingCache = {};
1.2486 - };
1.2487 -
1.2488 - ko.utils.extend(ko.bindingProvider.prototype, {
1.2489 - 'nodeHasBindings': function(node) {
1.2490 - switch (node.nodeType) {
1.2491 - case 1: // Element
1.2492 - return node.getAttribute(defaultBindingAttributeName) != null
1.2493 - || ko.components['getComponentNameForNode'](node);
1.2494 - case 8: // Comment node
1.2495 - return ko.virtualElements.hasBindingValue(node);
1.2496 - default: return false;
1.2497 - }
1.2498 - },
1.2499 -
1.2500 - 'getBindings': function(node, bindingContext) {
1.2501 - var bindingsString = this['getBindingsString'](node, bindingContext),
1.2502 - parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
1.2503 - return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ false);
1.2504 - },
1.2505 -
1.2506 - 'getBindingAccessors': function(node, bindingContext) {
1.2507 - var bindingsString = this['getBindingsString'](node, bindingContext),
1.2508 - parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node, { 'valueAccessors': true }) : null;
1.2509 - return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ true);
1.2510 - },
1.2511 -
1.2512 - // The following function is only used internally by this default provider.
1.2513 - // It's not part of the interface definition for a general binding provider.
1.2514 - 'getBindingsString': function(node, bindingContext) {
1.2515 - switch (node.nodeType) {
1.2516 - case 1: return node.getAttribute(defaultBindingAttributeName); // Element
1.2517 - case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
1.2518 - default: return null;
1.2519 - }
1.2520 - },
1.2521 -
1.2522 - // The following function is only used internally by this default provider.
1.2523 - // It's not part of the interface definition for a general binding provider.
1.2524 - 'parseBindingsString': function(bindingsString, bindingContext, node, options) {
1.2525 - try {
1.2526 - var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache, options);
1.2527 - return bindingFunction(bindingContext, node);
1.2528 - } catch (ex) {
1.2529 - ex.message = "Unable to parse bindings.\nBindings value: " + bindingsString + "\nMessage: " + ex.message;
1.2530 - throw ex;
1.2531 - }
1.2532 - }
1.2533 - });
1.2534 -
1.2535 - ko.bindingProvider['instance'] = new ko.bindingProvider();
1.2536 -
1.2537 - function createBindingsStringEvaluatorViaCache(bindingsString, cache, options) {
1.2538 - var cacheKey = bindingsString + (options && options['valueAccessors'] || '');
1.2539 - return cache[cacheKey]
1.2540 - || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, options));
1.2541 - }
1.2542 -
1.2543 - function createBindingsStringEvaluator(bindingsString, options) {
1.2544 - // Build the source for a function that evaluates "expression"
1.2545 - // For each scope variable, add an extra level of "with" nesting
1.2546 - // Example result: with(sc1) { with(sc0) { return (expression) } }
1.2547 - var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString, options),
1.2548 - functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
1.2549 - return new Function("$context", "$element", functionBody);
1.2550 - }
1.2551 -})();
1.2552 -
1.2553 -ko.exportSymbol('bindingProvider', ko.bindingProvider);
1.2554 -(function () {
1.2555 - ko.bindingHandlers = {};
1.2556 -
1.2557 - // The following element types will not be recursed into during binding. In the future, we
1.2558 - // may consider adding <template> to this list, because such elements' contents are always
1.2559 - // intended to be bound in a different context from where they appear in the document.
1.2560 - var bindingDoesNotRecurseIntoElementTypes = {
1.2561 - // Don't want bindings that operate on text nodes to mutate <script> contents,
1.2562 - // because it's unexpected and a potential XSS issue
1.2563 - 'script': true
1.2564 - };
1.2565 -
1.2566 - // Use an overridable method for retrieving binding handlers so that a plugins may support dynamically created handlers
1.2567 - ko['getBindingHandler'] = function(bindingKey) {
1.2568 - return ko.bindingHandlers[bindingKey];
1.2569 - };
1.2570 -
1.2571 - // The ko.bindingContext constructor is only called directly to create the root context. For child
1.2572 - // contexts, use bindingContext.createChildContext or bindingContext.extend.
1.2573 - ko.bindingContext = function(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback) {
1.2574 -
1.2575 - // The binding context object includes static properties for the current, parent, and root view models.
1.2576 - // If a view model is actually stored in an observable, the corresponding binding context object, and
1.2577 - // any child contexts, must be updated when the view model is changed.
1.2578 - function updateContext() {
1.2579 - // Most of the time, the context will directly get a view model object, but if a function is given,
1.2580 - // we call the function to retrieve the view model. If the function accesses any obsevables or returns
1.2581 - // an observable, the dependency is tracked, and those observables can later cause the binding
1.2582 - // context to be updated.
1.2583 - var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
1.2584 - dataItem = ko.utils.unwrapObservable(dataItemOrObservable);
1.2585 -
1.2586 - if (parentContext) {
1.2587 - // When a "parent" context is given, register a dependency on the parent context. Thus whenever the
1.2588 - // parent context is updated, this context will also be updated.
1.2589 - if (parentContext._subscribable)
1.2590 - parentContext._subscribable();
1.2591 -
1.2592 - // Copy $root and any custom properties from the parent context
1.2593 - ko.utils.extend(self, parentContext);
1.2594 -
1.2595 - // Because the above copy overwrites our own properties, we need to reset them.
1.2596 - // During the first execution, "subscribable" isn't set, so don't bother doing the update then.
1.2597 - if (subscribable) {
1.2598 - self._subscribable = subscribable;
1.2599 - }
1.2600 - } else {
1.2601 - self['$parents'] = [];
1.2602 - self['$root'] = dataItem;
1.2603 -
1.2604 - // Export 'ko' in the binding context so it will be available in bindings and templates
1.2605 - // even if 'ko' isn't exported as a global, such as when using an AMD loader.
1.2606 - // See https://github.com/SteveSanderson/knockout/issues/490
1.2607 - self['ko'] = ko;
1.2608 - }
1.2609 - self['$rawData'] = dataItemOrObservable;
1.2610 - self['$data'] = dataItem;
1.2611 - if (dataItemAlias)
1.2612 - self[dataItemAlias] = dataItem;
1.2613 -
1.2614 - // The extendCallback function is provided when creating a child context or extending a context.
1.2615 - // It handles the specific actions needed to finish setting up the binding context. Actions in this
1.2616 - // function could also add dependencies to this binding context.
1.2617 - if (extendCallback)
1.2618 - extendCallback(self, parentContext, dataItem);
1.2619 -
1.2620 - return self['$data'];
1.2621 - }
1.2622 - function disposeWhen() {
1.2623 - return nodes && !ko.utils.anyDomNodeIsAttachedToDocument(nodes);
1.2624 - }
1.2625 -
1.2626 - var self = this,
1.2627 - isFunc = typeof(dataItemOrAccessor) == "function" && !ko.isObservable(dataItemOrAccessor),
1.2628 - nodes,
1.2629 - subscribable = ko.dependentObservable(updateContext, null, { disposeWhen: disposeWhen, disposeWhenNodeIsRemoved: true });
1.2630 -
1.2631 - // At this point, the binding context has been initialized, and the "subscribable" computed observable is
1.2632 - // subscribed to any observables that were accessed in the process. If there is nothing to track, the
1.2633 - // computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
1.2634 - // the context object.
1.2635 - if (subscribable.isActive()) {
1.2636 - self._subscribable = subscribable;
1.2637 -
1.2638 - // Always notify because even if the model ($data) hasn't changed, other context properties might have changed
1.2639 - subscribable['equalityComparer'] = null;
1.2640 -
1.2641 - // We need to be able to dispose of this computed observable when it's no longer needed. This would be
1.2642 - // easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
1.2643 - // we cannot assume that those nodes have any relation to each other. So instead we track any node that
1.2644 - // the context is attached to, and dispose the computed when all of those nodes have been cleaned.
1.2645 -
1.2646 - // Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
1.2647 - nodes = [];
1.2648 - subscribable._addNode = function(node) {
1.2649 - nodes.push(node);
1.2650 - ko.utils.domNodeDisposal.addDisposeCallback(node, function(node) {
1.2651 - ko.utils.arrayRemoveItem(nodes, node);
1.2652 - if (!nodes.length) {
1.2653 - subscribable.dispose();
1.2654 - self._subscribable = subscribable = undefined;
1.2655 - }
1.2656 - });
1.2657 - };
1.2658 - }
1.2659 - }
1.2660 -
1.2661 - // Extend the binding context hierarchy with a new view model object. If the parent context is watching
1.2662 - // any obsevables, the new child context will automatically get a dependency on the parent context.
1.2663 - // But this does not mean that the $data value of the child context will also get updated. If the child
1.2664 - // view model also depends on the parent view model, you must provide a function that returns the correct
1.2665 - // view model on each update.
1.2666 - ko.bindingContext.prototype['createChildContext'] = function (dataItemOrAccessor, dataItemAlias, extendCallback) {
1.2667 - return new ko.bindingContext(dataItemOrAccessor, this, dataItemAlias, function(self, parentContext) {
1.2668 - // Extend the context hierarchy by setting the appropriate pointers
1.2669 - self['$parentContext'] = parentContext;
1.2670 - self['$parent'] = parentContext['$data'];
1.2671 - self['$parents'] = (parentContext['$parents'] || []).slice(0);
1.2672 - self['$parents'].unshift(self['$parent']);
1.2673 - if (extendCallback)
1.2674 - extendCallback(self);
1.2675 - });
1.2676 - };
1.2677 -
1.2678 - // Extend the binding context with new custom properties. This doesn't change the context hierarchy.
1.2679 - // Similarly to "child" contexts, provide a function here to make sure that the correct values are set
1.2680 - // when an observable view model is updated.
1.2681 - ko.bindingContext.prototype['extend'] = function(properties) {
1.2682 - // If the parent context references an observable view model, "_subscribable" will always be the
1.2683 - // latest view model object. If not, "_subscribable" isn't set, and we can use the static "$data" value.
1.2684 - return new ko.bindingContext(this._subscribable || this['$data'], this, null, function(self, parentContext) {
1.2685 - // This "child" context doesn't directly track a parent observable view model,
1.2686 - // so we need to manually set the $rawData value to match the parent.
1.2687 - self['$rawData'] = parentContext['$rawData'];
1.2688 - ko.utils.extend(self, typeof(properties) == "function" ? properties() : properties);
1.2689 - });
1.2690 - };
1.2691 -
1.2692 - // Returns the valueAccesor function for a binding value
1.2693 - function makeValueAccessor(value) {
1.2694 - return function() {
1.2695 - return value;
1.2696 - };
1.2697 - }
1.2698 -
1.2699 - // Returns the value of a valueAccessor function
1.2700 - function evaluateValueAccessor(valueAccessor) {
1.2701 - return valueAccessor();
1.2702 - }
1.2703 -
1.2704 - // Given a function that returns bindings, create and return a new object that contains
1.2705 - // binding value-accessors functions. Each accessor function calls the original function
1.2706 - // so that it always gets the latest value and all dependencies are captured. This is used
1.2707 - // by ko.applyBindingsToNode and getBindingsAndMakeAccessors.
1.2708 - function makeAccessorsFromFunction(callback) {
1.2709 - return ko.utils.objectMap(ko.dependencyDetection.ignore(callback), function(value, key) {
1.2710 - return function() {
1.2711 - return callback()[key];
1.2712 - };
1.2713 - });
1.2714 - }
1.2715 -
1.2716 - // Given a bindings function or object, create and return a new object that contains
1.2717 - // binding value-accessors functions. This is used by ko.applyBindingsToNode.
1.2718 - function makeBindingAccessors(bindings, context, node) {
1.2719 - if (typeof bindings === 'function') {
1.2720 - return makeAccessorsFromFunction(bindings.bind(null, context, node));
1.2721 - } else {
1.2722 - return ko.utils.objectMap(bindings, makeValueAccessor);
1.2723 - }
1.2724 - }
1.2725 -
1.2726 - // This function is used if the binding provider doesn't include a getBindingAccessors function.
1.2727 - // It must be called with 'this' set to the provider instance.
1.2728 - function getBindingsAndMakeAccessors(node, context) {
1.2729 - return makeAccessorsFromFunction(this['getBindings'].bind(this, node, context));
1.2730 - }
1.2731 -
1.2732 - function validateThatBindingIsAllowedForVirtualElements(bindingName) {
1.2733 - var validator = ko.virtualElements.allowedBindings[bindingName];
1.2734 - if (!validator)
1.2735 - throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
1.2736 - }
1.2737 -
1.2738 - function applyBindingsToDescendantsInternal (bindingContext, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
1.2739 - var currentChild,
1.2740 - nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement),
1.2741 - provider = ko.bindingProvider['instance'],
1.2742 - preprocessNode = provider['preprocessNode'];
1.2743 -
1.2744 - // Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's
1.2745 - // possible to insert new siblings after it, and/or replace the node with a different one. This can be used to
1.2746 - // implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that
1.2747 - // trigger insertion of <template> contents at that point in the document.
1.2748 - if (preprocessNode) {
1.2749 - while (currentChild = nextInQueue) {
1.2750 - nextInQueue = ko.virtualElements.nextSibling(currentChild);
1.2751 - preprocessNode.call(provider, currentChild);
1.2752 - }
1.2753 - // Reset nextInQueue for the next loop
1.2754 - nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
1.2755 - }
1.2756 -
1.2757 - while (currentChild = nextInQueue) {
1.2758 - // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
1.2759 - nextInQueue = ko.virtualElements.nextSibling(currentChild);
1.2760 - applyBindingsToNodeAndDescendantsInternal(bindingContext, currentChild, bindingContextsMayDifferFromDomParentElement);
1.2761 - }
1.2762 - }
1.2763 -
1.2764 - function applyBindingsToNodeAndDescendantsInternal (bindingContext, nodeVerified, bindingContextMayDifferFromDomParentElement) {
1.2765 - var shouldBindDescendants = true;
1.2766 -
1.2767 - // Perf optimisation: Apply bindings only if...
1.2768 - // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
1.2769 - // 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.2770 - // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
1.2771 - var isElement = (nodeVerified.nodeType === 1);
1.2772 - if (isElement) // Workaround IE <= 8 HTML parsing weirdness
1.2773 - ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
1.2774 -
1.2775 - var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
1.2776 - || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
1.2777 - if (shouldApplyBindings)
1.2778 - shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, bindingContext, bindingContextMayDifferFromDomParentElement)['shouldBindDescendants'];
1.2779 -
1.2780 - if (shouldBindDescendants && !bindingDoesNotRecurseIntoElementTypes[ko.utils.tagNameLower(nodeVerified)]) {
1.2781 - // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
1.2782 - // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
1.2783 - // hence bindingContextsMayDifferFromDomParentElement is false
1.2784 - // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
1.2785 - // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
1.2786 - // hence bindingContextsMayDifferFromDomParentElement is true
1.2787 - applyBindingsToDescendantsInternal(bindingContext, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
1.2788 - }
1.2789 - }
1.2790 -
1.2791 - var boundElementDomDataKey = ko.utils.domData.nextKey();
1.2792 -
1.2793 -
1.2794 - function topologicalSortBindings(bindings) {
1.2795 - // Depth-first sort
1.2796 - var result = [], // The list of key/handler pairs that we will return
1.2797 - bindingsConsidered = {}, // A temporary record of which bindings are already in 'result'
1.2798 - cyclicDependencyStack = []; // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it
1.2799 - ko.utils.objectForEach(bindings, function pushBinding(bindingKey) {
1.2800 - if (!bindingsConsidered[bindingKey]) {
1.2801 - var binding = ko['getBindingHandler'](bindingKey);
1.2802 - if (binding) {
1.2803 - // First add dependencies (if any) of the current binding
1.2804 - if (binding['after']) {
1.2805 - cyclicDependencyStack.push(bindingKey);
1.2806 - ko.utils.arrayForEach(binding['after'], function(bindingDependencyKey) {
1.2807 - if (bindings[bindingDependencyKey]) {
1.2808 - if (ko.utils.arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) {
1.2809 - throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + cyclicDependencyStack.join(", "));
1.2810 - } else {
1.2811 - pushBinding(bindingDependencyKey);
1.2812 - }
1.2813 - }
1.2814 - });
1.2815 - cyclicDependencyStack.length--;
1.2816 - }
1.2817 - // Next add the current binding
1.2818 - result.push({ key: bindingKey, handler: binding });
1.2819 - }
1.2820 - bindingsConsidered[bindingKey] = true;
1.2821 - }
1.2822 - });
1.2823 -
1.2824 - return result;
1.2825 - }
1.2826 -
1.2827 - function applyBindingsToNodeInternal(node, sourceBindings, bindingContext, bindingContextMayDifferFromDomParentElement) {
1.2828 - // Prevent multiple applyBindings calls for the same node, except when a binding value is specified
1.2829 - var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
1.2830 - if (!sourceBindings) {
1.2831 - if (alreadyBound) {
1.2832 - throw Error("You cannot apply bindings multiple times to the same element.");
1.2833 - }
1.2834 - ko.utils.domData.set(node, boundElementDomDataKey, true);
1.2835 - }
1.2836 -
1.2837 - // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
1.2838 - // we can easily recover it just by scanning up the node's ancestors in the DOM
1.2839 - // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
1.2840 - if (!alreadyBound && bindingContextMayDifferFromDomParentElement)
1.2841 - ko.storedBindingContextForNode(node, bindingContext);
1.2842 -
1.2843 - // Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings
1.2844 - var bindings;
1.2845 - if (sourceBindings && typeof sourceBindings !== 'function') {
1.2846 - bindings = sourceBindings;
1.2847 - } else {
1.2848 - var provider = ko.bindingProvider['instance'],
1.2849 - getBindings = provider['getBindingAccessors'] || getBindingsAndMakeAccessors;
1.2850 -
1.2851 - // Get the binding from the provider within a computed observable so that we can update the bindings whenever
1.2852 - // the binding context is updated or if the binding provider accesses observables.
1.2853 - var bindingsUpdater = ko.dependentObservable(
1.2854 - function() {
1.2855 - bindings = sourceBindings ? sourceBindings(bindingContext, node) : getBindings.call(provider, node, bindingContext);
1.2856 - // Register a dependency on the binding context to support obsevable view models.
1.2857 - if (bindings && bindingContext._subscribable)
1.2858 - bindingContext._subscribable();
1.2859 - return bindings;
1.2860 - },
1.2861 - null, { disposeWhenNodeIsRemoved: node }
1.2862 - );
1.2863 -
1.2864 - if (!bindings || !bindingsUpdater.isActive())
1.2865 - bindingsUpdater = null;
1.2866 - }
1.2867 -
1.2868 - var bindingHandlerThatControlsDescendantBindings;
1.2869 - if (bindings) {
1.2870 - // Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding
1.2871 - // context update), just return the value accessor from the binding. Otherwise, return a function that always gets
1.2872 - // the latest binding value and registers a dependency on the binding updater.
1.2873 - var getValueAccessor = bindingsUpdater
1.2874 - ? function(bindingKey) {
1.2875 - return function() {
1.2876 - return evaluateValueAccessor(bindingsUpdater()[bindingKey]);
1.2877 - };
1.2878 - } : function(bindingKey) {
1.2879 - return bindings[bindingKey];
1.2880 - };
1.2881 -
1.2882 - // Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated
1.2883 - function allBindings() {
1.2884 - return ko.utils.objectMap(bindingsUpdater ? bindingsUpdater() : bindings, evaluateValueAccessor);
1.2885 - }
1.2886 - // The following is the 3.x allBindings API
1.2887 - allBindings['get'] = function(key) {
1.2888 - return bindings[key] && evaluateValueAccessor(getValueAccessor(key));
1.2889 - };
1.2890 - allBindings['has'] = function(key) {
1.2891 - return key in bindings;
1.2892 - };
1.2893 -
1.2894 - // First put the bindings into the right order
1.2895 - var orderedBindings = topologicalSortBindings(bindings);
1.2896 -
1.2897 - // Go through the sorted bindings, calling init and update for each
1.2898 - ko.utils.arrayForEach(orderedBindings, function(bindingKeyAndHandler) {
1.2899 - // Note that topologicalSortBindings has already filtered out any nonexistent binding handlers,
1.2900 - // so bindingKeyAndHandler.handler will always be nonnull.
1.2901 - var handlerInitFn = bindingKeyAndHandler.handler["init"],
1.2902 - handlerUpdateFn = bindingKeyAndHandler.handler["update"],
1.2903 - bindingKey = bindingKeyAndHandler.key;
1.2904 -
1.2905 - if (node.nodeType === 8) {
1.2906 - validateThatBindingIsAllowedForVirtualElements(bindingKey);
1.2907 - }
1.2908 -
1.2909 - try {
1.2910 - // Run init, ignoring any dependencies
1.2911 - if (typeof handlerInitFn == "function") {
1.2912 - ko.dependencyDetection.ignore(function() {
1.2913 - var initResult = handlerInitFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
1.2914 -
1.2915 - // If this binding handler claims to control descendant bindings, make a note of this
1.2916 - if (initResult && initResult['controlsDescendantBindings']) {
1.2917 - if (bindingHandlerThatControlsDescendantBindings !== undefined)
1.2918 - 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.2919 - bindingHandlerThatControlsDescendantBindings = bindingKey;
1.2920 - }
1.2921 - });
1.2922 - }
1.2923 -
1.2924 - // Run update in its own computed wrapper
1.2925 - if (typeof handlerUpdateFn == "function") {
1.2926 - ko.dependentObservable(
1.2927 - function() {
1.2928 - handlerUpdateFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
1.2929 - },
1.2930 - null,
1.2931 - { disposeWhenNodeIsRemoved: node }
1.2932 - );
1.2933 - }
1.2934 - } catch (ex) {
1.2935 - ex.message = "Unable to process binding \"" + bindingKey + ": " + bindings[bindingKey] + "\"\nMessage: " + ex.message;
1.2936 - throw ex;
1.2937 - }
1.2938 - });
1.2939 - }
1.2940 -
1.2941 - return {
1.2942 - 'shouldBindDescendants': bindingHandlerThatControlsDescendantBindings === undefined
1.2943 - };
1.2944 - };
1.2945 -
1.2946 - var storedBindingContextDomDataKey = ko.utils.domData.nextKey();
1.2947 - ko.storedBindingContextForNode = function (node, bindingContext) {
1.2948 - if (arguments.length == 2) {
1.2949 - ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
1.2950 - if (bindingContext._subscribable)
1.2951 - bindingContext._subscribable._addNode(node);
1.2952 - } else {
1.2953 - return ko.utils.domData.get(node, storedBindingContextDomDataKey);
1.2954 - }
1.2955 - }
1.2956 -
1.2957 - function getBindingContext(viewModelOrBindingContext) {
1.2958 - return viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
1.2959 - ? viewModelOrBindingContext
1.2960 - : new ko.bindingContext(viewModelOrBindingContext);
1.2961 - }
1.2962 -
1.2963 - ko.applyBindingAccessorsToNode = function (node, bindings, viewModelOrBindingContext) {
1.2964 - if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
1.2965 - ko.virtualElements.normaliseVirtualElementDomStructure(node);
1.2966 - return applyBindingsToNodeInternal(node, bindings, getBindingContext(viewModelOrBindingContext), true);
1.2967 - };
1.2968 -
1.2969 - ko.applyBindingsToNode = function (node, bindings, viewModelOrBindingContext) {
1.2970 - var context = getBindingContext(viewModelOrBindingContext);
1.2971 - return ko.applyBindingAccessorsToNode(node, makeBindingAccessors(bindings, context, node), context);
1.2972 - };
1.2973 -
1.2974 - ko.applyBindingsToDescendants = function(viewModelOrBindingContext, rootNode) {
1.2975 - if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
1.2976 - applyBindingsToDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
1.2977 - };
1.2978 -
1.2979 - ko.applyBindings = function (viewModelOrBindingContext, rootNode) {
1.2980 - // If jQuery is loaded after Knockout, we won't initially have access to it. So save it here.
1.2981 - if (!jQueryInstance && window['jQuery']) {
1.2982 - jQueryInstance = window['jQuery'];
1.2983 - }
1.2984 -
1.2985 - if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
1.2986 - throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
1.2987 - rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
1.2988 -
1.2989 - applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
1.2990 - };
1.2991 -
1.2992 - // Retrieving binding context from arbitrary nodes
1.2993 - ko.contextFor = function(node) {
1.2994 - // 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.2995 - switch (node.nodeType) {
1.2996 - case 1:
1.2997 - case 8:
1.2998 - var context = ko.storedBindingContextForNode(node);
1.2999 - if (context) return context;
1.3000 - if (node.parentNode) return ko.contextFor(node.parentNode);
1.3001 - break;
1.3002 - }
1.3003 - return undefined;
1.3004 - };
1.3005 - ko.dataFor = function(node) {
1.3006 - var context = ko.contextFor(node);
1.3007 - return context ? context['$data'] : undefined;
1.3008 - };
1.3009 -
1.3010 - ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
1.3011 - ko.exportSymbol('applyBindings', ko.applyBindings);
1.3012 - ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
1.3013 - ko.exportSymbol('applyBindingAccessorsToNode', ko.applyBindingAccessorsToNode);
1.3014 - ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
1.3015 - ko.exportSymbol('contextFor', ko.contextFor);
1.3016 - ko.exportSymbol('dataFor', ko.dataFor);
1.3017 -})();
1.3018 -(function(undefined) {
1.3019 - var loadingSubscribablesCache = {}, // Tracks component loads that are currently in flight
1.3020 - loadedDefinitionsCache = {}; // Tracks component loads that have already completed
1.3021 -
1.3022 - ko.components = {
1.3023 - get: function(componentName, callback) {
1.3024 - var cachedDefinition = getObjectOwnProperty(loadedDefinitionsCache, componentName);
1.3025 - if (cachedDefinition) {
1.3026 - // It's already loaded and cached. Reuse the same definition object.
1.3027 - // Note that for API consistency, even cache hits complete asynchronously.
1.3028 - setTimeout(function() { callback(cachedDefinition) }, 0);
1.3029 - } else {
1.3030 - // Join the loading process that is already underway, or start a new one.
1.3031 - loadComponentAndNotify(componentName, callback);
1.3032 - }
1.3033 - },
1.3034 -
1.3035 - clearCachedDefinition: function(componentName) {
1.3036 - delete loadedDefinitionsCache[componentName];
1.3037 - },
1.3038 -
1.3039 - _getFirstResultFromLoaders: getFirstResultFromLoaders
1.3040 - };
1.3041 -
1.3042 - function getObjectOwnProperty(obj, propName) {
1.3043 - return obj.hasOwnProperty(propName) ? obj[propName] : undefined;
1.3044 - }
1.3045 -
1.3046 - function loadComponentAndNotify(componentName, callback) {
1.3047 - var subscribable = getObjectOwnProperty(loadingSubscribablesCache, componentName),
1.3048 - completedAsync;
1.3049 - if (!subscribable) {
1.3050 - // It's not started loading yet. Start loading, and when it's done, move it to loadedDefinitionsCache.
1.3051 - subscribable = loadingSubscribablesCache[componentName] = new ko.subscribable();
1.3052 - beginLoadingComponent(componentName, function(definition) {
1.3053 - loadedDefinitionsCache[componentName] = definition;
1.3054 - delete loadingSubscribablesCache[componentName];
1.3055 -
1.3056 - // For API consistency, all loads complete asynchronously. However we want to avoid
1.3057 - // adding an extra setTimeout if it's unnecessary (i.e., the completion is already
1.3058 - // async) since setTimeout(..., 0) still takes about 16ms or more on most browsers.
1.3059 - if (completedAsync) {
1.3060 - subscribable['notifySubscribers'](definition);
1.3061 - } else {
1.3062 - setTimeout(function() {
1.3063 - subscribable['notifySubscribers'](definition);
1.3064 - }, 0);
1.3065 - }
1.3066 - });
1.3067 - completedAsync = true;
1.3068 - }
1.3069 - subscribable.subscribe(callback);
1.3070 - }
1.3071 -
1.3072 - function beginLoadingComponent(componentName, callback) {
1.3073 - getFirstResultFromLoaders('getConfig', [componentName], function(config) {
1.3074 - if (config) {
1.3075 - // We have a config, so now load its definition
1.3076 - getFirstResultFromLoaders('loadComponent', [componentName, config], function(definition) {
1.3077 - callback(definition);
1.3078 - });
1.3079 - } else {
1.3080 - // The component has no config - it's unknown to all the loaders.
1.3081 - // Note that this is not an error (e.g., a module loading error) - that would abort the
1.3082 - // process and this callback would not run. For this callback to run, all loaders must
1.3083 - // have confirmed they don't know about this component.
1.3084 - callback(null);
1.3085 - }
1.3086 - });
1.3087 - }
1.3088 -
1.3089 - function getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders) {
1.3090 - // On the first call in the stack, start with the full set of loaders
1.3091 - if (!candidateLoaders) {
1.3092 - candidateLoaders = ko.components['loaders'].slice(0); // Use a copy, because we'll be mutating this array
1.3093 - }
1.3094 -
1.3095 - // Try the next candidate
1.3096 - var currentCandidateLoader = candidateLoaders.shift();
1.3097 - if (currentCandidateLoader) {
1.3098 - var methodInstance = currentCandidateLoader[methodName];
1.3099 - if (methodInstance) {
1.3100 - var wasAborted = false,
1.3101 - synchronousReturnValue = methodInstance.apply(currentCandidateLoader, argsExceptCallback.concat(function(result) {
1.3102 - if (wasAborted) {
1.3103 - callback(null);
1.3104 - } else if (result !== null) {
1.3105 - // This candidate returned a value. Use it.
1.3106 - callback(result);
1.3107 - } else {
1.3108 - // Try the next candidate
1.3109 - getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);
1.3110 - }
1.3111 - }));
1.3112 -
1.3113 - // Currently, loaders may not return anything synchronously. This leaves open the possibility
1.3114 - // that we'll extend the API to support synchronous return values in the future. It won't be
1.3115 - // a breaking change, because currently no loader is allowed to return anything except undefined.
1.3116 - if (synchronousReturnValue !== undefined) {
1.3117 - wasAborted = true;
1.3118 -
1.3119 - // Method to suppress exceptions will remain undocumented. This is only to keep
1.3120 - // KO's specs running tidily, since we can observe the loading got aborted without
1.3121 - // having exceptions cluttering up the console too.
1.3122 - if (!currentCandidateLoader['suppressLoaderExceptions']) {
1.3123 - throw new Error('Component loaders must supply values by invoking the callback, not by returning values synchronously.');
1.3124 - }
1.3125 - }
1.3126 - } else {
1.3127 - // This candidate doesn't have the relevant handler. Synchronously move on to the next one.
1.3128 - getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);
1.3129 - }
1.3130 - } else {
1.3131 - // No candidates returned a value
1.3132 - callback(null);
1.3133 - }
1.3134 - }
1.3135 -
1.3136 - // Reference the loaders via string name so it's possible for developers
1.3137 - // to replace the whole array by assigning to ko.components.loaders
1.3138 - ko.components['loaders'] = [];
1.3139 -
1.3140 - ko.exportSymbol('components', ko.components);
1.3141 - ko.exportSymbol('components.get', ko.components.get);
1.3142 - ko.exportSymbol('components.clearCachedDefinition', ko.components.clearCachedDefinition);
1.3143 -})();
1.3144 -(function(undefined) {
1.3145 -
1.3146 - // The default loader is responsible for two things:
1.3147 - // 1. Maintaining the default in-memory registry of component configuration objects
1.3148 - // (i.e., the thing you're writing to when you call ko.components.register(someName, ...))
1.3149 - // 2. Answering requests for components by fetching configuration objects
1.3150 - // from that default in-memory registry and resolving them into standard
1.3151 - // component definition objects (of the form { createViewModel: ..., template: ... })
1.3152 - // Custom loaders may override either of these facilities, i.e.,
1.3153 - // 1. To supply configuration objects from some other source (e.g., conventions)
1.3154 - // 2. Or, to resolve configuration objects by loading viewmodels/templates via arbitrary logic.
1.3155 -
1.3156 - var defaultConfigRegistry = {};
1.3157 -
1.3158 - ko.components.register = function(componentName, config) {
1.3159 - if (!config) {
1.3160 - throw new Error('Invalid configuration for ' + componentName);
1.3161 - }
1.3162 -
1.3163 - if (ko.components.isRegistered(componentName)) {
1.3164 - throw new Error('Component ' + componentName + ' is already registered');
1.3165 - }
1.3166 -
1.3167 - defaultConfigRegistry[componentName] = config;
1.3168 - }
1.3169 -
1.3170 - ko.components.isRegistered = function(componentName) {
1.3171 - return componentName in defaultConfigRegistry;
1.3172 - }
1.3173 -
1.3174 - ko.components.unregister = function(componentName) {
1.3175 - delete defaultConfigRegistry[componentName];
1.3176 - ko.components.clearCachedDefinition(componentName);
1.3177 - }
1.3178 -
1.3179 - ko.components.defaultLoader = {
1.3180 - 'getConfig': function(componentName, callback) {
1.3181 - var result = defaultConfigRegistry.hasOwnProperty(componentName)
1.3182 - ? defaultConfigRegistry[componentName]
1.3183 - : null;
1.3184 - callback(result);
1.3185 - },
1.3186 -
1.3187 - 'loadComponent': function(componentName, config, callback) {
1.3188 - var errorCallback = makeErrorCallback(componentName);
1.3189 - possiblyGetConfigFromAmd(errorCallback, config, function(loadedConfig) {
1.3190 - resolveConfig(componentName, errorCallback, loadedConfig, callback);
1.3191 - });
1.3192 - },
1.3193 -
1.3194 - 'loadTemplate': function(componentName, templateConfig, callback) {
1.3195 - resolveTemplate(makeErrorCallback(componentName), templateConfig, callback);
1.3196 - },
1.3197 -
1.3198 - 'loadViewModel': function(componentName, viewModelConfig, callback) {
1.3199 - resolveViewModel(makeErrorCallback(componentName), viewModelConfig, callback);
1.3200 - }
1.3201 - };
1.3202 -
1.3203 - var createViewModelKey = 'createViewModel';
1.3204 -
1.3205 - // Takes a config object of the form { template: ..., viewModel: ... }, and asynchronously convert it
1.3206 - // into the standard component definition format:
1.3207 - // { template: <ArrayOfDomNodes>, createViewModel: function(params, componentInfo) { ... } }.
1.3208 - // Since both template and viewModel may need to be resolved asynchronously, both tasks are performed
1.3209 - // in parallel, and the results joined when both are ready. We don't depend on any promises infrastructure,
1.3210 - // so this is implemented manually below.
1.3211 - function resolveConfig(componentName, errorCallback, config, callback) {
1.3212 - var result = {},
1.3213 - makeCallBackWhenZero = 2,
1.3214 - tryIssueCallback = function() {
1.3215 - if (--makeCallBackWhenZero === 0) {
1.3216 - callback(result);
1.3217 - }
1.3218 - },
1.3219 - templateConfig = config['template'],
1.3220 - viewModelConfig = config['viewModel'];
1.3221 -
1.3222 - if (templateConfig) {
1.3223 - possiblyGetConfigFromAmd(errorCallback, templateConfig, function(loadedConfig) {
1.3224 - ko.components._getFirstResultFromLoaders('loadTemplate', [componentName, loadedConfig], function(resolvedTemplate) {
1.3225 - result['template'] = resolvedTemplate;
1.3226 - tryIssueCallback();
1.3227 - });
1.3228 - });
1.3229 - } else {
1.3230 - tryIssueCallback();
1.3231 - }
1.3232 -
1.3233 - if (viewModelConfig) {
1.3234 - possiblyGetConfigFromAmd(errorCallback, viewModelConfig, function(loadedConfig) {
1.3235 - ko.components._getFirstResultFromLoaders('loadViewModel', [componentName, loadedConfig], function(resolvedViewModel) {
1.3236 - result[createViewModelKey] = resolvedViewModel;
1.3237 - tryIssueCallback();
1.3238 - });
1.3239 - });
1.3240 - } else {
1.3241 - tryIssueCallback();
1.3242 - }
1.3243 - }
1.3244 -
1.3245 - function resolveTemplate(errorCallback, templateConfig, callback) {
1.3246 - if (typeof templateConfig === 'string') {
1.3247 - // Markup - parse it
1.3248 - callback(ko.utils.parseHtmlFragment(templateConfig));
1.3249 - } else if (templateConfig instanceof Array) {
1.3250 - // Assume already an array of DOM nodes - pass through unchanged
1.3251 - callback(templateConfig);
1.3252 - } else if (isDocumentFragment(templateConfig)) {
1.3253 - // Document fragment - use its child nodes
1.3254 - callback(ko.utils.makeArray(templateConfig.childNodes));
1.3255 - } else if (templateConfig['element']) {
1.3256 - var element = templateConfig['element'];
1.3257 - if (isDomElement(element)) {
1.3258 - // Element instance - copy its child nodes
1.3259 - callback(cloneNodesFromTemplateSourceElement(element));
1.3260 - } else if (typeof element === 'string') {
1.3261 - // Element ID - find it, then copy its child nodes
1.3262 - var elemInstance = document.getElementById(element);
1.3263 - if (elemInstance) {
1.3264 - callback(cloneNodesFromTemplateSourceElement(elemInstance));
1.3265 - } else {
1.3266 - errorCallback('Cannot find element with ID ' + element);
1.3267 - }
1.3268 - } else {
1.3269 - errorCallback('Unknown element type: ' + element);
1.3270 - }
1.3271 - } else {
1.3272 - errorCallback('Unknown template value: ' + templateConfig);
1.3273 - }
1.3274 - }
1.3275 -
1.3276 - function resolveViewModel(errorCallback, viewModelConfig, callback) {
1.3277 - if (typeof viewModelConfig === 'function') {
1.3278 - // Constructor - convert to standard factory function format
1.3279 - // By design, this does *not* supply componentInfo to the constructor, as the intent is that
1.3280 - // componentInfo contains non-viewmodel data (e.g., the component's element) that should only
1.3281 - // be used in factory functions, not viewmodel constructors.
1.3282 - callback(function (params /*, componentInfo */) {
1.3283 - return new viewModelConfig(params);
1.3284 - });
1.3285 - } else if (typeof viewModelConfig[createViewModelKey] === 'function') {
1.3286 - // Already a factory function - use it as-is
1.3287 - callback(viewModelConfig[createViewModelKey]);
1.3288 - } else if ('instance' in viewModelConfig) {
1.3289 - // Fixed object instance - promote to createViewModel format for API consistency
1.3290 - var fixedInstance = viewModelConfig['instance'];
1.3291 - callback(function (params, componentInfo) {
1.3292 - return fixedInstance;
1.3293 - });
1.3294 - } else if ('viewModel' in viewModelConfig) {
1.3295 - // Resolved AMD module whose value is of the form { viewModel: ... }
1.3296 - resolveViewModel(errorCallback, viewModelConfig['viewModel'], callback);
1.3297 - } else {
1.3298 - errorCallback('Unknown viewModel value: ' + viewModelConfig);
1.3299 - }
1.3300 - }
1.3301 -
1.3302 - function cloneNodesFromTemplateSourceElement(elemInstance) {
1.3303 - switch (ko.utils.tagNameLower(elemInstance)) {
1.3304 - case 'script':
1.3305 - return ko.utils.parseHtmlFragment(elemInstance.text);
1.3306 - case 'textarea':
1.3307 - return ko.utils.parseHtmlFragment(elemInstance.value);
1.3308 - case 'template':
1.3309 - // For browsers with proper <template> element support (i.e., where the .content property
1.3310 - // gives a document fragment), use that document fragment.
1.3311 - if (isDocumentFragment(elemInstance.content)) {
1.3312 - return ko.utils.cloneNodes(elemInstance.content.childNodes);
1.3313 - }
1.3314 - }
1.3315 -
1.3316 - // Regular elements such as <div>, and <template> elements on old browsers that don't really
1.3317 - // understand <template> and just treat it as a regular container
1.3318 - return ko.utils.cloneNodes(elemInstance.childNodes);
1.3319 - }
1.3320 -
1.3321 - function isDomElement(obj) {
1.3322 - if (window['HTMLElement']) {
1.3323 - return obj instanceof HTMLElement;
1.3324 - } else {
1.3325 - return obj && obj.tagName && obj.nodeType === 1;
1.3326 - }
1.3327 - }
1.3328 -
1.3329 - function isDocumentFragment(obj) {
1.3330 - if (window['DocumentFragment']) {
1.3331 - return obj instanceof DocumentFragment;
1.3332 - } else {
1.3333 - return obj && obj.nodeType === 11;
1.3334 - }
1.3335 - }
1.3336 -
1.3337 - function possiblyGetConfigFromAmd(errorCallback, config, callback) {
1.3338 - if (typeof config['require'] === 'string') {
1.3339 - // The config is the value of an AMD module
1.3340 - if (require || window['require']) {
1.3341 - (require || window['require'])([config['require']], callback);
1.3342 - } else {
1.3343 - errorCallback('Uses require, but no AMD loader is present');
1.3344 - }
1.3345 - } else {
1.3346 - callback(config);
1.3347 - }
1.3348 - }
1.3349 -
1.3350 - function makeErrorCallback(componentName) {
1.3351 - return function (message) {
1.3352 - throw new Error('Component \'' + componentName + '\': ' + message);
1.3353 - };
1.3354 - }
1.3355 -
1.3356 - ko.exportSymbol('components.register', ko.components.register);
1.3357 - ko.exportSymbol('components.isRegistered', ko.components.isRegistered);
1.3358 - ko.exportSymbol('components.unregister', ko.components.unregister);
1.3359 -
1.3360 - // Expose the default loader so that developers can directly ask it for configuration
1.3361 - // or to resolve configuration
1.3362 - ko.exportSymbol('components.defaultLoader', ko.components.defaultLoader);
1.3363 -
1.3364 - // By default, the default loader is the only registered component loader
1.3365 - ko.components['loaders'].push(ko.components.defaultLoader);
1.3366 -
1.3367 - // Privately expose the underlying config registry for use in old-IE shim
1.3368 - ko.components._allRegisteredComponents = defaultConfigRegistry;
1.3369 -})();
1.3370 -(function (undefined) {
1.3371 - // Overridable API for determining which component name applies to a given node. By overriding this,
1.3372 - // you can for example map specific tagNames to components that are not preregistered.
1.3373 - ko.components['getComponentNameForNode'] = function(node) {
1.3374 - var tagNameLower = ko.utils.tagNameLower(node);
1.3375 - return ko.components.isRegistered(tagNameLower) && tagNameLower;
1.3376 - };
1.3377 -
1.3378 - ko.components.addBindingsForCustomElement = function(allBindings, node, bindingContext, valueAccessors) {
1.3379 - // Determine if it's really a custom element matching a component
1.3380 - if (node.nodeType === 1) {
1.3381 - var componentName = ko.components['getComponentNameForNode'](node);
1.3382 - if (componentName) {
1.3383 - // It does represent a component, so add a component binding for it
1.3384 - allBindings = allBindings || {};
1.3385 -
1.3386 - if (allBindings['component']) {
1.3387 - // Avoid silently overwriting some other 'component' binding that may already be on the element
1.3388 - throw new Error('Cannot use the "component" binding on a custom element matching a component');
1.3389 - }
1.3390 -
1.3391 - var componentBindingValue = { 'name': componentName, 'params': getComponentParamsFromCustomElement(node, bindingContext) };
1.3392 -
1.3393 - allBindings['component'] = valueAccessors
1.3394 - ? function() { return componentBindingValue; }
1.3395 - : componentBindingValue;
1.3396 - }
1.3397 - }
1.3398 -
1.3399 - return allBindings;
1.3400 - }
1.3401 -
1.3402 - var nativeBindingProviderInstance = new ko.bindingProvider();
1.3403 -
1.3404 - function getComponentParamsFromCustomElement(elem, bindingContext) {
1.3405 - var paramsAttribute = elem.getAttribute('params');
1.3406 -
1.3407 - if (paramsAttribute) {
1.3408 - var params = nativeBindingProviderInstance['parseBindingsString'](paramsAttribute, bindingContext, elem, { 'valueAccessors': true, 'bindingParams': true }),
1.3409 - rawParamComputedValues = ko.utils.objectMap(params, function(paramValue, paramName) {
1.3410 - return ko.computed(paramValue, null, { disposeWhenNodeIsRemoved: elem });
1.3411 - }),
1.3412 - result = ko.utils.objectMap(rawParamComputedValues, function(paramValueComputed, paramName) {
1.3413 - // Does the evaluation of the parameter value unwrap any observables?
1.3414 - if (!paramValueComputed.isActive()) {
1.3415 - // No it doesn't, so there's no need for any computed wrapper. Just pass through the supplied value directly.
1.3416 - // Example: "someVal: firstName, age: 123" (whether or not firstName is an observable/computed)
1.3417 - return paramValueComputed.peek();
1.3418 - } else {
1.3419 - // Yes it does. Supply a computed property that unwraps both the outer (binding expression)
1.3420 - // level of observability, and any inner (resulting model value) level of observability.
1.3421 - // This means the component doesn't have to worry about multiple unwrapping.
1.3422 - return ko.computed(function() {
1.3423 - return ko.utils.unwrapObservable(paramValueComputed());
1.3424 - }, null, { disposeWhenNodeIsRemoved: elem });
1.3425 - }
1.3426 - });
1.3427 -
1.3428 - // Give access to the raw computeds, as long as that wouldn't overwrite any custom param also called '$raw'
1.3429 - // This is in case the developer wants to react to outer (binding) observability separately from inner
1.3430 - // (model value) observability, or in case the model value observable has subobservables.
1.3431 - if (!result.hasOwnProperty('$raw')) {
1.3432 - result['$raw'] = rawParamComputedValues;
1.3433 - }
1.3434 -
1.3435 - return result;
1.3436 - } else {
1.3437 - // For consistency, absence of a "params" attribute is treated the same as the presence of
1.3438 - // any empty one. Otherwise component viewmodels need special code to check whether or not
1.3439 - // 'params' or 'params.$raw' is null/undefined before reading subproperties, which is annoying.
1.3440 - return { '$raw': {} };
1.3441 - }
1.3442 - }
1.3443 -
1.3444 - // --------------------------------------------------------------------------------
1.3445 - // Compatibility code for older (pre-HTML5) IE browsers
1.3446 -
1.3447 - if (ko.utils.ieVersion < 9) {
1.3448 - // Whenever you preregister a component, enable it as a custom element in the current document
1.3449 - ko.components['register'] = (function(originalFunction) {
1.3450 - return function(componentName) {
1.3451 - document.createElement(componentName); // Allows IE<9 to parse markup containing the custom element
1.3452 - return originalFunction.apply(this, arguments);
1.3453 - }
1.3454 - })(ko.components['register']);
1.3455 -
1.3456 - // Whenever you create a document fragment, enable all preregistered component names as custom elements
1.3457 - // This is needed to make innerShiv/jQuery HTML parsing correctly handle the custom elements
1.3458 - document.createDocumentFragment = (function(originalFunction) {
1.3459 - return function() {
1.3460 - var newDocFrag = originalFunction(),
1.3461 - allComponents = ko.components._allRegisteredComponents;
1.3462 - for (var componentName in allComponents) {
1.3463 - if (allComponents.hasOwnProperty(componentName)) {
1.3464 - newDocFrag.createElement(componentName);
1.3465 - }
1.3466 - }
1.3467 - return newDocFrag;
1.3468 - };
1.3469 - })(document.createDocumentFragment);
1.3470 - }
1.3471 -})();(function(undefined) {
1.3472 -
1.3473 - var componentLoadingOperationUniqueId = 0;
1.3474 -
1.3475 - ko.bindingHandlers['component'] = {
1.3476 - 'init': function(element, valueAccessor, ignored1, ignored2, bindingContext) {
1.3477 - var currentViewModel,
1.3478 - currentLoadingOperationId,
1.3479 - disposeAssociatedComponentViewModel = function () {
1.3480 - var currentViewModelDispose = currentViewModel && currentViewModel['dispose'];
1.3481 - if (typeof currentViewModelDispose === 'function') {
1.3482 - currentViewModelDispose.call(currentViewModel);
1.3483 - }
1.3484 -
1.3485 - // Any in-flight loading operation is no longer relevant, so make sure we ignore its completion
1.3486 - currentLoadingOperationId = null;
1.3487 - };
1.3488 -
1.3489 - ko.utils.domNodeDisposal.addDisposeCallback(element, disposeAssociatedComponentViewModel);
1.3490 -
1.3491 - ko.computed(function () {
1.3492 - var value = ko.utils.unwrapObservable(valueAccessor()),
1.3493 - componentName, componentParams;
1.3494 -
1.3495 - if (typeof value === 'string') {
1.3496 - componentName = value;
1.3497 - } else {
1.3498 - componentName = ko.utils.unwrapObservable(value['name']);
1.3499 - componentParams = ko.utils.unwrapObservable(value['params']);
1.3500 - }
1.3501 -
1.3502 - if (!componentName) {
1.3503 - throw new Error('No component name specified');
1.3504 - }
1.3505 -
1.3506 - var loadingOperationId = currentLoadingOperationId = ++componentLoadingOperationUniqueId;
1.3507 - ko.components.get(componentName, function(componentDefinition) {
1.3508 - // If this is not the current load operation for this element, ignore it.
1.3509 - if (currentLoadingOperationId !== loadingOperationId) {
1.3510 - return;
1.3511 - }
1.3512 -
1.3513 - // Clean up previous state
1.3514 - disposeAssociatedComponentViewModel();
1.3515 -
1.3516 - // Instantiate and bind new component. Implicitly this cleans any old DOM nodes.
1.3517 - if (!componentDefinition) {
1.3518 - throw new Error('Unknown component \'' + componentName + '\'');
1.3519 - }
1.3520 - cloneTemplateIntoElement(componentName, componentDefinition, element);
1.3521 - var componentViewModel = createViewModel(componentDefinition, element, componentParams),
1.3522 - childBindingContext = bindingContext['createChildContext'](componentViewModel);
1.3523 - currentViewModel = componentViewModel;
1.3524 - ko.applyBindingsToDescendants(childBindingContext, element);
1.3525 - });
1.3526 - }, null, { disposeWhenNodeIsRemoved: element });
1.3527 -
1.3528 - return { 'controlsDescendantBindings': true };
1.3529 - }
1.3530 - };
1.3531 -
1.3532 - ko.virtualElements.allowedBindings['component'] = true;
1.3533 -
1.3534 - function cloneTemplateIntoElement(componentName, componentDefinition, element) {
1.3535 - var template = componentDefinition['template'];
1.3536 - if (!template) {
1.3537 - throw new Error('Component \'' + componentName + '\' has no template');
1.3538 - }
1.3539 -
1.3540 - var clonedNodesArray = ko.utils.cloneNodes(template);
1.3541 - ko.virtualElements.setDomNodeChildren(element, clonedNodesArray);
1.3542 - }
1.3543 -
1.3544 - function createViewModel(componentDefinition, element, componentParams) {
1.3545 - var componentViewModelFactory = componentDefinition['createViewModel'];
1.3546 - return componentViewModelFactory
1.3547 - ? componentViewModelFactory.call(componentDefinition, componentParams, { element: element })
1.3548 - : componentParams; // Template-only component
1.3549 - }
1.3550 -
1.3551 -})();
1.3552 -var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
1.3553 -ko.bindingHandlers['attr'] = {
1.3554 - 'update': function(element, valueAccessor, allBindings) {
1.3555 - var value = ko.utils.unwrapObservable(valueAccessor()) || {};
1.3556 - ko.utils.objectForEach(value, function(attrName, attrValue) {
1.3557 - attrValue = ko.utils.unwrapObservable(attrValue);
1.3558 -
1.3559 - // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
1.3560 - // when someProp is a "no value"-like value (strictly null, false, or undefined)
1.3561 - // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
1.3562 - var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
1.3563 - if (toRemove)
1.3564 - element.removeAttribute(attrName);
1.3565 -
1.3566 - // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
1.3567 - // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
1.3568 - // but instead of figuring out the mode, we'll just set the attribute through the Javascript
1.3569 - // property for IE <= 8.
1.3570 - if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
1.3571 - attrName = attrHtmlToJavascriptMap[attrName];
1.3572 - if (toRemove)
1.3573 - element.removeAttribute(attrName);
1.3574 - else
1.3575 - element[attrName] = attrValue;
1.3576 - } else if (!toRemove) {
1.3577 - element.setAttribute(attrName, attrValue.toString());
1.3578 - }
1.3579 -
1.3580 - // Treat "name" specially - although you can think of it as an attribute, it also needs
1.3581 - // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
1.3582 - // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
1.3583 - // entirely, and there's no strong reason to allow for such casing in HTML.
1.3584 - if (attrName === "name") {
1.3585 - ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
1.3586 - }
1.3587 - });
1.3588 - }
1.3589 -};
1.3590 -(function() {
1.3591 -
1.3592 -ko.bindingHandlers['checked'] = {
1.3593 - 'after': ['value', 'attr'],
1.3594 - 'init': function (element, valueAccessor, allBindings) {
1.3595 - var checkedValue = ko.pureComputed(function() {
1.3596 - // Treat "value" like "checkedValue" when it is included with "checked" binding
1.3597 - if (allBindings['has']('checkedValue')) {
1.3598 - return ko.utils.unwrapObservable(allBindings.get('checkedValue'));
1.3599 - } else if (allBindings['has']('value')) {
1.3600 - return ko.utils.unwrapObservable(allBindings.get('value'));
1.3601 - }
1.3602 -
1.3603 - return element.value;
1.3604 - });
1.3605 -
1.3606 - function updateModel() {
1.3607 - // This updates the model value from the view value.
1.3608 - // It runs in response to DOM events (click) and changes in checkedValue.
1.3609 - var isChecked = element.checked,
1.3610 - elemValue = useCheckedValue ? checkedValue() : isChecked;
1.3611 -
1.3612 - // When we're first setting up this computed, don't change any model state.
1.3613 - if (ko.computedContext.isInitial()) {
1.3614 - return;
1.3615 - }
1.3616 -
1.3617 - // We can ignore unchecked radio buttons, because some other radio
1.3618 - // button will be getting checked, and that one can take care of updating state.
1.3619 - if (isRadio && !isChecked) {
1.3620 - return;
1.3621 - }
1.3622 -
1.3623 - var modelValue = ko.dependencyDetection.ignore(valueAccessor);
1.3624 - if (isValueArray) {
1.3625 - if (oldElemValue !== elemValue) {
1.3626 - // When we're responding to the checkedValue changing, and the element is
1.3627 - // currently checked, replace the old elem value with the new elem value
1.3628 - // in the model array.
1.3629 - if (isChecked) {
1.3630 - ko.utils.addOrRemoveItem(modelValue, elemValue, true);
1.3631 - ko.utils.addOrRemoveItem(modelValue, oldElemValue, false);
1.3632 - }
1.3633 -
1.3634 - oldElemValue = elemValue;
1.3635 - } else {
1.3636 - // When we're responding to the user having checked/unchecked a checkbox,
1.3637 - // add/remove the element value to the model array.
1.3638 - ko.utils.addOrRemoveItem(modelValue, elemValue, isChecked);
1.3639 - }
1.3640 - } else {
1.3641 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'checked', elemValue, true);
1.3642 - }
1.3643 - };
1.3644 -
1.3645 - function updateView() {
1.3646 - // This updates the view value from the model value.
1.3647 - // It runs in response to changes in the bound (checked) value.
1.3648 - var modelValue = ko.utils.unwrapObservable(valueAccessor());
1.3649 -
1.3650 - if (isValueArray) {
1.3651 - // When a checkbox is bound to an array, being checked represents its value being present in that array
1.3652 - element.checked = ko.utils.arrayIndexOf(modelValue, checkedValue()) >= 0;
1.3653 - } else if (isCheckbox) {
1.3654 - // When a checkbox is bound to any other value (not an array), being checked represents the value being trueish
1.3655 - element.checked = modelValue;
1.3656 - } else {
1.3657 - // For radio buttons, being checked means that the radio button's value corresponds to the model value
1.3658 - element.checked = (checkedValue() === modelValue);
1.3659 - }
1.3660 - };
1.3661 -
1.3662 - var isCheckbox = element.type == "checkbox",
1.3663 - isRadio = element.type == "radio";
1.3664 -
1.3665 - // Only bind to check boxes and radio buttons
1.3666 - if (!isCheckbox && !isRadio) {
1.3667 - return;
1.3668 - }
1.3669 -
1.3670 - var isValueArray = isCheckbox && (ko.utils.unwrapObservable(valueAccessor()) instanceof Array),
1.3671 - oldElemValue = isValueArray ? checkedValue() : undefined,
1.3672 - useCheckedValue = isRadio || isValueArray;
1.3673 -
1.3674 - // IE 6 won't allow radio buttons to be selected unless they have a name
1.3675 - if (isRadio && !element.name)
1.3676 - ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
1.3677 -
1.3678 - // Set up two computeds to update the binding:
1.3679 -
1.3680 - // The first responds to changes in the checkedValue value and to element clicks
1.3681 - ko.computed(updateModel, null, { disposeWhenNodeIsRemoved: element });
1.3682 - ko.utils.registerEventHandler(element, "click", updateModel);
1.3683 -
1.3684 - // The second responds to changes in the model value (the one associated with the checked binding)
1.3685 - ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
1.3686 - }
1.3687 -};
1.3688 -ko.expressionRewriting.twoWayBindings['checked'] = true;
1.3689 -
1.3690 -ko.bindingHandlers['checkedValue'] = {
1.3691 - 'update': function (element, valueAccessor) {
1.3692 - element.value = ko.utils.unwrapObservable(valueAccessor());
1.3693 - }
1.3694 -};
1.3695 -
1.3696 -})();var classesWrittenByBindingKey = '__ko__cssValue';
1.3697 -ko.bindingHandlers['css'] = {
1.3698 - 'update': function (element, valueAccessor) {
1.3699 - var value = ko.utils.unwrapObservable(valueAccessor());
1.3700 - if (typeof value == "object") {
1.3701 - ko.utils.objectForEach(value, function(className, shouldHaveClass) {
1.3702 - shouldHaveClass = ko.utils.unwrapObservable(shouldHaveClass);
1.3703 - ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
1.3704 - });
1.3705 - } else {
1.3706 - value = String(value || ''); // Make sure we don't try to store or set a non-string value
1.3707 - ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
1.3708 - element[classesWrittenByBindingKey] = value;
1.3709 - ko.utils.toggleDomNodeCssClass(element, value, true);
1.3710 - }
1.3711 - }
1.3712 -};
1.3713 -ko.bindingHandlers['enable'] = {
1.3714 - 'update': function (element, valueAccessor) {
1.3715 - var value = ko.utils.unwrapObservable(valueAccessor());
1.3716 - if (value && element.disabled)
1.3717 - element.removeAttribute("disabled");
1.3718 - else if ((!value) && (!element.disabled))
1.3719 - element.disabled = true;
1.3720 - }
1.3721 -};
1.3722 -
1.3723 -ko.bindingHandlers['disable'] = {
1.3724 - 'update': function (element, valueAccessor) {
1.3725 - ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
1.3726 - }
1.3727 -};
1.3728 -// For certain common events (currently just 'click'), allow a simplified data-binding syntax
1.3729 -// e.g. click:handler instead of the usual full-length event:{click:handler}
1.3730 -function makeEventHandlerShortcut(eventName) {
1.3731 - ko.bindingHandlers[eventName] = {
1.3732 - 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
1.3733 - var newValueAccessor = function () {
1.3734 - var result = {};
1.3735 - result[eventName] = valueAccessor();
1.3736 - return result;
1.3737 - };
1.3738 - return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindings, viewModel, bindingContext);
1.3739 - }
1.3740 - }
1.3741 -}
1.3742 -
1.3743 -ko.bindingHandlers['event'] = {
1.3744 - 'init' : function (element, valueAccessor, allBindings, viewModel, bindingContext) {
1.3745 - var eventsToHandle = valueAccessor() || {};
1.3746 - ko.utils.objectForEach(eventsToHandle, function(eventName) {
1.3747 - if (typeof eventName == "string") {
1.3748 - ko.utils.registerEventHandler(element, eventName, function (event) {
1.3749 - var handlerReturnValue;
1.3750 - var handlerFunction = valueAccessor()[eventName];
1.3751 - if (!handlerFunction)
1.3752 - return;
1.3753 -
1.3754 - try {
1.3755 - // Take all the event args, and prefix with the viewmodel
1.3756 - var argsForHandler = ko.utils.makeArray(arguments);
1.3757 - viewModel = bindingContext['$data'];
1.3758 - argsForHandler.unshift(viewModel);
1.3759 - handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
1.3760 - } finally {
1.3761 - if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
1.3762 - if (event.preventDefault)
1.3763 - event.preventDefault();
1.3764 - else
1.3765 - event.returnValue = false;
1.3766 - }
1.3767 - }
1.3768 -
1.3769 - var bubble = allBindings.get(eventName + 'Bubble') !== false;
1.3770 - if (!bubble) {
1.3771 - event.cancelBubble = true;
1.3772 - if (event.stopPropagation)
1.3773 - event.stopPropagation();
1.3774 - }
1.3775 - });
1.3776 - }
1.3777 - });
1.3778 - }
1.3779 -};
1.3780 -// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
1.3781 -// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
1.3782 -ko.bindingHandlers['foreach'] = {
1.3783 - makeTemplateValueAccessor: function(valueAccessor) {
1.3784 - return function() {
1.3785 - var modelValue = valueAccessor(),
1.3786 - unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
1.3787 -
1.3788 - // If unwrappedValue is the array, pass in the wrapped value on its own
1.3789 - // The value will be unwrapped and tracked within the template binding
1.3790 - // (See https://github.com/SteveSanderson/knockout/issues/523)
1.3791 - if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
1.3792 - return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
1.3793 -
1.3794 - // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
1.3795 - ko.utils.unwrapObservable(modelValue);
1.3796 - return {
1.3797 - 'foreach': unwrappedValue['data'],
1.3798 - 'as': unwrappedValue['as'],
1.3799 - 'includeDestroyed': unwrappedValue['includeDestroyed'],
1.3800 - 'afterAdd': unwrappedValue['afterAdd'],
1.3801 - 'beforeRemove': unwrappedValue['beforeRemove'],
1.3802 - 'afterRender': unwrappedValue['afterRender'],
1.3803 - 'beforeMove': unwrappedValue['beforeMove'],
1.3804 - 'afterMove': unwrappedValue['afterMove'],
1.3805 - 'templateEngine': ko.nativeTemplateEngine.instance
1.3806 - };
1.3807 - };
1.3808 - },
1.3809 - 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
1.3810 - return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
1.3811 - },
1.3812 - 'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
1.3813 - return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindings, viewModel, bindingContext);
1.3814 - }
1.3815 -};
1.3816 -ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
1.3817 -ko.virtualElements.allowedBindings['foreach'] = true;
1.3818 -var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
1.3819 -var hasfocusLastValue = '__ko_hasfocusLastValue';
1.3820 -ko.bindingHandlers['hasfocus'] = {
1.3821 - 'init': function(element, valueAccessor, allBindings) {
1.3822 - var handleElementFocusChange = function(isFocused) {
1.3823 - // Where possible, ignore which event was raised and determine focus state using activeElement,
1.3824 - // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
1.3825 - // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
1.3826 - // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
1.3827 - // from calling 'blur()' on the element when it loses focus.
1.3828 - // Discussion at https://github.com/SteveSanderson/knockout/pull/352
1.3829 - element[hasfocusUpdatingProperty] = true;
1.3830 - var ownerDoc = element.ownerDocument;
1.3831 - if ("activeElement" in ownerDoc) {
1.3832 - var active;
1.3833 - try {
1.3834 - active = ownerDoc.activeElement;
1.3835 - } catch(e) {
1.3836 - // IE9 throws if you access activeElement during page load (see issue #703)
1.3837 - active = ownerDoc.body;
1.3838 - }
1.3839 - isFocused = (active === element);
1.3840 - }
1.3841 - var modelValue = valueAccessor();
1.3842 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'hasfocus', isFocused, true);
1.3843 -
1.3844 - //cache the latest value, so we can avoid unnecessarily calling focus/blur in the update function
1.3845 - element[hasfocusLastValue] = isFocused;
1.3846 - element[hasfocusUpdatingProperty] = false;
1.3847 - };
1.3848 - var handleElementFocusIn = handleElementFocusChange.bind(null, true);
1.3849 - var handleElementFocusOut = handleElementFocusChange.bind(null, false);
1.3850 -
1.3851 - ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
1.3852 - ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
1.3853 - ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
1.3854 - ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
1.3855 - },
1.3856 - 'update': function(element, valueAccessor) {
1.3857 - var value = !!ko.utils.unwrapObservable(valueAccessor()); //force boolean to compare with last value
1.3858 - if (!element[hasfocusUpdatingProperty] && element[hasfocusLastValue] !== value) {
1.3859 - value ? element.focus() : element.blur();
1.3860 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
1.3861 - }
1.3862 - }
1.3863 -};
1.3864 -ko.expressionRewriting.twoWayBindings['hasfocus'] = true;
1.3865 -
1.3866 -ko.bindingHandlers['hasFocus'] = ko.bindingHandlers['hasfocus']; // Make "hasFocus" an alias
1.3867 -ko.expressionRewriting.twoWayBindings['hasFocus'] = true;
1.3868 -ko.bindingHandlers['html'] = {
1.3869 - 'init': function() {
1.3870 - // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
1.3871 - return { 'controlsDescendantBindings': true };
1.3872 - },
1.3873 - 'update': function (element, valueAccessor) {
1.3874 - // setHtml will unwrap the value if needed
1.3875 - ko.utils.setHtml(element, valueAccessor());
1.3876 - }
1.3877 -};
1.3878 -// Makes a binding like with or if
1.3879 -function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
1.3880 - ko.bindingHandlers[bindingKey] = {
1.3881 - 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
1.3882 - var didDisplayOnLastUpdate,
1.3883 - savedNodes;
1.3884 - ko.computed(function() {
1.3885 - var dataValue = ko.utils.unwrapObservable(valueAccessor()),
1.3886 - shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
1.3887 - isFirstRender = !savedNodes,
1.3888 - needsRefresh = isFirstRender || isWith || (shouldDisplay !== didDisplayOnLastUpdate);
1.3889 -
1.3890 - if (needsRefresh) {
1.3891 - // Save a copy of the inner nodes on the initial update, but only if we have dependencies.
1.3892 - if (isFirstRender && ko.computedContext.getDependenciesCount()) {
1.3893 - savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
1.3894 - }
1.3895 -
1.3896 - if (shouldDisplay) {
1.3897 - if (!isFirstRender) {
1.3898 - ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes));
1.3899 - }
1.3900 - ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
1.3901 - } else {
1.3902 - ko.virtualElements.emptyNode(element);
1.3903 - }
1.3904 -
1.3905 - didDisplayOnLastUpdate = shouldDisplay;
1.3906 - }
1.3907 - }, null, { disposeWhenNodeIsRemoved: element });
1.3908 - return { 'controlsDescendantBindings': true };
1.3909 - }
1.3910 - };
1.3911 - ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
1.3912 - ko.virtualElements.allowedBindings[bindingKey] = true;
1.3913 -}
1.3914 -
1.3915 -// Construct the actual binding handlers
1.3916 -makeWithIfBinding('if');
1.3917 -makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
1.3918 -makeWithIfBinding('with', true /* isWith */, false /* isNot */,
1.3919 - function(bindingContext, dataValue) {
1.3920 - return bindingContext['createChildContext'](dataValue);
1.3921 - }
1.3922 -);
1.3923 -var captionPlaceholder = {};
1.3924 -ko.bindingHandlers['options'] = {
1.3925 - 'init': function(element) {
1.3926 - if (ko.utils.tagNameLower(element) !== "select")
1.3927 - throw new Error("options binding applies only to SELECT elements");
1.3928 -
1.3929 - // Remove all existing <option>s.
1.3930 - while (element.length > 0) {
1.3931 - element.remove(0);
1.3932 - }
1.3933 -
1.3934 - // Ensures that the binding processor doesn't try to bind the options
1.3935 - return { 'controlsDescendantBindings': true };
1.3936 - },
1.3937 - 'update': function (element, valueAccessor, allBindings) {
1.3938 - function selectedOptions() {
1.3939 - return ko.utils.arrayFilter(element.options, function (node) { return node.selected; });
1.3940 - }
1.3941 -
1.3942 - var selectWasPreviouslyEmpty = element.length == 0;
1.3943 - var previousScrollTop = (!selectWasPreviouslyEmpty && element.multiple) ? element.scrollTop : null;
1.3944 - var unwrappedArray = ko.utils.unwrapObservable(valueAccessor());
1.3945 - var includeDestroyed = allBindings.get('optionsIncludeDestroyed');
1.3946 - var arrayToDomNodeChildrenOptions = {};
1.3947 - var captionValue;
1.3948 - var filteredArray;
1.3949 - var previousSelectedValues;
1.3950 -
1.3951 - if (element.multiple) {
1.3952 - previousSelectedValues = ko.utils.arrayMap(selectedOptions(), ko.selectExtensions.readValue);
1.3953 - } else {
1.3954 - previousSelectedValues = element.selectedIndex >= 0 ? [ ko.selectExtensions.readValue(element.options[element.selectedIndex]) ] : [];
1.3955 - }
1.3956 -
1.3957 - if (unwrappedArray) {
1.3958 - if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
1.3959 - unwrappedArray = [unwrappedArray];
1.3960 -
1.3961 - // Filter out any entries marked as destroyed
1.3962 - filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
1.3963 - return includeDestroyed || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
1.3964 - });
1.3965 -
1.3966 - // If caption is included, add it to the array
1.3967 - if (allBindings['has']('optionsCaption')) {
1.3968 - captionValue = ko.utils.unwrapObservable(allBindings.get('optionsCaption'));
1.3969 - // If caption value is null or undefined, don't show a caption
1.3970 - if (captionValue !== null && captionValue !== undefined) {
1.3971 - filteredArray.unshift(captionPlaceholder);
1.3972 - }
1.3973 - }
1.3974 - } else {
1.3975 - // If a falsy value is provided (e.g. null), we'll simply empty the select element
1.3976 - }
1.3977 -
1.3978 - function applyToObject(object, predicate, defaultValue) {
1.3979 - var predicateType = typeof predicate;
1.3980 - if (predicateType == "function") // Given a function; run it against the data value
1.3981 - return predicate(object);
1.3982 - else if (predicateType == "string") // Given a string; treat it as a property name on the data value
1.3983 - return object[predicate];
1.3984 - else // Given no optionsText arg; use the data value itself
1.3985 - return defaultValue;
1.3986 - }
1.3987 -
1.3988 - // The following functions can run at two different times:
1.3989 - // The first is when the whole array is being updated directly from this binding handler.
1.3990 - // The second is when an observable value for a specific array entry is updated.
1.3991 - // oldOptions will be empty in the first case, but will be filled with the previously generated option in the second.
1.3992 - var itemUpdate = false;
1.3993 - function optionForArrayItem(arrayEntry, index, oldOptions) {
1.3994 - if (oldOptions.length) {
1.3995 - previousSelectedValues = oldOptions[0].selected ? [ ko.selectExtensions.readValue(oldOptions[0]) ] : [];
1.3996 - itemUpdate = true;
1.3997 - }
1.3998 - var option = element.ownerDocument.createElement("option");
1.3999 - if (arrayEntry === captionPlaceholder) {
1.4000 - ko.utils.setTextContent(option, allBindings.get('optionsCaption'));
1.4001 - ko.selectExtensions.writeValue(option, undefined);
1.4002 - } else {
1.4003 - // Apply a value to the option element
1.4004 - var optionValue = applyToObject(arrayEntry, allBindings.get('optionsValue'), arrayEntry);
1.4005 - ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
1.4006 -
1.4007 - // Apply some text to the option element
1.4008 - var optionText = applyToObject(arrayEntry, allBindings.get('optionsText'), optionValue);
1.4009 - ko.utils.setTextContent(option, optionText);
1.4010 - }
1.4011 - return [option];
1.4012 - }
1.4013 -
1.4014 - // By using a beforeRemove callback, we delay the removal until after new items are added. This fixes a selection
1.4015 - // problem in IE<=8 and Firefox. See https://github.com/knockout/knockout/issues/1208
1.4016 - arrayToDomNodeChildrenOptions['beforeRemove'] =
1.4017 - function (option) {
1.4018 - element.removeChild(option);
1.4019 - };
1.4020 -
1.4021 - function setSelectionCallback(arrayEntry, newOptions) {
1.4022 - // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
1.4023 - // That's why we first added them without selection. Now it's time to set the selection.
1.4024 - if (previousSelectedValues.length) {
1.4025 - var isSelected = ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[0])) >= 0;
1.4026 - ko.utils.setOptionNodeSelectionState(newOptions[0], isSelected);
1.4027 -
1.4028 - // If this option was changed from being selected during a single-item update, notify the change
1.4029 - if (itemUpdate && !isSelected)
1.4030 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
1.4031 - }
1.4032 - }
1.4033 -
1.4034 - var callback = setSelectionCallback;
1.4035 - if (allBindings['has']('optionsAfterRender')) {
1.4036 - callback = function(arrayEntry, newOptions) {
1.4037 - setSelectionCallback(arrayEntry, newOptions);
1.4038 - ko.dependencyDetection.ignore(allBindings.get('optionsAfterRender'), null, [newOptions[0], arrayEntry !== captionPlaceholder ? arrayEntry : undefined]);
1.4039 - }
1.4040 - }
1.4041 -
1.4042 - ko.utils.setDomNodeChildrenFromArrayMapping(element, filteredArray, optionForArrayItem, arrayToDomNodeChildrenOptions, callback);
1.4043 -
1.4044 - ko.dependencyDetection.ignore(function () {
1.4045 - if (allBindings.get('valueAllowUnset') && allBindings['has']('value')) {
1.4046 - // The model value is authoritative, so make sure its value is the one selected
1.4047 - ko.selectExtensions.writeValue(element, ko.utils.unwrapObservable(allBindings.get('value')), true /* allowUnset */);
1.4048 - } else {
1.4049 - // Determine if the selection has changed as a result of updating the options list
1.4050 - var selectionChanged;
1.4051 - if (element.multiple) {
1.4052 - // For a multiple-select box, compare the new selection count to the previous one
1.4053 - // But if nothing was selected before, the selection can't have changed
1.4054 - selectionChanged = previousSelectedValues.length && selectedOptions().length < previousSelectedValues.length;
1.4055 - } else {
1.4056 - // For a single-select box, compare the current value to the previous value
1.4057 - // But if nothing was selected before or nothing is selected now, just look for a change in selection
1.4058 - selectionChanged = (previousSelectedValues.length && element.selectedIndex >= 0)
1.4059 - ? (ko.selectExtensions.readValue(element.options[element.selectedIndex]) !== previousSelectedValues[0])
1.4060 - : (previousSelectedValues.length || element.selectedIndex >= 0);
1.4061 - }
1.4062 -
1.4063 - // Ensure consistency between model value and selected option.
1.4064 - // If the dropdown was changed so that selection is no longer the same,
1.4065 - // notify the value or selectedOptions binding.
1.4066 - if (selectionChanged) {
1.4067 - ko.utils.triggerEvent(element, "change");
1.4068 - }
1.4069 - }
1.4070 - });
1.4071 -
1.4072 - // Workaround for IE bug
1.4073 - ko.utils.ensureSelectElementIsRenderedCorrectly(element);
1.4074 -
1.4075 - if (previousScrollTop && Math.abs(previousScrollTop - element.scrollTop) > 20)
1.4076 - element.scrollTop = previousScrollTop;
1.4077 - }
1.4078 -};
1.4079 -ko.bindingHandlers['options'].optionValueDomDataKey = ko.utils.domData.nextKey();
1.4080 -ko.bindingHandlers['selectedOptions'] = {
1.4081 - 'after': ['options', 'foreach'],
1.4082 - 'init': function (element, valueAccessor, allBindings) {
1.4083 - ko.utils.registerEventHandler(element, "change", function () {
1.4084 - var value = valueAccessor(), valueToWrite = [];
1.4085 - ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
1.4086 - if (node.selected)
1.4087 - valueToWrite.push(ko.selectExtensions.readValue(node));
1.4088 - });
1.4089 - ko.expressionRewriting.writeValueToProperty(value, allBindings, 'selectedOptions', valueToWrite);
1.4090 - });
1.4091 - },
1.4092 - 'update': function (element, valueAccessor) {
1.4093 - if (ko.utils.tagNameLower(element) != "select")
1.4094 - throw new Error("values binding applies only to SELECT elements");
1.4095 -
1.4096 - var newValue = ko.utils.unwrapObservable(valueAccessor());
1.4097 - if (newValue && typeof newValue.length == "number") {
1.4098 - ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
1.4099 - var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
1.4100 - ko.utils.setOptionNodeSelectionState(node, isSelected);
1.4101 - });
1.4102 - }
1.4103 - }
1.4104 -};
1.4105 -ko.expressionRewriting.twoWayBindings['selectedOptions'] = true;
1.4106 -ko.bindingHandlers['style'] = {
1.4107 - 'update': function (element, valueAccessor) {
1.4108 - var value = ko.utils.unwrapObservable(valueAccessor() || {});
1.4109 - ko.utils.objectForEach(value, function(styleName, styleValue) {
1.4110 - styleValue = ko.utils.unwrapObservable(styleValue);
1.4111 -
1.4112 - if (styleValue === null || styleValue === undefined || styleValue === false) {
1.4113 - // Empty string removes the value, whereas null/undefined have no effect
1.4114 - styleValue = "";
1.4115 - }
1.4116 -
1.4117 - element.style[styleName] = styleValue;
1.4118 - });
1.4119 - }
1.4120 -};
1.4121 -ko.bindingHandlers['submit'] = {
1.4122 - 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
1.4123 - if (typeof valueAccessor() != "function")
1.4124 - throw new Error("The value for a submit binding must be a function");
1.4125 - ko.utils.registerEventHandler(element, "submit", function (event) {
1.4126 - var handlerReturnValue;
1.4127 - var value = valueAccessor();
1.4128 - try { handlerReturnValue = value.call(bindingContext['$data'], element); }
1.4129 - finally {
1.4130 - if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
1.4131 - if (event.preventDefault)
1.4132 - event.preventDefault();
1.4133 - else
1.4134 - event.returnValue = false;
1.4135 - }
1.4136 - }
1.4137 - });
1.4138 - }
1.4139 -};
1.4140 -ko.bindingHandlers['text'] = {
1.4141 - 'init': function() {
1.4142 - // Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications).
1.4143 - // It should also make things faster, as we no longer have to consider whether the text node might be bindable.
1.4144 - return { 'controlsDescendantBindings': true };
1.4145 - },
1.4146 - 'update': function (element, valueAccessor) {
1.4147 - ko.utils.setTextContent(element, valueAccessor());
1.4148 - }
1.4149 -};
1.4150 -ko.virtualElements.allowedBindings['text'] = true;
1.4151 -(function () {
1.4152 -
1.4153 -if (window && window.navigator) {
1.4154 - var parseVersion = function (matches) {
1.4155 - if (matches) {
1.4156 - return parseFloat(matches[1]);
1.4157 - }
1.4158 - };
1.4159 -
1.4160 - // Detect various browser versions because some old versions don't fully support the 'input' event
1.4161 - var operaVersion = window.opera && window.opera.version && parseInt(window.opera.version()),
1.4162 - userAgent = window.navigator.userAgent,
1.4163 - safariVersion = parseVersion(userAgent.match(/^(?:(?!chrome).)*version\/([^ ]*) safari/i)),
1.4164 - firefoxVersion = parseVersion(userAgent.match(/Firefox\/([^ ]*)/));
1.4165 -}
1.4166 -
1.4167 -// IE 8 and 9 have bugs that prevent the normal events from firing when the value changes.
1.4168 -// But it does fire the 'selectionchange' event on many of those, presumably because the
1.4169 -// cursor is moving and that counts as the selection changing. The 'selectionchange' event is
1.4170 -// fired at the document level only and doesn't directly indicate which element changed. We
1.4171 -// set up just one event handler for the document and use 'activeElement' to determine which
1.4172 -// element was changed.
1.4173 -if (ko.utils.ieVersion < 10) {
1.4174 - var selectionChangeRegisteredName = ko.utils.domData.nextKey(),
1.4175 - selectionChangeHandlerName = ko.utils.domData.nextKey();
1.4176 - var selectionChangeHandler = function(event) {
1.4177 - var target = this.activeElement,
1.4178 - handler = target && ko.utils.domData.get(target, selectionChangeHandlerName);
1.4179 - if (handler) {
1.4180 - handler(event);
1.4181 - }
1.4182 - };
1.4183 - var registerForSelectionChangeEvent = function (element, handler) {
1.4184 - var ownerDoc = element.ownerDocument;
1.4185 - if (!ko.utils.domData.get(ownerDoc, selectionChangeRegisteredName)) {
1.4186 - ko.utils.domData.set(ownerDoc, selectionChangeRegisteredName, true);
1.4187 - ko.utils.registerEventHandler(ownerDoc, 'selectionchange', selectionChangeHandler);
1.4188 - }
1.4189 - ko.utils.domData.set(element, selectionChangeHandlerName, handler);
1.4190 - };
1.4191 -}
1.4192 -
1.4193 -ko.bindingHandlers['textInput'] = {
1.4194 - 'init': function (element, valueAccessor, allBindings) {
1.4195 -
1.4196 - var previousElementValue = element.value,
1.4197 - timeoutHandle,
1.4198 - elementValueBeforeEvent;
1.4199 -
1.4200 - var updateModel = function (event) {
1.4201 - clearTimeout(timeoutHandle);
1.4202 - elementValueBeforeEvent = timeoutHandle = undefined;
1.4203 -
1.4204 - var elementValue = element.value;
1.4205 - if (previousElementValue !== elementValue) {
1.4206 - // Provide a way for tests to know exactly which event was processed
1.4207 - if (DEBUG && event) element['_ko_textInputProcessedEvent'] = event.type;
1.4208 - previousElementValue = elementValue;
1.4209 - ko.expressionRewriting.writeValueToProperty(valueAccessor(), allBindings, 'textInput', elementValue);
1.4210 - }
1.4211 - };
1.4212 -
1.4213 - var deferUpdateModel = function (event) {
1.4214 - if (!timeoutHandle) {
1.4215 - // The elementValueBeforeEvent variable is set *only* during the brief gap between an
1.4216 - // event firing and the updateModel function running. This allows us to ignore model
1.4217 - // updates that are from the previous state of the element, usually due to techniques
1.4218 - // such as rateLimit. Such updates, if not ignored, can cause keystrokes to be lost.
1.4219 - elementValueBeforeEvent = element.value;
1.4220 - var handler = DEBUG ? updateModel.bind(element, {type: event.type}) : updateModel;
1.4221 - timeoutHandle = setTimeout(handler, 4);
1.4222 - }
1.4223 - };
1.4224 -
1.4225 - var updateView = function () {
1.4226 - var modelValue = ko.utils.unwrapObservable(valueAccessor());
1.4227 -
1.4228 - if (modelValue === null || modelValue === undefined) {
1.4229 - modelValue = '';
1.4230 - }
1.4231 -
1.4232 - if (elementValueBeforeEvent !== undefined && modelValue === elementValueBeforeEvent) {
1.4233 - setTimeout(updateView, 4);
1.4234 - return;
1.4235 - }
1.4236 -
1.4237 - // Update the element only if the element and model are different. On some browsers, updating the value
1.4238 - // will move the cursor to the end of the input, which would be bad while the user is typing.
1.4239 - if (element.value !== modelValue) {
1.4240 - previousElementValue = modelValue; // Make sure we ignore events (propertychange) that result from updating the value
1.4241 - element.value = modelValue;
1.4242 - }
1.4243 - };
1.4244 -
1.4245 - var onEvent = function (event, handler) {
1.4246 - ko.utils.registerEventHandler(element, event, handler);
1.4247 - };
1.4248 -
1.4249 - if (DEBUG && ko.bindingHandlers['textInput']['_forceUpdateOn']) {
1.4250 - // Provide a way for tests to specify exactly which events are bound
1.4251 - ko.utils.arrayForEach(ko.bindingHandlers['textInput']['_forceUpdateOn'], function(eventName) {
1.4252 - if (eventName.slice(0,5) == 'after') {
1.4253 - onEvent(eventName.slice(5), deferUpdateModel);
1.4254 - } else {
1.4255 - onEvent(eventName, updateModel);
1.4256 - }
1.4257 - });
1.4258 - } else {
1.4259 - if (ko.utils.ieVersion < 10) {
1.4260 - // Internet Explorer <= 8 doesn't support the 'input' event, but does include 'propertychange' that fires whenever
1.4261 - // any property of an element changes. Unlike 'input', it also fires if a property is changed from JavaScript code,
1.4262 - // but that's an acceptable compromise for this binding. IE 9 does support 'input', but since it doesn't fire it
1.4263 - // when using autocomplete, we'll use 'propertychange' for it also.
1.4264 - onEvent('propertychange', function(event) {
1.4265 - if (event.propertyName === 'value') {
1.4266 - updateModel(event);
1.4267 - }
1.4268 - });
1.4269 -
1.4270 - if (ko.utils.ieVersion == 8) {
1.4271 - // IE 8 has a bug where it fails to fire 'propertychange' on the first update following a value change from
1.4272 - // JavaScript code. It also doesn't fire if you clear the entire value. To fix this, we bind to the following
1.4273 - // events too.
1.4274 - onEvent('keyup', updateModel); // A single keystoke
1.4275 - onEvent('keydown', updateModel); // The first character when a key is held down
1.4276 - }
1.4277 - if (ko.utils.ieVersion >= 8) {
1.4278 - // Internet Explorer 9 doesn't fire the 'input' event when deleting text, including using
1.4279 - // the backspace, delete, or ctrl-x keys, clicking the 'x' to clear the input, dragging text
1.4280 - // out of the field, and cutting or deleting text using the context menu. 'selectionchange'
1.4281 - // can detect all of those except dragging text out of the field, for which we use 'dragend'.
1.4282 - // These are also needed in IE8 because of the bug described above.
1.4283 - registerForSelectionChangeEvent(element, updateModel); // 'selectionchange' covers cut, paste, drop, delete, etc.
1.4284 - onEvent('dragend', deferUpdateModel);
1.4285 - }
1.4286 - } else {
1.4287 - // All other supported browsers support the 'input' event, which fires whenever the content of the element is changed
1.4288 - // through the user interface.
1.4289 - onEvent('input', updateModel);
1.4290 -
1.4291 - if (safariVersion < 5 && ko.utils.tagNameLower(element) === "textarea") {
1.4292 - // Safari <5 doesn't fire the 'input' event for <textarea> elements (it does fire 'textInput'
1.4293 - // but only when typing). So we'll just catch as much as we can with keydown, cut, and paste.
1.4294 - onEvent('keydown', deferUpdateModel);
1.4295 - onEvent('paste', deferUpdateModel);
1.4296 - onEvent('cut', deferUpdateModel);
1.4297 - } else if (operaVersion < 11) {
1.4298 - // Opera 10 doesn't always fire the 'input' event for cut, paste, undo & drop operations.
1.4299 - // We can try to catch some of those using 'keydown'.
1.4300 - onEvent('keydown', deferUpdateModel);
1.4301 - } else if (firefoxVersion < 4.0) {
1.4302 - // Firefox <= 3.6 doesn't fire the 'input' event when text is filled in through autocomplete
1.4303 - onEvent('DOMAutoComplete', updateModel);
1.4304 -
1.4305 - // Firefox <=3.5 doesn't fire the 'input' event when text is dropped into the input.
1.4306 - onEvent('dragdrop', updateModel); // <3.5
1.4307 - onEvent('drop', updateModel); // 3.5
1.4308 - }
1.4309 - }
1.4310 - }
1.4311 -
1.4312 - // Bind to the change event so that we can catch programmatic updates of the value that fire this event.
1.4313 - onEvent('change', updateModel);
1.4314 -
1.4315 - ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
1.4316 - }
1.4317 -};
1.4318 -ko.expressionRewriting.twoWayBindings['textInput'] = true;
1.4319 -
1.4320 -// textinput is an alias for textInput
1.4321 -ko.bindingHandlers['textinput'] = {
1.4322 - // preprocess is the only way to set up a full alias
1.4323 - 'preprocess': function (value, name, addBinding) {
1.4324 - addBinding('textInput', value);
1.4325 - }
1.4326 -};
1.4327 -
1.4328 -})();ko.bindingHandlers['uniqueName'] = {
1.4329 - 'init': function (element, valueAccessor) {
1.4330 - if (valueAccessor()) {
1.4331 - var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
1.4332 - ko.utils.setElementName(element, name);
1.4333 - }
1.4334 - }
1.4335 -};
1.4336 -ko.bindingHandlers['uniqueName'].currentIndex = 0;
1.4337 -ko.bindingHandlers['value'] = {
1.4338 - 'after': ['options', 'foreach'],
1.4339 - 'init': function (element, valueAccessor, allBindings) {
1.4340 - // If the value binding is placed on a radio/checkbox, then just pass through to checkedValue and quit
1.4341 - if (element.tagName.toLowerCase() == "input" && (element.type == "checkbox" || element.type == "radio")) {
1.4342 - ko.applyBindingAccessorsToNode(element, { 'checkedValue': valueAccessor });
1.4343 - return;
1.4344 - }
1.4345 -
1.4346 - // Always catch "change" event; possibly other events too if asked
1.4347 - var eventsToCatch = ["change"];
1.4348 - var requestedEventsToCatch = allBindings.get("valueUpdate");
1.4349 - var propertyChangedFired = false;
1.4350 - var elementValueBeforeEvent = null;
1.4351 -
1.4352 - if (requestedEventsToCatch) {
1.4353 - if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
1.4354 - requestedEventsToCatch = [requestedEventsToCatch];
1.4355 - ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
1.4356 - eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
1.4357 - }
1.4358 -
1.4359 - var valueUpdateHandler = function() {
1.4360 - elementValueBeforeEvent = null;
1.4361 - propertyChangedFired = false;
1.4362 - var modelValue = valueAccessor();
1.4363 - var elementValue = ko.selectExtensions.readValue(element);
1.4364 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'value', elementValue);
1.4365 - }
1.4366 -
1.4367 - // Workaround for https://github.com/SteveSanderson/knockout/issues/122
1.4368 - // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
1.4369 - var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
1.4370 - && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
1.4371 - if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
1.4372 - ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
1.4373 - ko.utils.registerEventHandler(element, "focus", function () { propertyChangedFired = false });
1.4374 - ko.utils.registerEventHandler(element, "blur", function() {
1.4375 - if (propertyChangedFired) {
1.4376 - valueUpdateHandler();
1.4377 - }
1.4378 - });
1.4379 - }
1.4380 -
1.4381 - ko.utils.arrayForEach(eventsToCatch, function(eventName) {
1.4382 - // The syntax "after<eventname>" means "run the handler asynchronously after the event"
1.4383 - // This is useful, for example, to catch "keydown" events after the browser has updated the control
1.4384 - // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
1.4385 - var handler = valueUpdateHandler;
1.4386 - if (ko.utils.stringStartsWith(eventName, "after")) {
1.4387 - handler = function() {
1.4388 - // The elementValueBeforeEvent variable is non-null *only* during the brief gap between
1.4389 - // a keyX event firing and the valueUpdateHandler running, which is scheduled to happen
1.4390 - // at the earliest asynchronous opportunity. We store this temporary information so that
1.4391 - // if, between keyX and valueUpdateHandler, the underlying model value changes separately,
1.4392 - // we can overwrite that model value change with the value the user just typed. Otherwise,
1.4393 - // techniques like rateLimit can trigger model changes at critical moments that will
1.4394 - // override the user's inputs, causing keystrokes to be lost.
1.4395 - elementValueBeforeEvent = ko.selectExtensions.readValue(element);
1.4396 - setTimeout(valueUpdateHandler, 0);
1.4397 - };
1.4398 - eventName = eventName.substring("after".length);
1.4399 - }
1.4400 - ko.utils.registerEventHandler(element, eventName, handler);
1.4401 - });
1.4402 -
1.4403 - var updateFromModel = function () {
1.4404 - var newValue = ko.utils.unwrapObservable(valueAccessor());
1.4405 - var elementValue = ko.selectExtensions.readValue(element);
1.4406 -
1.4407 - if (elementValueBeforeEvent !== null && newValue === elementValueBeforeEvent) {
1.4408 - setTimeout(updateFromModel, 0);
1.4409 - return;
1.4410 - }
1.4411 -
1.4412 - var valueHasChanged = (newValue !== elementValue);
1.4413 -
1.4414 - if (valueHasChanged) {
1.4415 - if (ko.utils.tagNameLower(element) === "select") {
1.4416 - var allowUnset = allBindings.get('valueAllowUnset');
1.4417 - var applyValueAction = function () {
1.4418 - ko.selectExtensions.writeValue(element, newValue, allowUnset);
1.4419 - };
1.4420 - applyValueAction();
1.4421 -
1.4422 - if (!allowUnset && newValue !== ko.selectExtensions.readValue(element)) {
1.4423 - // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
1.4424 - // because you're not allowed to have a model value that disagrees with a visible UI selection.
1.4425 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
1.4426 - } else {
1.4427 - // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
1.4428 - // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
1.4429 - // to apply the value as well.
1.4430 - setTimeout(applyValueAction, 0);
1.4431 - }
1.4432 - } else {
1.4433 - ko.selectExtensions.writeValue(element, newValue);
1.4434 - }
1.4435 - }
1.4436 - };
1.4437 -
1.4438 - ko.computed(updateFromModel, null, { disposeWhenNodeIsRemoved: element });
1.4439 - },
1.4440 - 'update': function() {} // Keep for backwards compatibility with code that may have wrapped value binding
1.4441 -};
1.4442 -ko.expressionRewriting.twoWayBindings['value'] = true;
1.4443 -ko.bindingHandlers['visible'] = {
1.4444 - 'update': function (element, valueAccessor) {
1.4445 - var value = ko.utils.unwrapObservable(valueAccessor());
1.4446 - var isCurrentlyVisible = !(element.style.display == "none");
1.4447 - if (value && !isCurrentlyVisible)
1.4448 - element.style.display = "";
1.4449 - else if ((!value) && isCurrentlyVisible)
1.4450 - element.style.display = "none";
1.4451 - }
1.4452 -};
1.4453 -// 'click' is just a shorthand for the usual full-length event:{click:handler}
1.4454 -makeEventHandlerShortcut('click');
1.4455 -// If you want to make a custom template engine,
1.4456 -//
1.4457 -// [1] Inherit from this class (like ko.nativeTemplateEngine does)
1.4458 -// [2] Override 'renderTemplateSource', supplying a function with this signature:
1.4459 -//
1.4460 -// function (templateSource, bindingContext, options) {
1.4461 -// // - templateSource.text() is the text of the template you should render
1.4462 -// // - bindingContext.$data is the data you should pass into the template
1.4463 -// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
1.4464 -// // and bindingContext.$root available in the template too
1.4465 -// // - options gives you access to any other properties set on "data-bind: { template: options }"
1.4466 -// //
1.4467 -// // Return value: an array of DOM nodes
1.4468 -// }
1.4469 -//
1.4470 -// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
1.4471 -//
1.4472 -// function (script) {
1.4473 -// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
1.4474 -// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
1.4475 -// }
1.4476 -//
1.4477 -// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
1.4478 -// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
1.4479 -// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
1.4480 -
1.4481 -ko.templateEngine = function () { };
1.4482 -
1.4483 -ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
1.4484 - throw new Error("Override renderTemplateSource");
1.4485 -};
1.4486 -
1.4487 -ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
1.4488 - throw new Error("Override createJavaScriptEvaluatorBlock");
1.4489 -};
1.4490 -
1.4491 -ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
1.4492 - // Named template
1.4493 - if (typeof template == "string") {
1.4494 - templateDocument = templateDocument || document;
1.4495 - var elem = templateDocument.getElementById(template);
1.4496 - if (!elem)
1.4497 - throw new Error("Cannot find template with ID " + template);
1.4498 - return new ko.templateSources.domElement(elem);
1.4499 - } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
1.4500 - // Anonymous template
1.4501 - return new ko.templateSources.anonymousTemplate(template);
1.4502 - } else
1.4503 - throw new Error("Unknown template type: " + template);
1.4504 -};
1.4505 -
1.4506 -ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
1.4507 - var templateSource = this['makeTemplateSource'](template, templateDocument);
1.4508 - return this['renderTemplateSource'](templateSource, bindingContext, options);
1.4509 -};
1.4510 -
1.4511 -ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
1.4512 - // Skip rewriting if requested
1.4513 - if (this['allowTemplateRewriting'] === false)
1.4514 - return true;
1.4515 - return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
1.4516 -};
1.4517 -
1.4518 -ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
1.4519 - var templateSource = this['makeTemplateSource'](template, templateDocument);
1.4520 - var rewritten = rewriterCallback(templateSource['text']());
1.4521 - templateSource['text'](rewritten);
1.4522 - templateSource['data']("isRewritten", true);
1.4523 -};
1.4524 -
1.4525 -ko.exportSymbol('templateEngine', ko.templateEngine);
1.4526 -
1.4527 -ko.templateRewriting = (function () {
1.4528 - var memoizeDataBindingAttributeSyntaxRegex = /(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi;
1.4529 - var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
1.4530 -
1.4531 - function validateDataBindValuesForRewriting(keyValueArray) {
1.4532 - var allValidators = ko.expressionRewriting.bindingRewriteValidators;
1.4533 - for (var i = 0; i < keyValueArray.length; i++) {
1.4534 - var key = keyValueArray[i]['key'];
1.4535 - if (allValidators.hasOwnProperty(key)) {
1.4536 - var validator = allValidators[key];
1.4537 -
1.4538 - if (typeof validator === "function") {
1.4539 - var possibleErrorMessage = validator(keyValueArray[i]['value']);
1.4540 - if (possibleErrorMessage)
1.4541 - throw new Error(possibleErrorMessage);
1.4542 - } else if (!validator) {
1.4543 - throw new Error("This template engine does not support the '" + key + "' binding within its templates");
1.4544 - }
1.4545 - }
1.4546 - }
1.4547 - }
1.4548 -
1.4549 - function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, nodeName, templateEngine) {
1.4550 - var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
1.4551 - validateDataBindValuesForRewriting(dataBindKeyValueArray);
1.4552 - var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray, {'valueAccessors':true});
1.4553 -
1.4554 - // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
1.4555 - // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
1.4556 - // extra indirection.
1.4557 - var applyBindingsToNextSiblingScript =
1.4558 - "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()},'" + nodeName.toLowerCase() + "')";
1.4559 - return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
1.4560 - }
1.4561 -
1.4562 - return {
1.4563 - ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
1.4564 - if (!templateEngine['isTemplateRewritten'](template, templateDocument))
1.4565 - templateEngine['rewriteTemplate'](template, function (htmlString) {
1.4566 - return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
1.4567 - }, templateDocument);
1.4568 - },
1.4569 -
1.4570 - memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
1.4571 - return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
1.4572 - return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[4], /* tagToRetain: */ arguments[1], /* nodeName: */ arguments[2], templateEngine);
1.4573 - }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
1.4574 - return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", /* nodeName: */ "#comment", templateEngine);
1.4575 - });
1.4576 - },
1.4577 -
1.4578 - applyMemoizedBindingsToNextSibling: function (bindings, nodeName) {
1.4579 - return ko.memoization.memoize(function (domNode, bindingContext) {
1.4580 - var nodeToBind = domNode.nextSibling;
1.4581 - if (nodeToBind && nodeToBind.nodeName.toLowerCase() === nodeName) {
1.4582 - ko.applyBindingAccessorsToNode(nodeToBind, bindings, bindingContext);
1.4583 - }
1.4584 - });
1.4585 - }
1.4586 - }
1.4587 -})();
1.4588 -
1.4589 -
1.4590 -// Exported only because it has to be referenced by string lookup from within rewritten template
1.4591 -ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
1.4592 -(function() {
1.4593 - // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
1.4594 - // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
1.4595 - //
1.4596 - // Two are provided by default:
1.4597 - // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
1.4598 - // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
1.4599 - // without reading/writing the actual element text content, since it will be overwritten
1.4600 - // with the rendered template output.
1.4601 - // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
1.4602 - // Template sources need to have the following functions:
1.4603 - // text() - returns the template text from your storage location
1.4604 - // text(value) - writes the supplied template text to your storage location
1.4605 - // data(key) - reads values stored using data(key, value) - see below
1.4606 - // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
1.4607 - //
1.4608 - // Optionally, template sources can also have the following functions:
1.4609 - // nodes() - returns a DOM element containing the nodes of this template, where available
1.4610 - // nodes(value) - writes the given DOM element to your storage location
1.4611 - // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
1.4612 - // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
1.4613 - //
1.4614 - // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
1.4615 - // using and overriding "makeTemplateSource" to return an instance of your custom template source.
1.4616 -
1.4617 - ko.templateSources = {};
1.4618 -
1.4619 - // ---- ko.templateSources.domElement -----
1.4620 -
1.4621 - ko.templateSources.domElement = function(element) {
1.4622 - this.domElement = element;
1.4623 - }
1.4624 -
1.4625 - ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
1.4626 - var tagNameLower = ko.utils.tagNameLower(this.domElement),
1.4627 - elemContentsProperty = tagNameLower === "script" ? "text"
1.4628 - : tagNameLower === "textarea" ? "value"
1.4629 - : "innerHTML";
1.4630 -
1.4631 - if (arguments.length == 0) {
1.4632 - return this.domElement[elemContentsProperty];
1.4633 - } else {
1.4634 - var valueToWrite = arguments[0];
1.4635 - if (elemContentsProperty === "innerHTML")
1.4636 - ko.utils.setHtml(this.domElement, valueToWrite);
1.4637 - else
1.4638 - this.domElement[elemContentsProperty] = valueToWrite;
1.4639 - }
1.4640 - };
1.4641 -
1.4642 - var dataDomDataPrefix = ko.utils.domData.nextKey() + "_";
1.4643 - ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
1.4644 - if (arguments.length === 1) {
1.4645 - return ko.utils.domData.get(this.domElement, dataDomDataPrefix + key);
1.4646 - } else {
1.4647 - ko.utils.domData.set(this.domElement, dataDomDataPrefix + key, arguments[1]);
1.4648 - }
1.4649 - };
1.4650 -
1.4651 - // ---- ko.templateSources.anonymousTemplate -----
1.4652 - // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
1.4653 - // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
1.4654 - // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
1.4655 -
1.4656 - var anonymousTemplatesDomDataKey = ko.utils.domData.nextKey();
1.4657 - ko.templateSources.anonymousTemplate = function(element) {
1.4658 - this.domElement = element;
1.4659 - }
1.4660 - ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
1.4661 - ko.templateSources.anonymousTemplate.prototype.constructor = ko.templateSources.anonymousTemplate;
1.4662 - ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
1.4663 - if (arguments.length == 0) {
1.4664 - var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
1.4665 - if (templateData.textData === undefined && templateData.containerData)
1.4666 - templateData.textData = templateData.containerData.innerHTML;
1.4667 - return templateData.textData;
1.4668 - } else {
1.4669 - var valueToWrite = arguments[0];
1.4670 - ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
1.4671 - }
1.4672 - };
1.4673 - ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
1.4674 - if (arguments.length == 0) {
1.4675 - var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
1.4676 - return templateData.containerData;
1.4677 - } else {
1.4678 - var valueToWrite = arguments[0];
1.4679 - ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
1.4680 - }
1.4681 - };
1.4682 -
1.4683 - ko.exportSymbol('templateSources', ko.templateSources);
1.4684 - ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
1.4685 - ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
1.4686 -})();
1.4687 -(function () {
1.4688 - var _templateEngine;
1.4689 - ko.setTemplateEngine = function (templateEngine) {
1.4690 - if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
1.4691 - throw new Error("templateEngine must inherit from ko.templateEngine");
1.4692 - _templateEngine = templateEngine;
1.4693 - }
1.4694 -
1.4695 - function invokeForEachNodeInContinuousRange(firstNode, lastNode, action) {
1.4696 - var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
1.4697 - while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
1.4698 - nextInQueue = ko.virtualElements.nextSibling(node);
1.4699 - action(node, nextInQueue);
1.4700 - }
1.4701 - }
1.4702 -
1.4703 - function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
1.4704 - // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
1.4705 - // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
1.4706 - // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
1.4707 - // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
1.4708 - // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
1.4709 -
1.4710 - if (continuousNodeArray.length) {
1.4711 - var firstNode = continuousNodeArray[0],
1.4712 - lastNode = continuousNodeArray[continuousNodeArray.length - 1],
1.4713 - parentNode = firstNode.parentNode,
1.4714 - provider = ko.bindingProvider['instance'],
1.4715 - preprocessNode = provider['preprocessNode'];
1.4716 -
1.4717 - if (preprocessNode) {
1.4718 - invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node, nextNodeInRange) {
1.4719 - var nodePreviousSibling = node.previousSibling;
1.4720 - var newNodes = preprocessNode.call(provider, node);
1.4721 - if (newNodes) {
1.4722 - if (node === firstNode)
1.4723 - firstNode = newNodes[0] || nextNodeInRange;
1.4724 - if (node === lastNode)
1.4725 - lastNode = newNodes[newNodes.length - 1] || nodePreviousSibling;
1.4726 - }
1.4727 - });
1.4728 -
1.4729 - // Because preprocessNode can change the nodes, including the first and last nodes, update continuousNodeArray to match.
1.4730 - // We need the full set, including inner nodes, because the unmemoize step might remove the first node (and so the real
1.4731 - // first node needs to be in the array).
1.4732 - continuousNodeArray.length = 0;
1.4733 - if (!firstNode) { // preprocessNode might have removed all the nodes, in which case there's nothing left to do
1.4734 - return;
1.4735 - }
1.4736 - if (firstNode === lastNode) {
1.4737 - continuousNodeArray.push(firstNode);
1.4738 - } else {
1.4739 - continuousNodeArray.push(firstNode, lastNode);
1.4740 - ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
1.4741 - }
1.4742 - }
1.4743 -
1.4744 - // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
1.4745 - // whereas a regular applyBindings won't introduce new memoized nodes
1.4746 - invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
1.4747 - if (node.nodeType === 1 || node.nodeType === 8)
1.4748 - ko.applyBindings(bindingContext, node);
1.4749 - });
1.4750 - invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
1.4751 - if (node.nodeType === 1 || node.nodeType === 8)
1.4752 - ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
1.4753 - });
1.4754 -
1.4755 - // Make sure any changes done by applyBindings or unmemoize are reflected in the array
1.4756 - ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
1.4757 - }
1.4758 - }
1.4759 -
1.4760 - function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
1.4761 - return nodeOrNodeArray.nodeType ? nodeOrNodeArray
1.4762 - : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
1.4763 - : null;
1.4764 - }
1.4765 -
1.4766 - function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
1.4767 - options = options || {};
1.4768 - var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
1.4769 - var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
1.4770 - var templateEngineToUse = (options['templateEngine'] || _templateEngine);
1.4771 - ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
1.4772 - var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
1.4773 -
1.4774 - // Loosely check result is an array of DOM nodes
1.4775 - if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
1.4776 - throw new Error("Template engine must return an array of DOM nodes");
1.4777 -
1.4778 - var haveAddedNodesToParent = false;
1.4779 - switch (renderMode) {
1.4780 - case "replaceChildren":
1.4781 - ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
1.4782 - haveAddedNodesToParent = true;
1.4783 - break;
1.4784 - case "replaceNode":
1.4785 - ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
1.4786 - haveAddedNodesToParent = true;
1.4787 - break;
1.4788 - case "ignoreTargetNode": break;
1.4789 - default:
1.4790 - throw new Error("Unknown renderMode: " + renderMode);
1.4791 - }
1.4792 -
1.4793 - if (haveAddedNodesToParent) {
1.4794 - activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
1.4795 - if (options['afterRender'])
1.4796 - ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
1.4797 - }
1.4798 -
1.4799 - return renderedNodesArray;
1.4800 - }
1.4801 -
1.4802 - function resolveTemplateName(template, data, context) {
1.4803 - // The template can be specified as:
1.4804 - if (ko.isObservable(template)) {
1.4805 - // 1. An observable, with string value
1.4806 - return template();
1.4807 - } else if (typeof template === 'function') {
1.4808 - // 2. A function of (data, context) returning a string
1.4809 - return template(data, context);
1.4810 - } else {
1.4811 - // 3. A string
1.4812 - return template;
1.4813 - }
1.4814 - }
1.4815 -
1.4816 - ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
1.4817 - options = options || {};
1.4818 - if ((options['templateEngine'] || _templateEngine) == undefined)
1.4819 - throw new Error("Set a template engine before calling renderTemplate");
1.4820 - renderMode = renderMode || "replaceChildren";
1.4821 -
1.4822 - if (targetNodeOrNodeArray) {
1.4823 - var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
1.4824 -
1.4825 - var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
1.4826 - var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
1.4827 -
1.4828 - return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
1.4829 - function () {
1.4830 - // Ensure we've got a proper binding context to work with
1.4831 - var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
1.4832 - ? dataOrBindingContext
1.4833 - : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
1.4834 -
1.4835 - var templateName = resolveTemplateName(template, bindingContext['$data'], bindingContext),
1.4836 - renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
1.4837 -
1.4838 - if (renderMode == "replaceNode") {
1.4839 - targetNodeOrNodeArray = renderedNodesArray;
1.4840 - firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
1.4841 - }
1.4842 - },
1.4843 - null,
1.4844 - { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
1.4845 - );
1.4846 - } else {
1.4847 - // 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.4848 - return ko.memoization.memoize(function (domNode) {
1.4849 - ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
1.4850 - });
1.4851 - }
1.4852 - };
1.4853 -
1.4854 - ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
1.4855 - // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
1.4856 - // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
1.4857 - var arrayItemContext;
1.4858 -
1.4859 - // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
1.4860 - var executeTemplateForArrayItem = function (arrayValue, index) {
1.4861 - // Support selecting template as a function of the data being rendered
1.4862 - arrayItemContext = parentBindingContext['createChildContext'](arrayValue, options['as'], function(context) {
1.4863 - context['$index'] = index;
1.4864 - });
1.4865 -
1.4866 - var templateName = resolveTemplateName(template, arrayValue, arrayItemContext);
1.4867 - return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
1.4868 - }
1.4869 -
1.4870 - // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
1.4871 - var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
1.4872 - activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
1.4873 - if (options['afterRender'])
1.4874 - options['afterRender'](addedNodesArray, arrayValue);
1.4875 - };
1.4876 -
1.4877 - return ko.dependentObservable(function () {
1.4878 - var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
1.4879 - if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
1.4880 - unwrappedArray = [unwrappedArray];
1.4881 -
1.4882 - // Filter out any entries marked as destroyed
1.4883 - var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
1.4884 - return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
1.4885 - });
1.4886 -
1.4887 - // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
1.4888 - // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
1.4889 - ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
1.4890 -
1.4891 - }, null, { disposeWhenNodeIsRemoved: targetNode });
1.4892 - };
1.4893 -
1.4894 - var templateComputedDomDataKey = ko.utils.domData.nextKey();
1.4895 - function disposeOldComputedAndStoreNewOne(element, newComputed) {
1.4896 - var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
1.4897 - if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
1.4898 - oldComputed.dispose();
1.4899 - ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
1.4900 - }
1.4901 -
1.4902 - ko.bindingHandlers['template'] = {
1.4903 - 'init': function(element, valueAccessor) {
1.4904 - // Support anonymous templates
1.4905 - var bindingValue = ko.utils.unwrapObservable(valueAccessor());
1.4906 - if (typeof bindingValue == "string" || bindingValue['name']) {
1.4907 - // It's a named template - clear the element
1.4908 - ko.virtualElements.emptyNode(element);
1.4909 - } else {
1.4910 - // It's an anonymous template - store the element contents, then clear the element
1.4911 - var templateNodes = ko.virtualElements.childNodes(element),
1.4912 - container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
1.4913 - new ko.templateSources.anonymousTemplate(element)['nodes'](container);
1.4914 - }
1.4915 - return { 'controlsDescendantBindings': true };
1.4916 - },
1.4917 - 'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
1.4918 - var value = valueAccessor(),
1.4919 - dataValue,
1.4920 - options = ko.utils.unwrapObservable(value),
1.4921 - shouldDisplay = true,
1.4922 - templateComputed = null,
1.4923 - templateName;
1.4924 -
1.4925 - if (typeof options == "string") {
1.4926 - templateName = value;
1.4927 - options = {};
1.4928 - } else {
1.4929 - templateName = options['name'];
1.4930 -
1.4931 - // Support "if"/"ifnot" conditions
1.4932 - if ('if' in options)
1.4933 - shouldDisplay = ko.utils.unwrapObservable(options['if']);
1.4934 - if (shouldDisplay && 'ifnot' in options)
1.4935 - shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
1.4936 -
1.4937 - dataValue = ko.utils.unwrapObservable(options['data']);
1.4938 - }
1.4939 -
1.4940 - if ('foreach' in options) {
1.4941 - // Render once for each data point (treating data set as empty if shouldDisplay==false)
1.4942 - var dataArray = (shouldDisplay && options['foreach']) || [];
1.4943 - templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
1.4944 - } else if (!shouldDisplay) {
1.4945 - ko.virtualElements.emptyNode(element);
1.4946 - } else {
1.4947 - // Render once for this single data point (or use the viewModel if no data was provided)
1.4948 - var innerBindingContext = ('data' in options) ?
1.4949 - bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
1.4950 - bindingContext; // Given no explicit 'data' value, we retain the same binding context
1.4951 - templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
1.4952 - }
1.4953 -
1.4954 - // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
1.4955 - disposeOldComputedAndStoreNewOne(element, templateComputed);
1.4956 - }
1.4957 - };
1.4958 -
1.4959 - // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
1.4960 - ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
1.4961 - var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
1.4962 -
1.4963 - if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
1.4964 - 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.4965 -
1.4966 - if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
1.4967 - return null; // Named templates can be rewritten, so return "no error"
1.4968 - return "This template engine does not support anonymous templates nested within its templates";
1.4969 - };
1.4970 -
1.4971 - ko.virtualElements.allowedBindings['template'] = true;
1.4972 -})();
1.4973 -
1.4974 -ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
1.4975 -ko.exportSymbol('renderTemplate', ko.renderTemplate);
1.4976 -// Go through the items that have been added and deleted and try to find matches between them.
1.4977 -ko.utils.findMovesInArrayComparison = function (left, right, limitFailedCompares) {
1.4978 - if (left.length && right.length) {
1.4979 - var failedCompares, l, r, leftItem, rightItem;
1.4980 - for (failedCompares = l = 0; (!limitFailedCompares || failedCompares < limitFailedCompares) && (leftItem = left[l]); ++l) {
1.4981 - for (r = 0; rightItem = right[r]; ++r) {
1.4982 - if (leftItem['value'] === rightItem['value']) {
1.4983 - leftItem['moved'] = rightItem['index'];
1.4984 - rightItem['moved'] = leftItem['index'];
1.4985 - right.splice(r, 1); // This item is marked as moved; so remove it from right list
1.4986 - failedCompares = r = 0; // Reset failed compares count because we're checking for consecutive failures
1.4987 - break;
1.4988 - }
1.4989 - }
1.4990 - failedCompares += r;
1.4991 - }
1.4992 - }
1.4993 -};
1.4994 -
1.4995 -ko.utils.compareArrays = (function () {
1.4996 - var statusNotInOld = 'added', statusNotInNew = 'deleted';
1.4997 -
1.4998 - // Simple calculation based on Levenshtein distance.
1.4999 - function compareArrays(oldArray, newArray, options) {
1.5000 - // For backward compatibility, if the third arg is actually a bool, interpret
1.5001 - // it as the old parameter 'dontLimitMoves'. Newer code should use { dontLimitMoves: true }.
1.5002 - options = (typeof options === 'boolean') ? { 'dontLimitMoves': options } : (options || {});
1.5003 - oldArray = oldArray || [];
1.5004 - newArray = newArray || [];
1.5005 -
1.5006 - if (oldArray.length <= newArray.length)
1.5007 - return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, options);
1.5008 - else
1.5009 - return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, options);
1.5010 - }
1.5011 -
1.5012 - function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, options) {
1.5013 - var myMin = Math.min,
1.5014 - myMax = Math.max,
1.5015 - editDistanceMatrix = [],
1.5016 - smlIndex, smlIndexMax = smlArray.length,
1.5017 - bigIndex, bigIndexMax = bigArray.length,
1.5018 - compareRange = (bigIndexMax - smlIndexMax) || 1,
1.5019 - maxDistance = smlIndexMax + bigIndexMax + 1,
1.5020 - thisRow, lastRow,
1.5021 - bigIndexMaxForRow, bigIndexMinForRow;
1.5022 -
1.5023 - for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
1.5024 - lastRow = thisRow;
1.5025 - editDistanceMatrix.push(thisRow = []);
1.5026 - bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
1.5027 - bigIndexMinForRow = myMax(0, smlIndex - 1);
1.5028 - for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
1.5029 - if (!bigIndex)
1.5030 - thisRow[bigIndex] = smlIndex + 1;
1.5031 - else if (!smlIndex) // Top row - transform empty array into new array via additions
1.5032 - thisRow[bigIndex] = bigIndex + 1;
1.5033 - else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
1.5034 - thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
1.5035 - else {
1.5036 - var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
1.5037 - var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
1.5038 - thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
1.5039 - }
1.5040 - }
1.5041 - }
1.5042 -
1.5043 - var editScript = [], meMinusOne, notInSml = [], notInBig = [];
1.5044 - for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
1.5045 - meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
1.5046 - if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
1.5047 - notInSml.push(editScript[editScript.length] = { // added
1.5048 - 'status': statusNotInSml,
1.5049 - 'value': bigArray[--bigIndex],
1.5050 - 'index': bigIndex });
1.5051 - } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
1.5052 - notInBig.push(editScript[editScript.length] = { // deleted
1.5053 - 'status': statusNotInBig,
1.5054 - 'value': smlArray[--smlIndex],
1.5055 - 'index': smlIndex });
1.5056 - } else {
1.5057 - --bigIndex;
1.5058 - --smlIndex;
1.5059 - if (!options['sparse']) {
1.5060 - editScript.push({
1.5061 - 'status': "retained",
1.5062 - 'value': bigArray[bigIndex] });
1.5063 - }
1.5064 - }
1.5065 - }
1.5066 -
1.5067 - // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
1.5068 - // smlIndexMax keeps the time complexity of this algorithm linear.
1.5069 - ko.utils.findMovesInArrayComparison(notInSml, notInBig, smlIndexMax * 10);
1.5070 -
1.5071 - return editScript.reverse();
1.5072 - }
1.5073 -
1.5074 - return compareArrays;
1.5075 -})();
1.5076 -
1.5077 -ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
1.5078 -(function () {
1.5079 - // Objective:
1.5080 - // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
1.5081 - // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
1.5082 - // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
1.5083 - // 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.5084 - // previously mapped - retain those nodes, and just insert/delete other ones
1.5085 -
1.5086 - // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
1.5087 - // You can use this, for example, to activate bindings on those nodes.
1.5088 -
1.5089 - function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
1.5090 - // Map this array value inside a dependentObservable so we re-map when any dependency changes
1.5091 - var mappedNodes = [];
1.5092 - var dependentObservable = ko.dependentObservable(function() {
1.5093 - var newMappedNodes = mapping(valueToMap, index, ko.utils.fixUpContinuousNodeArray(mappedNodes, containerNode)) || [];
1.5094 -
1.5095 - // On subsequent evaluations, just replace the previously-inserted DOM nodes
1.5096 - if (mappedNodes.length > 0) {
1.5097 - ko.utils.replaceDomNodes(mappedNodes, newMappedNodes);
1.5098 - if (callbackAfterAddingNodes)
1.5099 - ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
1.5100 - }
1.5101 -
1.5102 - // Replace the contents of the mappedNodes array, thereby updating the record
1.5103 - // of which nodes would be deleted if valueToMap was itself later removed
1.5104 - mappedNodes.length = 0;
1.5105 - ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
1.5106 - }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return !ko.utils.anyDomNodeIsAttachedToDocument(mappedNodes); } });
1.5107 - return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
1.5108 - }
1.5109 -
1.5110 - var lastMappingResultDomDataKey = ko.utils.domData.nextKey();
1.5111 -
1.5112 - ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
1.5113 - // Compare the provided array against the previous one
1.5114 - array = array || [];
1.5115 - options = options || {};
1.5116 - var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
1.5117 - var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
1.5118 - var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
1.5119 - var editScript = ko.utils.compareArrays(lastArray, array, options['dontLimitMoves']);
1.5120 -
1.5121 - // Build the new mapping result
1.5122 - var newMappingResult = [];
1.5123 - var lastMappingResultIndex = 0;
1.5124 - var newMappingResultIndex = 0;
1.5125 -
1.5126 - var nodesToDelete = [];
1.5127 - var itemsToProcess = [];
1.5128 - var itemsForBeforeRemoveCallbacks = [];
1.5129 - var itemsForMoveCallbacks = [];
1.5130 - var itemsForAfterAddCallbacks = [];
1.5131 - var mapData;
1.5132 -
1.5133 - function itemMovedOrRetained(editScriptIndex, oldPosition) {
1.5134 - mapData = lastMappingResult[oldPosition];
1.5135 - if (newMappingResultIndex !== oldPosition)
1.5136 - itemsForMoveCallbacks[editScriptIndex] = mapData;
1.5137 - // Since updating the index might change the nodes, do so before calling fixUpContinuousNodeArray
1.5138 - mapData.indexObservable(newMappingResultIndex++);
1.5139 - ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode);
1.5140 - newMappingResult.push(mapData);
1.5141 - itemsToProcess.push(mapData);
1.5142 - }
1.5143 -
1.5144 - function callCallback(callback, items) {
1.5145 - if (callback) {
1.5146 - for (var i = 0, n = items.length; i < n; i++) {
1.5147 - if (items[i]) {
1.5148 - ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
1.5149 - callback(node, i, items[i].arrayEntry);
1.5150 - });
1.5151 - }
1.5152 - }
1.5153 - }
1.5154 - }
1.5155 -
1.5156 - for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
1.5157 - movedIndex = editScriptItem['moved'];
1.5158 - switch (editScriptItem['status']) {
1.5159 - case "deleted":
1.5160 - if (movedIndex === undefined) {
1.5161 - mapData = lastMappingResult[lastMappingResultIndex];
1.5162 -
1.5163 - // Stop tracking changes to the mapping for these nodes
1.5164 - if (mapData.dependentObservable)
1.5165 - mapData.dependentObservable.dispose();
1.5166 -
1.5167 - // Queue these nodes for later removal
1.5168 - nodesToDelete.push.apply(nodesToDelete, ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode));
1.5169 - if (options['beforeRemove']) {
1.5170 - itemsForBeforeRemoveCallbacks[i] = mapData;
1.5171 - itemsToProcess.push(mapData);
1.5172 - }
1.5173 - }
1.5174 - lastMappingResultIndex++;
1.5175 - break;
1.5176 -
1.5177 - case "retained":
1.5178 - itemMovedOrRetained(i, lastMappingResultIndex++);
1.5179 - break;
1.5180 -
1.5181 - case "added":
1.5182 - if (movedIndex !== undefined) {
1.5183 - itemMovedOrRetained(i, movedIndex);
1.5184 - } else {
1.5185 - mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
1.5186 - newMappingResult.push(mapData);
1.5187 - itemsToProcess.push(mapData);
1.5188 - if (!isFirstExecution)
1.5189 - itemsForAfterAddCallbacks[i] = mapData;
1.5190 - }
1.5191 - break;
1.5192 - }
1.5193 - }
1.5194 -
1.5195 - // Call beforeMove first before any changes have been made to the DOM
1.5196 - callCallback(options['beforeMove'], itemsForMoveCallbacks);
1.5197 -
1.5198 - // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
1.5199 - ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
1.5200 -
1.5201 - // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
1.5202 - for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
1.5203 - // Get nodes for newly added items
1.5204 - if (!mapData.mappedNodes)
1.5205 - ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
1.5206 -
1.5207 - // Put nodes in the right place if they aren't there already
1.5208 - for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
1.5209 - if (node !== nextNode)
1.5210 - ko.virtualElements.insertAfter(domNode, node, lastNode);
1.5211 - }
1.5212 -
1.5213 - // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
1.5214 - if (!mapData.initialized && callbackAfterAddingNodes) {
1.5215 - callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
1.5216 - mapData.initialized = true;
1.5217 - }
1.5218 - }
1.5219 -
1.5220 - // If there's a beforeRemove callback, call it after reordering.
1.5221 - // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
1.5222 - // some sort of animation, which is why we first reorder the nodes that will be removed. If the
1.5223 - // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
1.5224 - // Perhaps we'll make that change in the future if this scenario becomes more common.
1.5225 - callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
1.5226 -
1.5227 - // Finally call afterMove and afterAdd callbacks
1.5228 - callCallback(options['afterMove'], itemsForMoveCallbacks);
1.5229 - callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
1.5230 -
1.5231 - // Store a copy of the array items we just considered so we can difference it next time
1.5232 - ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
1.5233 - }
1.5234 -})();
1.5235 -
1.5236 -ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
1.5237 -ko.nativeTemplateEngine = function () {
1.5238 - this['allowTemplateRewriting'] = false;
1.5239 -}
1.5240 -
1.5241 -ko.nativeTemplateEngine.prototype = new ko.templateEngine();
1.5242 -ko.nativeTemplateEngine.prototype.constructor = ko.nativeTemplateEngine;
1.5243 -ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
1.5244 - var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
1.5245 - templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
1.5246 - templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
1.5247 -
1.5248 - if (templateNodes) {
1.5249 - return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
1.5250 - } else {
1.5251 - var templateText = templateSource['text']();
1.5252 - return ko.utils.parseHtmlFragment(templateText);
1.5253 - }
1.5254 -};
1.5255 -
1.5256 -ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
1.5257 -ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
1.5258 -
1.5259 -ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
1.5260 -(function() {
1.5261 - ko.jqueryTmplTemplateEngine = function () {
1.5262 - // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
1.5263 - // doesn't expose a version number, so we have to infer it.
1.5264 - // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
1.5265 - // which KO internally refers to as version "2", so older versions are no longer detected.
1.5266 - var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
1.5267 - if (!jQueryInstance || !(jQueryInstance['tmpl']))
1.5268 - return 0;
1.5269 - // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
1.5270 - try {
1.5271 - if (jQueryInstance['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
1.5272 - // Since 1.0.0pre, custom tags should append markup to an array called "__"
1.5273 - return 2; // Final version of jquery.tmpl
1.5274 - }
1.5275 - } catch(ex) { /* Apparently not the version we were looking for */ }
1.5276 -
1.5277 - return 1; // Any older version that we don't support
1.5278 - })();
1.5279 -
1.5280 - function ensureHasReferencedJQueryTemplates() {
1.5281 - if (jQueryTmplVersion < 2)
1.5282 - throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
1.5283 - }
1.5284 -
1.5285 - function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
1.5286 - return jQueryInstance['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
1.5287 - }
1.5288 -
1.5289 - this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
1.5290 - options = options || {};
1.5291 - ensureHasReferencedJQueryTemplates();
1.5292 -
1.5293 - // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
1.5294 - var precompiled = templateSource['data']('precompiled');
1.5295 - if (!precompiled) {
1.5296 - var templateText = templateSource['text']() || "";
1.5297 - // Wrap in "with($whatever.koBindingContext) { ... }"
1.5298 - templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
1.5299 -
1.5300 - precompiled = jQueryInstance['template'](null, templateText);
1.5301 - templateSource['data']('precompiled', precompiled);
1.5302 - }
1.5303 -
1.5304 - var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
1.5305 - var jQueryTemplateOptions = jQueryInstance['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
1.5306 -
1.5307 - var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
1.5308 - resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
1.5309 -
1.5310 - jQueryInstance['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
1.5311 - return resultNodes;
1.5312 - };
1.5313 -
1.5314 - this['createJavaScriptEvaluatorBlock'] = function(script) {
1.5315 - return "{{ko_code ((function() { return " + script + " })()) }}";
1.5316 - };
1.5317 -
1.5318 - this['addTemplate'] = function(templateName, templateMarkup) {
1.5319 - document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "<" + "/script>");
1.5320 - };
1.5321 -
1.5322 - if (jQueryTmplVersion > 0) {
1.5323 - jQueryInstance['tmpl']['tag']['ko_code'] = {
1.5324 - open: "__.push($1 || '');"
1.5325 - };
1.5326 - jQueryInstance['tmpl']['tag']['ko_with'] = {
1.5327 - open: "with($1) {",
1.5328 - close: "} "
1.5329 - };
1.5330 - }
1.5331 - };
1.5332 -
1.5333 - ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
1.5334 - ko.jqueryTmplTemplateEngine.prototype.constructor = ko.jqueryTmplTemplateEngine;
1.5335 -
1.5336 - // Use this one by default *only if jquery.tmpl is referenced*
1.5337 - var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
1.5338 - if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
1.5339 - ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
1.5340 -
1.5341 - ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
1.5342 -})();
1.5343 -}));
1.5344 -}());
1.5345 -})();