1.1 --- a/ko4j/src/main/java/org/netbeans/html/ko4j/Knockout.java Thu Aug 14 11:43:55 2014 +0200
1.2 +++ b/ko4j/src/main/java/org/netbeans/html/ko4j/Knockout.java Tue Aug 19 15:48:05 2014 +0200
1.3 @@ -57,7 +57,7 @@
1.4 *
1.5 * @author Jaroslav Tulach
1.6 */
1.7 -@JavaScriptResource("knockout-2.2.1.js")
1.8 +@JavaScriptResource("knockout-3.2.0.debug.js")
1.9 final class Knockout {
1.10 @JavaScriptBody(args = { "model", "prop", "oldValue", "newValue" },
1.11 wait4js = false,
1.12 @@ -78,6 +78,7 @@
1.13 );
1.14
1.15 @JavaScriptBody(args = { "bindings" }, wait4js = false, body =
1.16 + "ko.cleanNode(window.document.body);\n" +
1.17 "ko.applyBindings(bindings);\n"
1.18 )
1.19 native static void applyBindings(Object bindings);
1.20 @@ -96,6 +97,7 @@
1.21 body =
1.22 "ret['ko-fx.model'] = model;\n"
1.23 + "function koComputed(name, readOnly, value, prop) {\n"
1.24 + + " var trigger = ko.observable().extend({notify:'always'});"
1.25 + " function realGetter() {\n"
1.26 + " try {\n"
1.27 + " var v = prop.@org.apidesign.html.json.spi.PropertyBinding::getValue()();\n"
1.28 @@ -107,6 +109,7 @@
1.29 + " var activeGetter = function() { return value; };\n"
1.30 + " var bnd = {\n"
1.31 + " 'read': function() {\n"
1.32 + + " trigger();\n"
1.33 + " var r = activeGetter();\n"
1.34 + " activeGetter = realGetter;\n"
1.35 + " if (r) try { var br = r.valueOf(); } catch (err) {}\n"
1.36 @@ -121,10 +124,9 @@
1.37 + " };\n"
1.38 + " };\n"
1.39 + " var cmpt = ko['computed'](bnd);\n"
1.40 - + " var vhm = cmpt['valueHasMutated'];\n"
1.41 + " cmpt['valueHasMutated'] = function(val) {\n"
1.42 + " if (arguments.length === 1) activeGetter = function() { return val; };\n"
1.43 - + " vhm();\n"
1.44 + + " trigger.valueHasMutated();\n"
1.45 + " };\n"
1.46 + " ret[name] = cmpt;\n"
1.47 + "}\n"
2.1 --- a/ko4j/src/main/resources/org/netbeans/html/ko4j/knockout-2.2.1.js Thu Aug 14 11:43:55 2014 +0200
2.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
2.3 @@ -1,3595 +0,0 @@
2.4 -// Knockout JavaScript library v2.2.1
2.5 -// (c) Steven Sanderson - http://knockoutjs.com/
2.6 -// License: MIT (http://www.opensource.org/licenses/mit-license.php)
2.7 -
2.8 -(function(){
2.9 -var DEBUG=true;
2.10 -(function(window,document,navigator,jQuery,undefined){
2.11 -!function(factory) {
2.12 - // Support three module loading scenarios
2.13 - if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
2.14 - // [1] CommonJS/Node.js
2.15 - var target = module['exports'] || exports; // module.exports is for Node.js
2.16 - factory(target);
2.17 - } else if (typeof define === 'function' && define['amd']) {
2.18 - // [2] AMD anonymous module
2.19 - define(['exports'], factory);
2.20 - } else {
2.21 - // [3] No module loader (plain <script> tag) - put directly in global namespace
2.22 - factory(window['ko'] = {});
2.23 - }
2.24 -}(function(koExports){
2.25 -// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
2.26 -// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
2.27 -var ko = typeof koExports !== 'undefined' ? koExports : {};
2.28 -// Google Closure Compiler helpers (used only to make the minified file smaller)
2.29 -ko.exportSymbol = function(koPath, object) {
2.30 - var tokens = koPath.split(".");
2.31 -
2.32 - // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
2.33 - // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
2.34 - var target = ko;
2.35 -
2.36 - for (var i = 0; i < tokens.length - 1; i++)
2.37 - target = target[tokens[i]];
2.38 - target[tokens[tokens.length - 1]] = object;
2.39 -};
2.40 -ko.exportProperty = function(owner, publicName, object) {
2.41 - owner[publicName] = object;
2.42 -};
2.43 -ko.version = "2.2.1";
2.44 -
2.45 -ko.exportSymbol('version', ko.version);
2.46 -ko.utils = new (function () {
2.47 - var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
2.48 -
2.49 - // Represent the known event types in a compact way, then at runtime transform it into a hash with event name as key (for fast lookup)
2.50 - var knownEvents = {}, knownEventTypesByEventName = {};
2.51 - var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';
2.52 - knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
2.53 - knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
2.54 - for (var eventType in knownEvents) {
2.55 - var knownEventsForType = knownEvents[eventType];
2.56 - if (knownEventsForType.length) {
2.57 - for (var i = 0, j = knownEventsForType.length; i < j; i++)
2.58 - knownEventTypesByEventName[knownEventsForType[i]] = eventType;
2.59 - }
2.60 - }
2.61 - var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
2.62 -
2.63 - // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
2.64 - // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
2.65 - // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
2.66 - // If there is a future need to detect specific versions of IE10+, we will amend this.
2.67 - var ieVersion = (function() {
2.68 - var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
2.69 -
2.70 - // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
2.71 - while (
2.72 - div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
2.73 - iElems[0]
2.74 - );
2.75 - return version > 4 ? version : undefined;
2.76 - }());
2.77 - var isIe6 = ieVersion === 6,
2.78 - isIe7 = ieVersion === 7;
2.79 -
2.80 - function isClickOnCheckableElement(element, eventType) {
2.81 - if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
2.82 - if (eventType.toLowerCase() != "click") return false;
2.83 - var inputType = element.type;
2.84 - return (inputType == "checkbox") || (inputType == "radio");
2.85 - }
2.86 -
2.87 - return {
2.88 - fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
2.89 -
2.90 - arrayForEach: function (array, action) {
2.91 - for (var i = 0, j = array.length; i < j; i++)
2.92 - action(array[i]);
2.93 - },
2.94 -
2.95 - arrayIndexOf: function (array, item) {
2.96 - if (typeof Array.prototype.indexOf == "function")
2.97 - return Array.prototype.indexOf.call(array, item);
2.98 - for (var i = 0, j = array.length; i < j; i++)
2.99 - if (array[i] === item)
2.100 - return i;
2.101 - return -1;
2.102 - },
2.103 -
2.104 - arrayFirst: function (array, predicate, predicateOwner) {
2.105 - for (var i = 0, j = array.length; i < j; i++)
2.106 - if (predicate.call(predicateOwner, array[i]))
2.107 - return array[i];
2.108 - return null;
2.109 - },
2.110 -
2.111 - arrayRemoveItem: function (array, itemToRemove) {
2.112 - var index = ko.utils.arrayIndexOf(array, itemToRemove);
2.113 - if (index >= 0)
2.114 - array.splice(index, 1);
2.115 - },
2.116 -
2.117 - arrayGetDistinctValues: function (array) {
2.118 - array = array || [];
2.119 - var result = [];
2.120 - for (var i = 0, j = array.length; i < j; i++) {
2.121 - if (ko.utils.arrayIndexOf(result, array[i]) < 0)
2.122 - result.push(array[i]);
2.123 - }
2.124 - return result;
2.125 - },
2.126 -
2.127 - arrayMap: function (array, mapping) {
2.128 - array = array || [];
2.129 - var result = [];
2.130 - for (var i = 0, j = array.length; i < j; i++)
2.131 - result.push(mapping(array[i]));
2.132 - return result;
2.133 - },
2.134 -
2.135 - arrayFilter: function (array, predicate) {
2.136 - array = array || [];
2.137 - var result = [];
2.138 - for (var i = 0, j = array.length; i < j; i++)
2.139 - if (predicate(array[i]))
2.140 - result.push(array[i]);
2.141 - return result;
2.142 - },
2.143 -
2.144 - arrayPushAll: function (array, valuesToPush) {
2.145 - if (valuesToPush instanceof Array)
2.146 - array.push.apply(array, valuesToPush);
2.147 - else
2.148 - for (var i = 0, j = valuesToPush.length; i < j; i++)
2.149 - array.push(valuesToPush[i]);
2.150 - return array;
2.151 - },
2.152 -
2.153 - extend: function (target, source) {
2.154 - if (source) {
2.155 - for(var prop in source) {
2.156 - if(source.hasOwnProperty(prop)) {
2.157 - target[prop] = source[prop];
2.158 - }
2.159 - }
2.160 - }
2.161 - return target;
2.162 - },
2.163 -
2.164 - emptyDomNode: function (domNode) {
2.165 - while (domNode.firstChild) {
2.166 - ko.removeNode(domNode.firstChild);
2.167 - }
2.168 - },
2.169 -
2.170 - moveCleanedNodesToContainerElement: function(nodes) {
2.171 - // Ensure it's a real array, as we're about to reparent the nodes and
2.172 - // we don't want the underlying collection to change while we're doing that.
2.173 - var nodesArray = ko.utils.makeArray(nodes);
2.174 -
2.175 - var container = document.createElement('div');
2.176 - for (var i = 0, j = nodesArray.length; i < j; i++) {
2.177 - container.appendChild(ko.cleanNode(nodesArray[i]));
2.178 - }
2.179 - return container;
2.180 - },
2.181 -
2.182 - cloneNodes: function (nodesArray, shouldCleanNodes) {
2.183 - for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
2.184 - var clonedNode = nodesArray[i].cloneNode(true);
2.185 - newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
2.186 - }
2.187 - return newNodesArray;
2.188 - },
2.189 -
2.190 - setDomNodeChildren: function (domNode, childNodes) {
2.191 - ko.utils.emptyDomNode(domNode);
2.192 - if (childNodes) {
2.193 - for (var i = 0, j = childNodes.length; i < j; i++)
2.194 - domNode.appendChild(childNodes[i]);
2.195 - }
2.196 - },
2.197 -
2.198 - replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
2.199 - var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
2.200 - if (nodesToReplaceArray.length > 0) {
2.201 - var insertionPoint = nodesToReplaceArray[0];
2.202 - var parent = insertionPoint.parentNode;
2.203 - for (var i = 0, j = newNodesArray.length; i < j; i++)
2.204 - parent.insertBefore(newNodesArray[i], insertionPoint);
2.205 - for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
2.206 - ko.removeNode(nodesToReplaceArray[i]);
2.207 - }
2.208 - }
2.209 - },
2.210 -
2.211 - setOptionNodeSelectionState: function (optionNode, isSelected) {
2.212 - // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
2.213 - if (ieVersion < 7)
2.214 - optionNode.setAttribute("selected", isSelected);
2.215 - else
2.216 - optionNode.selected = isSelected;
2.217 - },
2.218 -
2.219 - stringTrim: function (string) {
2.220 - return (string || "").replace(stringTrimRegex, "");
2.221 - },
2.222 -
2.223 - stringTokenize: function (string, delimiter) {
2.224 - var result = [];
2.225 - var tokens = (string || "").split(delimiter);
2.226 - for (var i = 0, j = tokens.length; i < j; i++) {
2.227 - var trimmed = ko.utils.stringTrim(tokens[i]);
2.228 - if (trimmed !== "")
2.229 - result.push(trimmed);
2.230 - }
2.231 - return result;
2.232 - },
2.233 -
2.234 - stringStartsWith: function (string, startsWith) {
2.235 - string = string || "";
2.236 - if (startsWith.length > string.length)
2.237 - return false;
2.238 - return string.substring(0, startsWith.length) === startsWith;
2.239 - },
2.240 -
2.241 - domNodeIsContainedBy: function (node, containedByNode) {
2.242 - if (containedByNode.compareDocumentPosition)
2.243 - return (containedByNode.compareDocumentPosition(node) & 16) == 16;
2.244 - while (node != null) {
2.245 - if (node == containedByNode)
2.246 - return true;
2.247 - node = node.parentNode;
2.248 - }
2.249 - return false;
2.250 - },
2.251 -
2.252 - domNodeIsAttachedToDocument: function (node) {
2.253 - return ko.utils.domNodeIsContainedBy(node, node.ownerDocument);
2.254 - },
2.255 -
2.256 - tagNameLower: function(element) {
2.257 - // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
2.258 - // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
2.259 - // we don't need to do the .toLowerCase() as it will always be lower case anyway.
2.260 - return element && element.tagName && element.tagName.toLowerCase();
2.261 - },
2.262 -
2.263 - registerEventHandler: function (element, eventType, handler) {
2.264 - var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
2.265 - if (!mustUseAttachEvent && typeof jQuery != "undefined") {
2.266 - if (isClickOnCheckableElement(element, eventType)) {
2.267 - // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
2.268 - // it toggles the element checked state *after* the click event handlers run, whereas native
2.269 - // click events toggle the checked state *before* the event handler.
2.270 - // Fix this by intecepting the handler and applying the correct checkedness before it runs.
2.271 - var originalHandler = handler;
2.272 - handler = function(event, eventData) {
2.273 - var jQuerySuppliedCheckedState = this.checked;
2.274 - if (eventData)
2.275 - this.checked = eventData.checkedStateBeforeEvent !== true;
2.276 - originalHandler.call(this, event);
2.277 - this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
2.278 - };
2.279 - }
2.280 - jQuery(element)['bind'](eventType, handler);
2.281 - } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
2.282 - element.addEventListener(eventType, handler, false);
2.283 - else if (typeof element.attachEvent != "undefined")
2.284 - element.attachEvent("on" + eventType, function (event) {
2.285 - handler.call(element, event);
2.286 - });
2.287 - else
2.288 - throw new Error("Browser doesn't support addEventListener or attachEvent");
2.289 - },
2.290 -
2.291 - triggerEvent: function (element, eventType) {
2.292 - if (!(element && element.nodeType))
2.293 - throw new Error("element must be a DOM node when calling triggerEvent");
2.294 -
2.295 - if (typeof jQuery != "undefined") {
2.296 - var eventData = [];
2.297 - if (isClickOnCheckableElement(element, eventType)) {
2.298 - // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
2.299 - eventData.push({ checkedStateBeforeEvent: element.checked });
2.300 - }
2.301 - jQuery(element)['trigger'](eventType, eventData);
2.302 - } else if (typeof document.createEvent == "function") {
2.303 - if (typeof element.dispatchEvent == "function") {
2.304 - var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
2.305 - var event = document.createEvent(eventCategory);
2.306 - event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
2.307 - element.dispatchEvent(event);
2.308 - }
2.309 - else
2.310 - throw new Error("The supplied element doesn't support dispatchEvent");
2.311 - } else if (typeof element.fireEvent != "undefined") {
2.312 - // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
2.313 - // so to make it consistent, we'll do it manually here
2.314 - if (isClickOnCheckableElement(element, eventType))
2.315 - element.checked = element.checked !== true;
2.316 - element.fireEvent("on" + eventType);
2.317 - }
2.318 - else
2.319 - throw new Error("Browser doesn't support triggering events");
2.320 - },
2.321 -
2.322 - unwrapObservable: function (value) {
2.323 - return ko.isObservable(value) ? value() : value;
2.324 - },
2.325 -
2.326 - peekObservable: function (value) {
2.327 - return ko.isObservable(value) ? value.peek() : value;
2.328 - },
2.329 -
2.330 - toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
2.331 - if (classNames) {
2.332 - var cssClassNameRegex = /[\w-]+/g,
2.333 - currentClassNames = node.className.match(cssClassNameRegex) || [];
2.334 - ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
2.335 - var indexOfClass = ko.utils.arrayIndexOf(currentClassNames, className);
2.336 - if (indexOfClass >= 0) {
2.337 - if (!shouldHaveClass)
2.338 - currentClassNames.splice(indexOfClass, 1);
2.339 - } else {
2.340 - if (shouldHaveClass)
2.341 - currentClassNames.push(className);
2.342 - }
2.343 - });
2.344 - node.className = currentClassNames.join(" ");
2.345 - }
2.346 - },
2.347 -
2.348 - setTextContent: function(element, textContent) {
2.349 - var value = ko.utils.unwrapObservable(textContent);
2.350 - if ((value === null) || (value === undefined))
2.351 - value = "";
2.352 -
2.353 - if (element.nodeType === 3) {
2.354 - element.data = value;
2.355 - } else {
2.356 - // We need there to be exactly one child: a text node.
2.357 - // If there are no children, more than one, or if it's not a text node,
2.358 - // we'll clear everything and create a single text node.
2.359 - var innerTextNode = ko.virtualElements.firstChild(element);
2.360 - if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
2.361 - ko.virtualElements.setDomNodeChildren(element, [document.createTextNode(value)]);
2.362 - } else {
2.363 - innerTextNode.data = value;
2.364 - }
2.365 -
2.366 - ko.utils.forceRefresh(element);
2.367 - }
2.368 - },
2.369 -
2.370 - setElementName: function(element, name) {
2.371 - element.name = name;
2.372 -
2.373 - // Workaround IE 6/7 issue
2.374 - // - https://github.com/SteveSanderson/knockout/issues/197
2.375 - // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
2.376 - if (ieVersion <= 7) {
2.377 - try {
2.378 - element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
2.379 - }
2.380 - catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
2.381 - }
2.382 - },
2.383 -
2.384 - forceRefresh: function(node) {
2.385 - // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
2.386 - if (ieVersion >= 9) {
2.387 - // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
2.388 - var elem = node.nodeType == 1 ? node : node.parentNode;
2.389 - if (elem.style)
2.390 - elem.style.zoom = elem.style.zoom;
2.391 - }
2.392 - },
2.393 -
2.394 - ensureSelectElementIsRenderedCorrectly: function(selectElement) {
2.395 - // Workaround for IE9 rendering bug - it doesn't reliably display all the text in dynamically-added select boxes unless you force it to re-render by updating the width.
2.396 - // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
2.397 - if (ieVersion >= 9) {
2.398 - var originalWidth = selectElement.style.width;
2.399 - selectElement.style.width = 0;
2.400 - selectElement.style.width = originalWidth;
2.401 - }
2.402 - },
2.403 -
2.404 - range: function (min, max) {
2.405 - min = ko.utils.unwrapObservable(min);
2.406 - max = ko.utils.unwrapObservable(max);
2.407 - var result = [];
2.408 - for (var i = min; i <= max; i++)
2.409 - result.push(i);
2.410 - return result;
2.411 - },
2.412 -
2.413 - makeArray: function(arrayLikeObject) {
2.414 - var result = [];
2.415 - for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
2.416 - result.push(arrayLikeObject[i]);
2.417 - };
2.418 - return result;
2.419 - },
2.420 -
2.421 - isIe6 : isIe6,
2.422 - isIe7 : isIe7,
2.423 - ieVersion : ieVersion,
2.424 -
2.425 - getFormFields: function(form, fieldName) {
2.426 - var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
2.427 - var isMatchingField = (typeof fieldName == 'string')
2.428 - ? function(field) { return field.name === fieldName }
2.429 - : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
2.430 - var matches = [];
2.431 - for (var i = fields.length - 1; i >= 0; i--) {
2.432 - if (isMatchingField(fields[i]))
2.433 - matches.push(fields[i]);
2.434 - };
2.435 - return matches;
2.436 - },
2.437 -
2.438 - parseJson: function (jsonString) {
2.439 - if (typeof jsonString == "string") {
2.440 - jsonString = ko.utils.stringTrim(jsonString);
2.441 - if (jsonString) {
2.442 - if (window.JSON && window.JSON.parse) // Use native parsing where available
2.443 - return window.JSON.parse(jsonString);
2.444 - return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
2.445 - }
2.446 - }
2.447 - return null;
2.448 - },
2.449 -
2.450 - stringifyJson: function (data, replacer, space) { // replacer and space are optional
2.451 - if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
2.452 - throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");
2.453 - return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
2.454 - },
2.455 -
2.456 - postJson: function (urlOrForm, data, options) {
2.457 - options = options || {};
2.458 - var params = options['params'] || {};
2.459 - var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
2.460 - var url = urlOrForm;
2.461 -
2.462 - // If we were given a form, use its 'action' URL and pick out any requested field values
2.463 - if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
2.464 - var originalForm = urlOrForm;
2.465 - url = originalForm.action;
2.466 - for (var i = includeFields.length - 1; i >= 0; i--) {
2.467 - var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
2.468 - for (var j = fields.length - 1; j >= 0; j--)
2.469 - params[fields[j].name] = fields[j].value;
2.470 - }
2.471 - }
2.472 -
2.473 - data = ko.utils.unwrapObservable(data);
2.474 - var form = document.createElement("form");
2.475 - form.style.display = "none";
2.476 - form.action = url;
2.477 - form.method = "post";
2.478 - for (var key in data) {
2.479 - var input = document.createElement("input");
2.480 - input.name = key;
2.481 - input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
2.482 - form.appendChild(input);
2.483 - }
2.484 - for (var key in params) {
2.485 - var input = document.createElement("input");
2.486 - input.name = key;
2.487 - input.value = params[key];
2.488 - form.appendChild(input);
2.489 - }
2.490 - document.body.appendChild(form);
2.491 - options['submitter'] ? options['submitter'](form) : form.submit();
2.492 - setTimeout(function () { form.parentNode.removeChild(form); }, 0);
2.493 - }
2.494 - }
2.495 -})();
2.496 -
2.497 -ko.exportSymbol('utils', ko.utils);
2.498 -ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
2.499 -ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
2.500 -ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
2.501 -ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
2.502 -ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
2.503 -ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
2.504 -ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
2.505 -ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
2.506 -ko.exportSymbol('utils.extend', ko.utils.extend);
2.507 -ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
2.508 -ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
2.509 -ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
2.510 -ko.exportSymbol('utils.postJson', ko.utils.postJson);
2.511 -ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
2.512 -ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
2.513 -ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
2.514 -ko.exportSymbol('utils.range', ko.utils.range);
2.515 -ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
2.516 -ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
2.517 -ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
2.518 -
2.519 -if (!Function.prototype['bind']) {
2.520 - // Function.prototype.bind is a standard part of ECMAScript 5th Edition (December 2009, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf)
2.521 - // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
2.522 - Function.prototype['bind'] = function (object) {
2.523 - var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
2.524 - return function () {
2.525 - return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
2.526 - };
2.527 - };
2.528 -}
2.529 -
2.530 -ko.utils.domData = new (function () {
2.531 - var uniqueId = 0;
2.532 - var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
2.533 - var dataStore = {};
2.534 - return {
2.535 - get: function (node, key) {
2.536 - var allDataForNode = ko.utils.domData.getAll(node, false);
2.537 - return allDataForNode === undefined ? undefined : allDataForNode[key];
2.538 - },
2.539 - set: function (node, key, value) {
2.540 - if (value === undefined) {
2.541 - // Make sure we don't actually create a new domData key if we are actually deleting a value
2.542 - if (ko.utils.domData.getAll(node, false) === undefined)
2.543 - return;
2.544 - }
2.545 - var allDataForNode = ko.utils.domData.getAll(node, true);
2.546 - allDataForNode[key] = value;
2.547 - },
2.548 - getAll: function (node, createIfNotFound) {
2.549 - var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
2.550 - var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
2.551 - if (!hasExistingDataStore) {
2.552 - if (!createIfNotFound)
2.553 - return undefined;
2.554 - dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
2.555 - dataStore[dataStoreKey] = {};
2.556 - }
2.557 - return dataStore[dataStoreKey];
2.558 - },
2.559 - clear: function (node) {
2.560 - var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
2.561 - if (dataStoreKey) {
2.562 - delete dataStore[dataStoreKey];
2.563 - node[dataStoreKeyExpandoPropertyName] = null;
2.564 - return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
2.565 - }
2.566 - return false;
2.567 - }
2.568 - }
2.569 -})();
2.570 -
2.571 -ko.exportSymbol('utils.domData', ko.utils.domData);
2.572 -ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
2.573 -
2.574 -ko.utils.domNodeDisposal = new (function () {
2.575 - var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();
2.576 - var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
2.577 - var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
2.578 -
2.579 - function getDisposeCallbacksCollection(node, createIfNotFound) {
2.580 - var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
2.581 - if ((allDisposeCallbacks === undefined) && createIfNotFound) {
2.582 - allDisposeCallbacks = [];
2.583 - ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
2.584 - }
2.585 - return allDisposeCallbacks;
2.586 - }
2.587 - function destroyCallbacksCollection(node) {
2.588 - ko.utils.domData.set(node, domDataKey, undefined);
2.589 - }
2.590 -
2.591 - function cleanSingleNode(node) {
2.592 - // Run all the dispose callbacks
2.593 - var callbacks = getDisposeCallbacksCollection(node, false);
2.594 - if (callbacks) {
2.595 - callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
2.596 - for (var i = 0; i < callbacks.length; i++)
2.597 - callbacks[i](node);
2.598 - }
2.599 -
2.600 - // Also erase the DOM data
2.601 - ko.utils.domData.clear(node);
2.602 -
2.603 - // Special support for jQuery here because it's so commonly used.
2.604 - // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
2.605 - // so notify it to tear down any resources associated with the node & descendants here.
2.606 - if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
2.607 - jQuery['cleanData']([node]);
2.608 -
2.609 - // Also clear any immediate-child comment nodes, as these wouldn't have been found by
2.610 - // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
2.611 - if (cleanableNodeTypesWithDescendants[node.nodeType])
2.612 - cleanImmediateCommentTypeChildren(node);
2.613 - }
2.614 -
2.615 - function cleanImmediateCommentTypeChildren(nodeWithChildren) {
2.616 - var child, nextChild = nodeWithChildren.firstChild;
2.617 - while (child = nextChild) {
2.618 - nextChild = child.nextSibling;
2.619 - if (child.nodeType === 8)
2.620 - cleanSingleNode(child);
2.621 - }
2.622 - }
2.623 -
2.624 - return {
2.625 - addDisposeCallback : function(node, callback) {
2.626 - if (typeof callback != "function")
2.627 - throw new Error("Callback must be a function");
2.628 - getDisposeCallbacksCollection(node, true).push(callback);
2.629 - },
2.630 -
2.631 - removeDisposeCallback : function(node, callback) {
2.632 - var callbacksCollection = getDisposeCallbacksCollection(node, false);
2.633 - if (callbacksCollection) {
2.634 - ko.utils.arrayRemoveItem(callbacksCollection, callback);
2.635 - if (callbacksCollection.length == 0)
2.636 - destroyCallbacksCollection(node);
2.637 - }
2.638 - },
2.639 -
2.640 - cleanNode : function(node) {
2.641 - // First clean this node, where applicable
2.642 - if (cleanableNodeTypes[node.nodeType]) {
2.643 - cleanSingleNode(node);
2.644 -
2.645 - // ... then its descendants, where applicable
2.646 - if (cleanableNodeTypesWithDescendants[node.nodeType]) {
2.647 - // Clone the descendants list in case it changes during iteration
2.648 - var descendants = [];
2.649 - ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
2.650 - for (var i = 0, j = descendants.length; i < j; i++)
2.651 - cleanSingleNode(descendants[i]);
2.652 - }
2.653 - }
2.654 - return node;
2.655 - },
2.656 -
2.657 - removeNode : function(node) {
2.658 - ko.cleanNode(node);
2.659 - if (node.parentNode)
2.660 - node.parentNode.removeChild(node);
2.661 - }
2.662 - }
2.663 -})();
2.664 -ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
2.665 -ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
2.666 -ko.exportSymbol('cleanNode', ko.cleanNode);
2.667 -ko.exportSymbol('removeNode', ko.removeNode);
2.668 -ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
2.669 -ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
2.670 -ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
2.671 -(function () {
2.672 - var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
2.673 -
2.674 - function simpleHtmlParse(html) {
2.675 - // Based on jQuery's "clean" function, but only accounting for table-related elements.
2.676 - // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
2.677 -
2.678 - // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
2.679 - // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
2.680 - // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
2.681 - // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
2.682 -
2.683 - // Trim whitespace, otherwise indexOf won't work as expected
2.684 - var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
2.685 -
2.686 - // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
2.687 - var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
2.688 - !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
2.689 - (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
2.690 - /* anything else */ [0, "", ""];
2.691 -
2.692 - // Go to html and back, then peel off extra wrappers
2.693 - // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
2.694 - var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
2.695 - if (typeof window['innerShiv'] == "function") {
2.696 - div.appendChild(window['innerShiv'](markup));
2.697 - } else {
2.698 - div.innerHTML = markup;
2.699 - }
2.700 -
2.701 - // Move to the right depth
2.702 - while (wrap[0]--)
2.703 - div = div.lastChild;
2.704 -
2.705 - return ko.utils.makeArray(div.lastChild.childNodes);
2.706 - }
2.707 -
2.708 - function jQueryHtmlParse(html) {
2.709 - // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
2.710 - if (jQuery['parseHTML']) {
2.711 - return jQuery['parseHTML'](html);
2.712 - } else {
2.713 - // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
2.714 - var elems = jQuery['clean']([html]);
2.715 -
2.716 - // As of jQuery 1.7.1, jQuery parses the HTML by appending it to some dummy parent nodes held in an in-memory document fragment.
2.717 - // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
2.718 - // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
2.719 - if (elems && elems[0]) {
2.720 - // Find the top-most parent element that's a direct child of a document fragment
2.721 - var elem = elems[0];
2.722 - while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
2.723 - elem = elem.parentNode;
2.724 - // ... then detach it
2.725 - if (elem.parentNode)
2.726 - elem.parentNode.removeChild(elem);
2.727 - }
2.728 -
2.729 - return elems;
2.730 - }
2.731 - }
2.732 -
2.733 - ko.utils.parseHtmlFragment = function(html) {
2.734 - return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
2.735 - : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
2.736 - };
2.737 -
2.738 - ko.utils.setHtml = function(node, html) {
2.739 - ko.utils.emptyDomNode(node);
2.740 -
2.741 - // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
2.742 - html = ko.utils.unwrapObservable(html);
2.743 -
2.744 - if ((html !== null) && (html !== undefined)) {
2.745 - if (typeof html != 'string')
2.746 - html = html.toString();
2.747 -
2.748 - // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
2.749 - // for example <tr> elements which are not normally allowed to exist on their own.
2.750 - // If you've referenced jQuery we'll use that rather than duplicating its code.
2.751 - if (typeof jQuery != 'undefined') {
2.752 - jQuery(node)['html'](html);
2.753 - } else {
2.754 - // ... otherwise, use KO's own parsing logic.
2.755 - var parsedNodes = ko.utils.parseHtmlFragment(html);
2.756 - for (var i = 0; i < parsedNodes.length; i++)
2.757 - node.appendChild(parsedNodes[i]);
2.758 - }
2.759 - }
2.760 - };
2.761 -})();
2.762 -
2.763 -ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
2.764 -ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
2.765 -
2.766 -ko.memoization = (function () {
2.767 - var memos = {};
2.768 -
2.769 - function randomMax8HexChars() {
2.770 - return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
2.771 - }
2.772 - function generateRandomId() {
2.773 - return randomMax8HexChars() + randomMax8HexChars();
2.774 - }
2.775 - function findMemoNodes(rootNode, appendToArray) {
2.776 - if (!rootNode)
2.777 - return;
2.778 - if (rootNode.nodeType == 8) {
2.779 - var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
2.780 - if (memoId != null)
2.781 - appendToArray.push({ domNode: rootNode, memoId: memoId });
2.782 - } else if (rootNode.nodeType == 1) {
2.783 - for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
2.784 - findMemoNodes(childNodes[i], appendToArray);
2.785 - }
2.786 - }
2.787 -
2.788 - return {
2.789 - memoize: function (callback) {
2.790 - if (typeof callback != "function")
2.791 - throw new Error("You can only pass a function to ko.memoization.memoize()");
2.792 - var memoId = generateRandomId();
2.793 - memos[memoId] = callback;
2.794 - return "<!--[ko_memo:" + memoId + "]-->";
2.795 - },
2.796 -
2.797 - unmemoize: function (memoId, callbackParams) {
2.798 - var callback = memos[memoId];
2.799 - if (callback === undefined)
2.800 - throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
2.801 - try {
2.802 - callback.apply(null, callbackParams || []);
2.803 - return true;
2.804 - }
2.805 - finally { delete memos[memoId]; }
2.806 - },
2.807 -
2.808 - unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
2.809 - var memos = [];
2.810 - findMemoNodes(domNode, memos);
2.811 - for (var i = 0, j = memos.length; i < j; i++) {
2.812 - var node = memos[i].domNode;
2.813 - var combinedParams = [node];
2.814 - if (extraCallbackParamsArray)
2.815 - ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
2.816 - ko.memoization.unmemoize(memos[i].memoId, combinedParams);
2.817 - node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
2.818 - if (node.parentNode)
2.819 - node.parentNode.removeChild(node); // If possible, erase it totally (not always possible - someone else might just hold a reference to it then call unmemoizeDomNodeAndDescendants again)
2.820 - }
2.821 - },
2.822 -
2.823 - parseMemoText: function (memoText) {
2.824 - var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
2.825 - return match ? match[1] : null;
2.826 - }
2.827 - };
2.828 -})();
2.829 -
2.830 -ko.exportSymbol('memoization', ko.memoization);
2.831 -ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
2.832 -ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
2.833 -ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
2.834 -ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
2.835 -ko.extenders = {
2.836 - 'throttle': function(target, timeout) {
2.837 - // Throttling means two things:
2.838 -
2.839 - // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
2.840 - // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
2.841 - target['throttleEvaluation'] = timeout;
2.842 -
2.843 - // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
2.844 - // so the target cannot change value synchronously or faster than a certain rate
2.845 - var writeTimeoutInstance = null;
2.846 - return ko.dependentObservable({
2.847 - 'read': target,
2.848 - 'write': function(value) {
2.849 - clearTimeout(writeTimeoutInstance);
2.850 - writeTimeoutInstance = setTimeout(function() {
2.851 - target(value);
2.852 - }, timeout);
2.853 - }
2.854 - });
2.855 - },
2.856 -
2.857 - 'notify': function(target, notifyWhen) {
2.858 - target["equalityComparer"] = notifyWhen == "always"
2.859 - ? function() { return false } // Treat all values as not equal
2.860 - : ko.observable["fn"]["equalityComparer"];
2.861 - return target;
2.862 - }
2.863 -};
2.864 -
2.865 -function applyExtenders(requestedExtenders) {
2.866 - var target = this;
2.867 - if (requestedExtenders) {
2.868 - for (var key in requestedExtenders) {
2.869 - var extenderHandler = ko.extenders[key];
2.870 - if (typeof extenderHandler == 'function') {
2.871 - target = extenderHandler(target, requestedExtenders[key]);
2.872 - }
2.873 - }
2.874 - }
2.875 - return target;
2.876 -}
2.877 -
2.878 -ko.exportSymbol('extenders', ko.extenders);
2.879 -
2.880 -ko.subscription = function (target, callback, disposeCallback) {
2.881 - this.target = target;
2.882 - this.callback = callback;
2.883 - this.disposeCallback = disposeCallback;
2.884 - ko.exportProperty(this, 'dispose', this.dispose);
2.885 -};
2.886 -ko.subscription.prototype.dispose = function () {
2.887 - this.isDisposed = true;
2.888 - this.disposeCallback();
2.889 -};
2.890 -
2.891 -ko.subscribable = function () {
2.892 - this._subscriptions = {};
2.893 -
2.894 - ko.utils.extend(this, ko.subscribable['fn']);
2.895 - ko.exportProperty(this, 'subscribe', this.subscribe);
2.896 - ko.exportProperty(this, 'extend', this.extend);
2.897 - ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
2.898 -}
2.899 -
2.900 -var defaultEvent = "change";
2.901 -
2.902 -ko.subscribable['fn'] = {
2.903 - subscribe: function (callback, callbackTarget, event) {
2.904 - event = event || defaultEvent;
2.905 - var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
2.906 -
2.907 - var subscription = new ko.subscription(this, boundCallback, function () {
2.908 - ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
2.909 - }.bind(this));
2.910 -
2.911 - if (!this._subscriptions[event])
2.912 - this._subscriptions[event] = [];
2.913 - this._subscriptions[event].push(subscription);
2.914 - return subscription;
2.915 - },
2.916 -
2.917 - "notifySubscribers": function (valueToNotify, event) {
2.918 - event = event || defaultEvent;
2.919 - if (this._subscriptions[event]) {
2.920 - ko.dependencyDetection.ignore(function() {
2.921 - ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
2.922 - // In case a subscription was disposed during the arrayForEach cycle, check
2.923 - // for isDisposed on each subscription before invoking its callback
2.924 - if (subscription && (subscription.isDisposed !== true))
2.925 - subscription.callback(valueToNotify);
2.926 - });
2.927 - }, this);
2.928 - }
2.929 - },
2.930 -
2.931 - getSubscriptionsCount: function () {
2.932 - var total = 0;
2.933 - for (var eventName in this._subscriptions) {
2.934 - if (this._subscriptions.hasOwnProperty(eventName))
2.935 - total += this._subscriptions[eventName].length;
2.936 - }
2.937 - return total;
2.938 - },
2.939 -
2.940 - extend: applyExtenders
2.941 -};
2.942 -
2.943 -
2.944 -ko.isSubscribable = function (instance) {
2.945 - return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
2.946 -};
2.947 -
2.948 -ko.exportSymbol('subscribable', ko.subscribable);
2.949 -ko.exportSymbol('isSubscribable', ko.isSubscribable);
2.950 -
2.951 -ko.dependencyDetection = (function () {
2.952 - var _frames = [];
2.953 -
2.954 - return {
2.955 - begin: function (callback) {
2.956 - _frames.push({ callback: callback, distinctDependencies:[] });
2.957 - },
2.958 -
2.959 - end: function () {
2.960 - _frames.pop();
2.961 - },
2.962 -
2.963 - registerDependency: function (subscribable) {
2.964 - if (!ko.isSubscribable(subscribable))
2.965 - throw new Error("Only subscribable things can act as dependencies");
2.966 - if (_frames.length > 0) {
2.967 - var topFrame = _frames[_frames.length - 1];
2.968 - if (!topFrame || ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
2.969 - return;
2.970 - topFrame.distinctDependencies.push(subscribable);
2.971 - topFrame.callback(subscribable);
2.972 - }
2.973 - },
2.974 -
2.975 - ignore: function(callback, callbackTarget, callbackArgs) {
2.976 - try {
2.977 - _frames.push(null);
2.978 - return callback.apply(callbackTarget, callbackArgs || []);
2.979 - } finally {
2.980 - _frames.pop();
2.981 - }
2.982 - }
2.983 - };
2.984 -})();
2.985 -var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };
2.986 -
2.987 -ko.observable = function (initialValue) {
2.988 - var _latestValue = initialValue;
2.989 -
2.990 - function observable() {
2.991 - if (arguments.length > 0) {
2.992 - // Write
2.993 -
2.994 - // Ignore writes if the value hasn't changed
2.995 - if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
2.996 - observable.valueWillMutate();
2.997 - _latestValue = arguments[0];
2.998 - if (DEBUG) observable._latestValue = _latestValue;
2.999 - observable.valueHasMutated();
2.1000 - }
2.1001 - return this; // Permits chained assignments
2.1002 - }
2.1003 - else {
2.1004 - // Read
2.1005 - ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
2.1006 - return _latestValue;
2.1007 - }
2.1008 - }
2.1009 - if (DEBUG) observable._latestValue = _latestValue;
2.1010 - ko.subscribable.call(observable);
2.1011 - observable.peek = function() { return _latestValue };
2.1012 - observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
2.1013 - observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
2.1014 - ko.utils.extend(observable, ko.observable['fn']);
2.1015 -
2.1016 - ko.exportProperty(observable, 'peek', observable.peek);
2.1017 - ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
2.1018 - ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
2.1019 -
2.1020 - return observable;
2.1021 -}
2.1022 -
2.1023 -ko.observable['fn'] = {
2.1024 - "equalityComparer": function valuesArePrimitiveAndEqual(a, b) {
2.1025 - var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
2.1026 - return oldValueIsPrimitive ? (a === b) : false;
2.1027 - }
2.1028 -};
2.1029 -
2.1030 -var protoProperty = ko.observable.protoProperty = "__ko_proto__";
2.1031 -ko.observable['fn'][protoProperty] = ko.observable;
2.1032 -
2.1033 -ko.hasPrototype = function(instance, prototype) {
2.1034 - if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
2.1035 - if (instance[protoProperty] === prototype) return true;
2.1036 - return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
2.1037 -};
2.1038 -
2.1039 -ko.isObservable = function (instance) {
2.1040 - return ko.hasPrototype(instance, ko.observable);
2.1041 -}
2.1042 -ko.isWriteableObservable = function (instance) {
2.1043 - // Observable
2.1044 - if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
2.1045 - return true;
2.1046 - // Writeable dependent observable
2.1047 - if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
2.1048 - return true;
2.1049 - // Anything else
2.1050 - return false;
2.1051 -}
2.1052 -
2.1053 -
2.1054 -ko.exportSymbol('observable', ko.observable);
2.1055 -ko.exportSymbol('isObservable', ko.isObservable);
2.1056 -ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
2.1057 -ko.observableArray = function (initialValues) {
2.1058 - if (arguments.length == 0) {
2.1059 - // Zero-parameter constructor initializes to empty array
2.1060 - initialValues = [];
2.1061 - }
2.1062 - if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
2.1063 - throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
2.1064 -
2.1065 - var result = ko.observable(initialValues);
2.1066 - ko.utils.extend(result, ko.observableArray['fn']);
2.1067 - return result;
2.1068 -}
2.1069 -
2.1070 -ko.observableArray['fn'] = {
2.1071 - 'remove': function (valueOrPredicate) {
2.1072 - var underlyingArray = this.peek();
2.1073 - var removedValues = [];
2.1074 - var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
2.1075 - for (var i = 0; i < underlyingArray.length; i++) {
2.1076 - var value = underlyingArray[i];
2.1077 - if (predicate(value)) {
2.1078 - if (removedValues.length === 0) {
2.1079 - this.valueWillMutate();
2.1080 - }
2.1081 - removedValues.push(value);
2.1082 - underlyingArray.splice(i, 1);
2.1083 - i--;
2.1084 - }
2.1085 - }
2.1086 - if (removedValues.length) {
2.1087 - this.valueHasMutated();
2.1088 - }
2.1089 - return removedValues;
2.1090 - },
2.1091 -
2.1092 - 'removeAll': function (arrayOfValues) {
2.1093 - // If you passed zero args, we remove everything
2.1094 - if (arrayOfValues === undefined) {
2.1095 - var underlyingArray = this.peek();
2.1096 - var allValues = underlyingArray.slice(0);
2.1097 - this.valueWillMutate();
2.1098 - underlyingArray.splice(0, underlyingArray.length);
2.1099 - this.valueHasMutated();
2.1100 - return allValues;
2.1101 - }
2.1102 - // If you passed an arg, we interpret it as an array of entries to remove
2.1103 - if (!arrayOfValues)
2.1104 - return [];
2.1105 - return this['remove'](function (value) {
2.1106 - return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
2.1107 - });
2.1108 - },
2.1109 -
2.1110 - 'destroy': function (valueOrPredicate) {
2.1111 - var underlyingArray = this.peek();
2.1112 - var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
2.1113 - this.valueWillMutate();
2.1114 - for (var i = underlyingArray.length - 1; i >= 0; i--) {
2.1115 - var value = underlyingArray[i];
2.1116 - if (predicate(value))
2.1117 - underlyingArray[i]["_destroy"] = true;
2.1118 - }
2.1119 - this.valueHasMutated();
2.1120 - },
2.1121 -
2.1122 - 'destroyAll': function (arrayOfValues) {
2.1123 - // If you passed zero args, we destroy everything
2.1124 - if (arrayOfValues === undefined)
2.1125 - return this['destroy'](function() { return true });
2.1126 -
2.1127 - // If you passed an arg, we interpret it as an array of entries to destroy
2.1128 - if (!arrayOfValues)
2.1129 - return [];
2.1130 - return this['destroy'](function (value) {
2.1131 - return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
2.1132 - });
2.1133 - },
2.1134 -
2.1135 - 'indexOf': function (item) {
2.1136 - var underlyingArray = this();
2.1137 - return ko.utils.arrayIndexOf(underlyingArray, item);
2.1138 - },
2.1139 -
2.1140 - 'replace': function(oldItem, newItem) {
2.1141 - var index = this['indexOf'](oldItem);
2.1142 - if (index >= 0) {
2.1143 - this.valueWillMutate();
2.1144 - this.peek()[index] = newItem;
2.1145 - this.valueHasMutated();
2.1146 - }
2.1147 - }
2.1148 -}
2.1149 -
2.1150 -// Populate ko.observableArray.fn with read/write functions from native arrays
2.1151 -// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
2.1152 -// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
2.1153 -ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
2.1154 - ko.observableArray['fn'][methodName] = function () {
2.1155 - // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
2.1156 - // (for consistency with mutating regular observables)
2.1157 - var underlyingArray = this.peek();
2.1158 - this.valueWillMutate();
2.1159 - var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
2.1160 - this.valueHasMutated();
2.1161 - return methodCallResult;
2.1162 - };
2.1163 -});
2.1164 -
2.1165 -// Populate ko.observableArray.fn with read-only functions from native arrays
2.1166 -ko.utils.arrayForEach(["slice"], function (methodName) {
2.1167 - ko.observableArray['fn'][methodName] = function () {
2.1168 - var underlyingArray = this();
2.1169 - return underlyingArray[methodName].apply(underlyingArray, arguments);
2.1170 - };
2.1171 -});
2.1172 -
2.1173 -ko.exportSymbol('observableArray', ko.observableArray);
2.1174 -ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
2.1175 - var _latestValue,
2.1176 - _hasBeenEvaluated = false,
2.1177 - _isBeingEvaluated = false,
2.1178 - readFunction = evaluatorFunctionOrOptions;
2.1179 -
2.1180 - if (readFunction && typeof readFunction == "object") {
2.1181 - // Single-parameter syntax - everything is on this "options" param
2.1182 - options = readFunction;
2.1183 - readFunction = options["read"];
2.1184 - } else {
2.1185 - // Multi-parameter syntax - construct the options according to the params passed
2.1186 - options = options || {};
2.1187 - if (!readFunction)
2.1188 - readFunction = options["read"];
2.1189 - }
2.1190 - if (typeof readFunction != "function")
2.1191 - throw new Error("Pass a function that returns the value of the ko.computed");
2.1192 -
2.1193 - function addSubscriptionToDependency(subscribable) {
2.1194 - _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync));
2.1195 - }
2.1196 -
2.1197 - function disposeAllSubscriptionsToDependencies() {
2.1198 - ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
2.1199 - subscription.dispose();
2.1200 - });
2.1201 - _subscriptionsToDependencies = [];
2.1202 - }
2.1203 -
2.1204 - function evaluatePossiblyAsync() {
2.1205 - var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
2.1206 - if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
2.1207 - clearTimeout(evaluationTimeoutInstance);
2.1208 - evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
2.1209 - } else
2.1210 - evaluateImmediate();
2.1211 - }
2.1212 -
2.1213 - function evaluateImmediate() {
2.1214 - if (_isBeingEvaluated) {
2.1215 - // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
2.1216 - // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
2.1217 - // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
2.1218 - // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
2.1219 - return;
2.1220 - }
2.1221 -
2.1222 - // Don't dispose on first evaluation, because the "disposeWhen" callback might
2.1223 - // e.g., dispose when the associated DOM element isn't in the doc, and it's not
2.1224 - // going to be in the doc until *after* the first evaluation
2.1225 - if (_hasBeenEvaluated && disposeWhen()) {
2.1226 - dispose();
2.1227 - return;
2.1228 - }
2.1229 -
2.1230 - _isBeingEvaluated = true;
2.1231 - try {
2.1232 - // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
2.1233 - // Then, during evaluation, we cross off any that are in fact still being used.
2.1234 - var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
2.1235 -
2.1236 - ko.dependencyDetection.begin(function(subscribable) {
2.1237 - var inOld;
2.1238 - if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
2.1239 - disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
2.1240 - else
2.1241 - addSubscriptionToDependency(subscribable); // Brand new subscription - add it
2.1242 - });
2.1243 -
2.1244 - var newValue = readFunction.call(evaluatorFunctionTarget);
2.1245 -
2.1246 - // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
2.1247 - for (var i = disposalCandidates.length - 1; i >= 0; i--) {
2.1248 - if (disposalCandidates[i])
2.1249 - _subscriptionsToDependencies.splice(i, 1)[0].dispose();
2.1250 - }
2.1251 - _hasBeenEvaluated = true;
2.1252 -
2.1253 - dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
2.1254 - _latestValue = newValue;
2.1255 - if (DEBUG) dependentObservable._latestValue = _latestValue;
2.1256 - } finally {
2.1257 - ko.dependencyDetection.end();
2.1258 - }
2.1259 -
2.1260 - dependentObservable["notifySubscribers"](_latestValue);
2.1261 - _isBeingEvaluated = false;
2.1262 - if (!_subscriptionsToDependencies.length)
2.1263 - dispose();
2.1264 - }
2.1265 -
2.1266 - function dependentObservable() {
2.1267 - if (arguments.length > 0) {
2.1268 - if (typeof writeFunction === "function") {
2.1269 - // Writing a value
2.1270 - writeFunction.apply(evaluatorFunctionTarget, arguments);
2.1271 - } else {
2.1272 - throw new Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");
2.1273 - }
2.1274 - return this; // Permits chained assignments
2.1275 - } else {
2.1276 - // Reading the value
2.1277 - if (!_hasBeenEvaluated)
2.1278 - evaluateImmediate();
2.1279 - ko.dependencyDetection.registerDependency(dependentObservable);
2.1280 - return _latestValue;
2.1281 - }
2.1282 - }
2.1283 -
2.1284 - function peek() {
2.1285 - if (!_hasBeenEvaluated)
2.1286 - evaluateImmediate();
2.1287 - return _latestValue;
2.1288 - }
2.1289 -
2.1290 - function isActive() {
2.1291 - return !_hasBeenEvaluated || _subscriptionsToDependencies.length > 0;
2.1292 - }
2.1293 -
2.1294 - // By here, "options" is always non-null
2.1295 - var writeFunction = options["write"],
2.1296 - disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
2.1297 - disposeWhen = options["disposeWhen"] || options.disposeWhen || function() { return false; },
2.1298 - dispose = disposeAllSubscriptionsToDependencies,
2.1299 - _subscriptionsToDependencies = [],
2.1300 - evaluationTimeoutInstance = null;
2.1301 -
2.1302 - if (!evaluatorFunctionTarget)
2.1303 - evaluatorFunctionTarget = options["owner"];
2.1304 -
2.1305 - dependentObservable.peek = peek;
2.1306 - dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
2.1307 - dependentObservable.hasWriteFunction = typeof options["write"] === "function";
2.1308 - dependentObservable.dispose = function () { dispose(); };
2.1309 - dependentObservable.isActive = isActive;
2.1310 - dependentObservable.valueHasMutated = function() {
2.1311 - _hasBeenEvaluated = false;
2.1312 - evaluateImmediate();
2.1313 - };
2.1314 -
2.1315 - ko.subscribable.call(dependentObservable);
2.1316 - ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
2.1317 -
2.1318 - ko.exportProperty(dependentObservable, 'valueHasMutated', dependentObservable.valueHasMutated);
2.1319 - ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
2.1320 - ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
2.1321 - ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
2.1322 - ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
2.1323 -
2.1324 - // Evaluate, unless deferEvaluation is true
2.1325 - if (options['deferEvaluation'] !== true)
2.1326 - evaluateImmediate();
2.1327 -
2.1328 - // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values.
2.1329 - // But skip if isActive is false (there will never be any dependencies to dispose).
2.1330 - // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
2.1331 - // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
2.1332 - if (disposeWhenNodeIsRemoved && isActive()) {
2.1333 - dispose = function() {
2.1334 - ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
2.1335 - disposeAllSubscriptionsToDependencies();
2.1336 - };
2.1337 - ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
2.1338 - var existingDisposeWhenFunction = disposeWhen;
2.1339 - disposeWhen = function () {
2.1340 - return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
2.1341 - }
2.1342 - }
2.1343 -
2.1344 - return dependentObservable;
2.1345 -};
2.1346 -
2.1347 -ko.isComputed = function(instance) {
2.1348 - return ko.hasPrototype(instance, ko.dependentObservable);
2.1349 -};
2.1350 -
2.1351 -var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
2.1352 -ko.dependentObservable[protoProp] = ko.observable;
2.1353 -
2.1354 -ko.dependentObservable['fn'] = {};
2.1355 -ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
2.1356 -
2.1357 -ko.exportSymbol('dependentObservable', ko.dependentObservable);
2.1358 -ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
2.1359 -ko.exportSymbol('isComputed', ko.isComputed);
2.1360 -
2.1361 -(function() {
2.1362 - var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
2.1363 -
2.1364 - ko.toJS = function(rootObject) {
2.1365 - if (arguments.length == 0)
2.1366 - throw new Error("When calling ko.toJS, pass the object you want to convert.");
2.1367 -
2.1368 - // We just unwrap everything at every level in the object graph
2.1369 - return mapJsObjectGraph(rootObject, function(valueToMap) {
2.1370 - // Loop because an observable's value might in turn be another observable wrapper
2.1371 - for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
2.1372 - valueToMap = valueToMap();
2.1373 - return valueToMap;
2.1374 - });
2.1375 - };
2.1376 -
2.1377 - ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
2.1378 - var plainJavaScriptObject = ko.toJS(rootObject);
2.1379 - return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
2.1380 - };
2.1381 -
2.1382 - function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
2.1383 - visitedObjects = visitedObjects || new objectLookup();
2.1384 -
2.1385 - rootObject = mapInputCallback(rootObject);
2.1386 - var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
2.1387 - if (!canHaveProperties)
2.1388 - return rootObject;
2.1389 -
2.1390 - var outputProperties = rootObject instanceof Array ? [] : {};
2.1391 - visitedObjects.save(rootObject, outputProperties);
2.1392 -
2.1393 - visitPropertiesOrArrayEntries(rootObject, function(indexer) {
2.1394 - var propertyValue = mapInputCallback(rootObject[indexer]);
2.1395 -
2.1396 - switch (typeof propertyValue) {
2.1397 - case "boolean":
2.1398 - case "number":
2.1399 - case "string":
2.1400 - case "function":
2.1401 - outputProperties[indexer] = propertyValue;
2.1402 - break;
2.1403 - case "object":
2.1404 - case "undefined":
2.1405 - var previouslyMappedValue = visitedObjects.get(propertyValue);
2.1406 - outputProperties[indexer] = (previouslyMappedValue !== undefined)
2.1407 - ? previouslyMappedValue
2.1408 - : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
2.1409 - break;
2.1410 - }
2.1411 - });
2.1412 -
2.1413 - return outputProperties;
2.1414 - }
2.1415 -
2.1416 - function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
2.1417 - if (rootObject instanceof Array) {
2.1418 - for (var i = 0; i < rootObject.length; i++)
2.1419 - visitorCallback(i);
2.1420 -
2.1421 - // For arrays, also respect toJSON property for custom mappings (fixes #278)
2.1422 - if (typeof rootObject['toJSON'] == 'function')
2.1423 - visitorCallback('toJSON');
2.1424 - } else {
2.1425 - for (var propertyName in rootObject)
2.1426 - visitorCallback(propertyName);
2.1427 - }
2.1428 - };
2.1429 -
2.1430 - function objectLookup() {
2.1431 - var keys = [];
2.1432 - var values = [];
2.1433 - this.save = function(key, value) {
2.1434 - var existingIndex = ko.utils.arrayIndexOf(keys, key);
2.1435 - if (existingIndex >= 0)
2.1436 - values[existingIndex] = value;
2.1437 - else {
2.1438 - keys.push(key);
2.1439 - values.push(value);
2.1440 - }
2.1441 - };
2.1442 - this.get = function(key) {
2.1443 - var existingIndex = ko.utils.arrayIndexOf(keys, key);
2.1444 - return (existingIndex >= 0) ? values[existingIndex] : undefined;
2.1445 - };
2.1446 - };
2.1447 -})();
2.1448 -
2.1449 -ko.exportSymbol('toJS', ko.toJS);
2.1450 -ko.exportSymbol('toJSON', ko.toJSON);
2.1451 -(function () {
2.1452 - var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
2.1453 -
2.1454 - // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
2.1455 - // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
2.1456 - // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
2.1457 - ko.selectExtensions = {
2.1458 - readValue : function(element) {
2.1459 - switch (ko.utils.tagNameLower(element)) {
2.1460 - case 'option':
2.1461 - if (element[hasDomDataExpandoProperty] === true)
2.1462 - return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
2.1463 - return ko.utils.ieVersion <= 7
2.1464 - ? (element.getAttributeNode('value').specified ? element.value : element.text)
2.1465 - : element.value;
2.1466 - case 'select':
2.1467 - return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
2.1468 - default:
2.1469 - return element.value;
2.1470 - }
2.1471 - },
2.1472 -
2.1473 - writeValue: function(element, value) {
2.1474 - switch (ko.utils.tagNameLower(element)) {
2.1475 - case 'option':
2.1476 - switch(typeof value) {
2.1477 - case "string":
2.1478 - ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
2.1479 - if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
2.1480 - delete element[hasDomDataExpandoProperty];
2.1481 - }
2.1482 - element.value = value;
2.1483 - break;
2.1484 - default:
2.1485 - // Store arbitrary object using DomData
2.1486 - ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
2.1487 - element[hasDomDataExpandoProperty] = true;
2.1488 -
2.1489 - // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
2.1490 - element.value = typeof value === "number" ? value : "";
2.1491 - break;
2.1492 - }
2.1493 - break;
2.1494 - case 'select':
2.1495 - for (var i = element.options.length - 1; i >= 0; i--) {
2.1496 - if (ko.selectExtensions.readValue(element.options[i]) == value) {
2.1497 - element.selectedIndex = i;
2.1498 - break;
2.1499 - }
2.1500 - }
2.1501 - break;
2.1502 - default:
2.1503 - if ((value === null) || (value === undefined))
2.1504 - value = "";
2.1505 - element.value = value;
2.1506 - break;
2.1507 - }
2.1508 - }
2.1509 - };
2.1510 -})();
2.1511 -
2.1512 -ko.exportSymbol('selectExtensions', ko.selectExtensions);
2.1513 -ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
2.1514 -ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
2.1515 -ko.expressionRewriting = (function () {
2.1516 - var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
2.1517 - var javaScriptReservedWords = ["true", "false"];
2.1518 -
2.1519 - // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
2.1520 - // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
2.1521 - var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
2.1522 -
2.1523 - function restoreTokens(string, tokens) {
2.1524 - var prevValue = null;
2.1525 - while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
2.1526 - prevValue = string;
2.1527 - string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
2.1528 - return tokens[tokenIndex];
2.1529 - });
2.1530 - }
2.1531 - return string;
2.1532 - }
2.1533 -
2.1534 - function getWriteableValue(expression) {
2.1535 - if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
2.1536 - return false;
2.1537 - var match = expression.match(javaScriptAssignmentTarget);
2.1538 - return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
2.1539 - }
2.1540 -
2.1541 - function ensureQuoted(key) {
2.1542 - var trimmedKey = ko.utils.stringTrim(key);
2.1543 - switch (trimmedKey.length && trimmedKey.charAt(0)) {
2.1544 - case "'":
2.1545 - case '"':
2.1546 - return key;
2.1547 - default:
2.1548 - return "'" + trimmedKey + "'";
2.1549 - }
2.1550 - }
2.1551 -
2.1552 - return {
2.1553 - bindingRewriteValidators: [],
2.1554 -
2.1555 - parseObjectLiteral: function(objectLiteralString) {
2.1556 - // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
2.1557 - // that is sufficient just to split an object literal string into a set of top-level key-value pairs
2.1558 -
2.1559 - var str = ko.utils.stringTrim(objectLiteralString);
2.1560 - if (str.length < 3)
2.1561 - return [];
2.1562 - if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
2.1563 - str = str.substring(1, str.length - 1);
2.1564 -
2.1565 - // Pull out any string literals and regex literals
2.1566 - var tokens = [];
2.1567 - var tokenStart = null, tokenEndChar;
2.1568 - for (var position = 0; position < str.length; position++) {
2.1569 - var c = str.charAt(position);
2.1570 - if (tokenStart === null) {
2.1571 - switch (c) {
2.1572 - case '"':
2.1573 - case "'":
2.1574 - case "/":
2.1575 - tokenStart = position;
2.1576 - tokenEndChar = c;
2.1577 - break;
2.1578 - }
2.1579 - } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
2.1580 - var token = str.substring(tokenStart, position + 1);
2.1581 - tokens.push(token);
2.1582 - var replacement = "@ko_token_" + (tokens.length - 1) + "@";
2.1583 - str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
2.1584 - position -= (token.length - replacement.length);
2.1585 - tokenStart = null;
2.1586 - }
2.1587 - }
2.1588 -
2.1589 - // Next pull out balanced paren, brace, and bracket blocks
2.1590 - tokenStart = null;
2.1591 - tokenEndChar = null;
2.1592 - var tokenDepth = 0, tokenStartChar = null;
2.1593 - for (var position = 0; position < str.length; position++) {
2.1594 - var c = str.charAt(position);
2.1595 - if (tokenStart === null) {
2.1596 - switch (c) {
2.1597 - case "{": tokenStart = position; tokenStartChar = c;
2.1598 - tokenEndChar = "}";
2.1599 - break;
2.1600 - case "(": tokenStart = position; tokenStartChar = c;
2.1601 - tokenEndChar = ")";
2.1602 - break;
2.1603 - case "[": tokenStart = position; tokenStartChar = c;
2.1604 - tokenEndChar = "]";
2.1605 - break;
2.1606 - }
2.1607 - }
2.1608 -
2.1609 - if (c === tokenStartChar)
2.1610 - tokenDepth++;
2.1611 - else if (c === tokenEndChar) {
2.1612 - tokenDepth--;
2.1613 - if (tokenDepth === 0) {
2.1614 - var token = str.substring(tokenStart, position + 1);
2.1615 - tokens.push(token);
2.1616 - var replacement = "@ko_token_" + (tokens.length - 1) + "@";
2.1617 - str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
2.1618 - position -= (token.length - replacement.length);
2.1619 - tokenStart = null;
2.1620 - }
2.1621 - }
2.1622 - }
2.1623 -
2.1624 - // Now we can safely split on commas to get the key/value pairs
2.1625 - var result = [];
2.1626 - var keyValuePairs = str.split(",");
2.1627 - for (var i = 0, j = keyValuePairs.length; i < j; i++) {
2.1628 - var pair = keyValuePairs[i];
2.1629 - var colonPos = pair.indexOf(":");
2.1630 - if ((colonPos > 0) && (colonPos < pair.length - 1)) {
2.1631 - var key = pair.substring(0, colonPos);
2.1632 - var value = pair.substring(colonPos + 1);
2.1633 - result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
2.1634 - } else {
2.1635 - result.push({ 'unknown': restoreTokens(pair, tokens) });
2.1636 - }
2.1637 - }
2.1638 - return result;
2.1639 - },
2.1640 -
2.1641 - preProcessBindings: function (objectLiteralStringOrKeyValueArray) {
2.1642 - var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
2.1643 - ? ko.expressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
2.1644 - : objectLiteralStringOrKeyValueArray;
2.1645 - var resultStrings = [], propertyAccessorResultStrings = [];
2.1646 -
2.1647 - var keyValueEntry;
2.1648 - for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
2.1649 - if (resultStrings.length > 0)
2.1650 - resultStrings.push(",");
2.1651 -
2.1652 - if (keyValueEntry['key']) {
2.1653 - var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
2.1654 - resultStrings.push(quotedKey);
2.1655 - resultStrings.push(":");
2.1656 - resultStrings.push(val);
2.1657 -
2.1658 - if (val = getWriteableValue(ko.utils.stringTrim(val))) {
2.1659 - if (propertyAccessorResultStrings.length > 0)
2.1660 - propertyAccessorResultStrings.push(", ");
2.1661 - propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
2.1662 - }
2.1663 - } else if (keyValueEntry['unknown']) {
2.1664 - resultStrings.push(keyValueEntry['unknown']);
2.1665 - }
2.1666 - }
2.1667 -
2.1668 - var combinedResult = resultStrings.join("");
2.1669 - if (propertyAccessorResultStrings.length > 0) {
2.1670 - var allPropertyAccessors = propertyAccessorResultStrings.join("");
2.1671 - combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
2.1672 - }
2.1673 -
2.1674 - return combinedResult;
2.1675 - },
2.1676 -
2.1677 - keyValueArrayContainsKey: function(keyValueArray, key) {
2.1678 - for (var i = 0; i < keyValueArray.length; i++)
2.1679 - if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
2.1680 - return true;
2.1681 - return false;
2.1682 - },
2.1683 -
2.1684 - // Internal, private KO utility for updating model properties from within bindings
2.1685 - // property: If the property being updated is (or might be) an observable, pass it here
2.1686 - // If it turns out to be a writable observable, it will be written to directly
2.1687 - // allBindingsAccessor: All bindings in the current execution context.
2.1688 - // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
2.1689 - // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
2.1690 - // value: The value to be written
2.1691 - // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
2.1692 - // it is !== existing value on that writable observable
2.1693 - writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
2.1694 - if (!property || !ko.isWriteableObservable(property)) {
2.1695 - var propWriters = allBindingsAccessor()['_ko_property_writers'];
2.1696 - if (propWriters && propWriters[key])
2.1697 - propWriters[key](value);
2.1698 - } else if (!checkIfDifferent || property.peek() !== value) {
2.1699 - property(value);
2.1700 - }
2.1701 - }
2.1702 - };
2.1703 -})();
2.1704 -
2.1705 -ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
2.1706 -ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
2.1707 -ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
2.1708 -ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
2.1709 -
2.1710 -// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
2.1711 -// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
2.1712 -ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
2.1713 -ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);(function() {
2.1714 - // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
2.1715 - // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
2.1716 - // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
2.1717 - // of that virtual hierarchy
2.1718 - //
2.1719 - // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
2.1720 - // without having to scatter special cases all over the binding and templating code.
2.1721 -
2.1722 - // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
2.1723 - // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
2.1724 - // So, use node.text where available, and node.nodeValue elsewhere
2.1725 - var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
2.1726 -
2.1727 - var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*-->$/ : /^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/;
2.1728 - var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
2.1729 - var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
2.1730 -
2.1731 - function isStartComment(node) {
2.1732 - return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
2.1733 - }
2.1734 -
2.1735 - function isEndComment(node) {
2.1736 - return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
2.1737 - }
2.1738 -
2.1739 - function getVirtualChildren(startComment, allowUnbalanced) {
2.1740 - var currentNode = startComment;
2.1741 - var depth = 1;
2.1742 - var children = [];
2.1743 - while (currentNode = currentNode.nextSibling) {
2.1744 - if (isEndComment(currentNode)) {
2.1745 - depth--;
2.1746 - if (depth === 0)
2.1747 - return children;
2.1748 - }
2.1749 -
2.1750 - children.push(currentNode);
2.1751 -
2.1752 - if (isStartComment(currentNode))
2.1753 - depth++;
2.1754 - }
2.1755 - if (!allowUnbalanced)
2.1756 - throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
2.1757 - return null;
2.1758 - }
2.1759 -
2.1760 - function getMatchingEndComment(startComment, allowUnbalanced) {
2.1761 - var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
2.1762 - if (allVirtualChildren) {
2.1763 - if (allVirtualChildren.length > 0)
2.1764 - return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
2.1765 - return startComment.nextSibling;
2.1766 - } else
2.1767 - return null; // Must have no matching end comment, and allowUnbalanced is true
2.1768 - }
2.1769 -
2.1770 - function getUnbalancedChildTags(node) {
2.1771 - // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
2.1772 - // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
2.1773 - var childNode = node.firstChild, captureRemaining = null;
2.1774 - if (childNode) {
2.1775 - do {
2.1776 - if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
2.1777 - captureRemaining.push(childNode);
2.1778 - else if (isStartComment(childNode)) {
2.1779 - var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
2.1780 - if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
2.1781 - childNode = matchingEndComment;
2.1782 - else
2.1783 - captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
2.1784 - } else if (isEndComment(childNode)) {
2.1785 - captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
2.1786 - }
2.1787 - } while (childNode = childNode.nextSibling);
2.1788 - }
2.1789 - return captureRemaining;
2.1790 - }
2.1791 -
2.1792 - ko.virtualElements = {
2.1793 - allowedBindings: {},
2.1794 -
2.1795 - childNodes: function(node) {
2.1796 - return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
2.1797 - },
2.1798 -
2.1799 - emptyNode: function(node) {
2.1800 - if (!isStartComment(node))
2.1801 - ko.utils.emptyDomNode(node);
2.1802 - else {
2.1803 - var virtualChildren = ko.virtualElements.childNodes(node);
2.1804 - for (var i = 0, j = virtualChildren.length; i < j; i++)
2.1805 - ko.removeNode(virtualChildren[i]);
2.1806 - }
2.1807 - },
2.1808 -
2.1809 - setDomNodeChildren: function(node, childNodes) {
2.1810 - if (!isStartComment(node))
2.1811 - ko.utils.setDomNodeChildren(node, childNodes);
2.1812 - else {
2.1813 - ko.virtualElements.emptyNode(node);
2.1814 - var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
2.1815 - for (var i = 0, j = childNodes.length; i < j; i++)
2.1816 - endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
2.1817 - }
2.1818 - },
2.1819 -
2.1820 - prepend: function(containerNode, nodeToPrepend) {
2.1821 - if (!isStartComment(containerNode)) {
2.1822 - if (containerNode.firstChild)
2.1823 - containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
2.1824 - else
2.1825 - containerNode.appendChild(nodeToPrepend);
2.1826 - } else {
2.1827 - // Start comments must always have a parent and at least one following sibling (the end comment)
2.1828 - containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
2.1829 - }
2.1830 - },
2.1831 -
2.1832 - insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
2.1833 - if (!insertAfterNode) {
2.1834 - ko.virtualElements.prepend(containerNode, nodeToInsert);
2.1835 - } else if (!isStartComment(containerNode)) {
2.1836 - // Insert after insertion point
2.1837 - if (insertAfterNode.nextSibling)
2.1838 - containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
2.1839 - else
2.1840 - containerNode.appendChild(nodeToInsert);
2.1841 - } else {
2.1842 - // Children of start comments must always have a parent and at least one following sibling (the end comment)
2.1843 - containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
2.1844 - }
2.1845 - },
2.1846 -
2.1847 - firstChild: function(node) {
2.1848 - if (!isStartComment(node))
2.1849 - return node.firstChild;
2.1850 - if (!node.nextSibling || isEndComment(node.nextSibling))
2.1851 - return null;
2.1852 - return node.nextSibling;
2.1853 - },
2.1854 -
2.1855 - nextSibling: function(node) {
2.1856 - if (isStartComment(node))
2.1857 - node = getMatchingEndComment(node);
2.1858 - if (node.nextSibling && isEndComment(node.nextSibling))
2.1859 - return null;
2.1860 - return node.nextSibling;
2.1861 - },
2.1862 -
2.1863 - virtualNodeBindingValue: function(node) {
2.1864 - var regexMatch = isStartComment(node);
2.1865 - return regexMatch ? regexMatch[1] : null;
2.1866 - },
2.1867 -
2.1868 - normaliseVirtualElementDomStructure: function(elementVerified) {
2.1869 - // Workaround for https://github.com/SteveSanderson/knockout/issues/155
2.1870 - // (IE <= 8 or IE 9 quirks mode parses your HTML weirdly, treating closing </li> tags as if they don't exist, thereby moving comment nodes
2.1871 - // that are direct descendants of <ul> into the preceding <li>)
2.1872 - if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
2.1873 - return;
2.1874 -
2.1875 - // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
2.1876 - // must be intended to appear *after* that child, so move them there.
2.1877 - var childNode = elementVerified.firstChild;
2.1878 - if (childNode) {
2.1879 - do {
2.1880 - if (childNode.nodeType === 1) {
2.1881 - var unbalancedTags = getUnbalancedChildTags(childNode);
2.1882 - if (unbalancedTags) {
2.1883 - // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
2.1884 - var nodeToInsertBefore = childNode.nextSibling;
2.1885 - for (var i = 0; i < unbalancedTags.length; i++) {
2.1886 - if (nodeToInsertBefore)
2.1887 - elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
2.1888 - else
2.1889 - elementVerified.appendChild(unbalancedTags[i]);
2.1890 - }
2.1891 - }
2.1892 - }
2.1893 - } while (childNode = childNode.nextSibling);
2.1894 - }
2.1895 - }
2.1896 - };
2.1897 -})();
2.1898 -ko.exportSymbol('virtualElements', ko.virtualElements);
2.1899 -ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
2.1900 -ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
2.1901 -//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
2.1902 -ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
2.1903 -//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
2.1904 -ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
2.1905 -ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
2.1906 -(function() {
2.1907 - var defaultBindingAttributeName = "data-bind";
2.1908 -
2.1909 - ko.bindingProvider = function() {
2.1910 - this.bindingCache = {};
2.1911 - };
2.1912 -
2.1913 - ko.utils.extend(ko.bindingProvider.prototype, {
2.1914 - 'nodeHasBindings': function(node) {
2.1915 - switch (node.nodeType) {
2.1916 - case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
2.1917 - case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
2.1918 - default: return false;
2.1919 - }
2.1920 - },
2.1921 -
2.1922 - 'getBindings': function(node, bindingContext) {
2.1923 - var bindingsString = this['getBindingsString'](node, bindingContext);
2.1924 - return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
2.1925 - },
2.1926 -
2.1927 - // The following function is only used internally by this default provider.
2.1928 - // It's not part of the interface definition for a general binding provider.
2.1929 - 'getBindingsString': function(node, bindingContext) {
2.1930 - switch (node.nodeType) {
2.1931 - case 1: return node.getAttribute(defaultBindingAttributeName); // Element
2.1932 - case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
2.1933 - default: return null;
2.1934 - }
2.1935 - },
2.1936 -
2.1937 - // The following function is only used internally by this default provider.
2.1938 - // It's not part of the interface definition for a general binding provider.
2.1939 - 'parseBindingsString': function(bindingsString, bindingContext, node) {
2.1940 - try {
2.1941 - var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
2.1942 - return bindingFunction(bindingContext, node);
2.1943 - } catch (ex) {
2.1944 - throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
2.1945 - }
2.1946 - }
2.1947 - });
2.1948 -
2.1949 - ko.bindingProvider['instance'] = new ko.bindingProvider();
2.1950 -
2.1951 - function createBindingsStringEvaluatorViaCache(bindingsString, cache) {
2.1952 - var cacheKey = bindingsString;
2.1953 - return cache[cacheKey]
2.1954 - || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString));
2.1955 - }
2.1956 -
2.1957 - function createBindingsStringEvaluator(bindingsString) {
2.1958 - // Build the source for a function that evaluates "expression"
2.1959 - // For each scope variable, add an extra level of "with" nesting
2.1960 - // Example result: with(sc1) { with(sc0) { return (expression) } }
2.1961 - var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString),
2.1962 - functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
2.1963 - return new Function("$context", "$element", functionBody);
2.1964 - }
2.1965 -})();
2.1966 -
2.1967 -ko.exportSymbol('bindingProvider', ko.bindingProvider);
2.1968 -(function () {
2.1969 - ko.bindingHandlers = {};
2.1970 -
2.1971 - ko.bindingContext = function(dataItem, parentBindingContext, dataItemAlias) {
2.1972 - if (parentBindingContext) {
2.1973 - ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
2.1974 - this['$parentContext'] = parentBindingContext;
2.1975 - this['$parent'] = parentBindingContext['$data'];
2.1976 - this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
2.1977 - this['$parents'].unshift(this['$parent']);
2.1978 - } else {
2.1979 - this['$parents'] = [];
2.1980 - this['$root'] = dataItem;
2.1981 - // Export 'ko' in the binding context so it will be available in bindings and templates
2.1982 - // even if 'ko' isn't exported as a global, such as when using an AMD loader.
2.1983 - // See https://github.com/SteveSanderson/knockout/issues/490
2.1984 - this['ko'] = ko;
2.1985 - }
2.1986 - this['$data'] = dataItem;
2.1987 - if (dataItemAlias)
2.1988 - this[dataItemAlias] = dataItem;
2.1989 - }
2.1990 - ko.bindingContext.prototype['createChildContext'] = function (dataItem, dataItemAlias) {
2.1991 - return new ko.bindingContext(dataItem, this, dataItemAlias);
2.1992 - };
2.1993 - ko.bindingContext.prototype['extend'] = function(properties) {
2.1994 - var clone = ko.utils.extend(new ko.bindingContext(), this);
2.1995 - return ko.utils.extend(clone, properties);
2.1996 - };
2.1997 -
2.1998 - function validateThatBindingIsAllowedForVirtualElements(bindingName) {
2.1999 - var validator = ko.virtualElements.allowedBindings[bindingName];
2.2000 - if (!validator)
2.2001 - throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
2.2002 - }
2.2003 -
2.2004 - function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
2.2005 - var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
2.2006 - while (currentChild = nextInQueue) {
2.2007 - // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
2.2008 - nextInQueue = ko.virtualElements.nextSibling(currentChild);
2.2009 - applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
2.2010 - }
2.2011 - }
2.2012 -
2.2013 - function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
2.2014 - var shouldBindDescendants = true;
2.2015 -
2.2016 - // Perf optimisation: Apply bindings only if...
2.2017 - // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
2.2018 - // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
2.2019 - // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
2.2020 - var isElement = (nodeVerified.nodeType === 1);
2.2021 - if (isElement) // Workaround IE <= 8 HTML parsing weirdness
2.2022 - ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
2.2023 -
2.2024 - var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
2.2025 - || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
2.2026 - if (shouldApplyBindings)
2.2027 - shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
2.2028 -
2.2029 - if (shouldBindDescendants) {
2.2030 - // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
2.2031 - // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
2.2032 - // hence bindingContextsMayDifferFromDomParentElement is false
2.2033 - // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
2.2034 - // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
2.2035 - // hence bindingContextsMayDifferFromDomParentElement is true
2.2036 - applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
2.2037 - }
2.2038 - }
2.2039 -
2.2040 - function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
2.2041 - // Need to be sure that inits are only run once, and updates never run until all the inits have been run
2.2042 - var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
2.2043 -
2.2044 - // Each time the dependentObservable is evaluated (after data changes),
2.2045 - // the binding attribute is reparsed so that it can pick out the correct
2.2046 - // model properties in the context of the changed data.
2.2047 - // DOM event callbacks need to be able to access this changed data,
2.2048 - // so we need a single parsedBindings variable (shared by all callbacks
2.2049 - // associated with this node's bindings) that all the closures can access.
2.2050 - var parsedBindings;
2.2051 - function makeValueAccessor(bindingKey) {
2.2052 - return function () { return parsedBindings[bindingKey] }
2.2053 - }
2.2054 - function parsedBindingsAccessor() {
2.2055 - return parsedBindings;
2.2056 - }
2.2057 -
2.2058 - var bindingHandlerThatControlsDescendantBindings;
2.2059 - ko.dependentObservable(
2.2060 - function () {
2.2061 - // Ensure we have a nonnull binding context to work with
2.2062 - var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
2.2063 - ? viewModelOrBindingContext
2.2064 - : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
2.2065 - var viewModel = bindingContextInstance['$data'];
2.2066 -
2.2067 - // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
2.2068 - // we can easily recover it just by scanning up the node's ancestors in the DOM
2.2069 - // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
2.2070 - if (bindingContextMayDifferFromDomParentElement)
2.2071 - ko.storedBindingContextForNode(node, bindingContextInstance);
2.2072 -
2.2073 - // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
2.2074 - var evaluatedBindings = (typeof bindings == "function") ? bindings(bindingContextInstance, node) : bindings;
2.2075 - parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
2.2076 -
2.2077 - if (parsedBindings) {
2.2078 - // First run all the inits, so bindings can register for notification on changes
2.2079 - if (initPhase === 0) {
2.2080 - initPhase = 1;
2.2081 - for (var bindingKey in parsedBindings) {
2.2082 - var binding = ko.bindingHandlers[bindingKey];
2.2083 - if (binding && node.nodeType === 8)
2.2084 - validateThatBindingIsAllowedForVirtualElements(bindingKey);
2.2085 -
2.2086 - if (binding && typeof binding["init"] == "function") {
2.2087 - var handlerInitFn = binding["init"];
2.2088 - var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
2.2089 -
2.2090 - // If this binding handler claims to control descendant bindings, make a note of this
2.2091 - if (initResult && initResult['controlsDescendantBindings']) {
2.2092 - if (bindingHandlerThatControlsDescendantBindings !== undefined)
2.2093 - throw new Error("Multiple bindings (" + bindingHandlerThatControlsDescendantBindings + " and " + bindingKey + ") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");
2.2094 - bindingHandlerThatControlsDescendantBindings = bindingKey;
2.2095 - }
2.2096 - }
2.2097 - }
2.2098 - initPhase = 2;
2.2099 - }
2.2100 -
2.2101 - // ... then run all the updates, which might trigger changes even on the first evaluation
2.2102 - if (initPhase === 2) {
2.2103 - for (var bindingKey in parsedBindings) {
2.2104 - var binding = ko.bindingHandlers[bindingKey];
2.2105 - if (binding && typeof binding["update"] == "function") {
2.2106 - var handlerUpdateFn = binding["update"];
2.2107 - handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
2.2108 - }
2.2109 - }
2.2110 - }
2.2111 - }
2.2112 - },
2.2113 - null,
2.2114 - { disposeWhenNodeIsRemoved : node }
2.2115 - );
2.2116 -
2.2117 - return {
2.2118 - shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
2.2119 - };
2.2120 - };
2.2121 -
2.2122 - var storedBindingContextDomDataKey = "__ko_bindingContext__";
2.2123 - ko.storedBindingContextForNode = function (node, bindingContext) {
2.2124 - if (arguments.length == 2)
2.2125 - ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
2.2126 - else
2.2127 - return ko.utils.domData.get(node, storedBindingContextDomDataKey);
2.2128 - }
2.2129 -
2.2130 - ko.applyBindingsToNode = function (node, bindings, viewModel) {
2.2131 - if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
2.2132 - ko.virtualElements.normaliseVirtualElementDomStructure(node);
2.2133 - return applyBindingsToNodeInternal(node, bindings, viewModel, true);
2.2134 - };
2.2135 -
2.2136 - ko.applyBindingsToDescendants = function(viewModel, rootNode) {
2.2137 - if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
2.2138 - applyBindingsToDescendantsInternal(viewModel, rootNode, true);
2.2139 - };
2.2140 -
2.2141 - ko.applyBindings = function (viewModel, rootNode) {
2.2142 - if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
2.2143 - throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
2.2144 - rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
2.2145 -
2.2146 - applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
2.2147 - };
2.2148 -
2.2149 - // Retrieving binding context from arbitrary nodes
2.2150 - ko.contextFor = function(node) {
2.2151 - // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
2.2152 - switch (node.nodeType) {
2.2153 - case 1:
2.2154 - case 8:
2.2155 - var context = ko.storedBindingContextForNode(node);
2.2156 - if (context) return context;
2.2157 - if (node.parentNode) return ko.contextFor(node.parentNode);
2.2158 - break;
2.2159 - }
2.2160 - return undefined;
2.2161 - };
2.2162 - ko.dataFor = function(node) {
2.2163 - var context = ko.contextFor(node);
2.2164 - return context ? context['$data'] : undefined;
2.2165 - };
2.2166 -
2.2167 - ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
2.2168 - ko.exportSymbol('applyBindings', ko.applyBindings);
2.2169 - ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
2.2170 - ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
2.2171 - ko.exportSymbol('contextFor', ko.contextFor);
2.2172 - ko.exportSymbol('dataFor', ko.dataFor);
2.2173 -})();
2.2174 -var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
2.2175 -ko.bindingHandlers['attr'] = {
2.2176 - 'update': function(element, valueAccessor, allBindingsAccessor) {
2.2177 - var value = ko.utils.unwrapObservable(valueAccessor()) || {};
2.2178 - for (var attrName in value) {
2.2179 - if (typeof attrName == "string") {
2.2180 - var attrValue = ko.utils.unwrapObservable(value[attrName]);
2.2181 -
2.2182 - // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
2.2183 - // when someProp is a "no value"-like value (strictly null, false, or undefined)
2.2184 - // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
2.2185 - var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
2.2186 - if (toRemove)
2.2187 - element.removeAttribute(attrName);
2.2188 -
2.2189 - // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
2.2190 - // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
2.2191 - // but instead of figuring out the mode, we'll just set the attribute through the Javascript
2.2192 - // property for IE <= 8.
2.2193 - if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
2.2194 - attrName = attrHtmlToJavascriptMap[attrName];
2.2195 - if (toRemove)
2.2196 - element.removeAttribute(attrName);
2.2197 - else
2.2198 - element[attrName] = attrValue;
2.2199 - } else if (!toRemove) {
2.2200 - try {
2.2201 - element.setAttribute(attrName, attrValue.toString());
2.2202 - } catch (err) {
2.2203 - // ignore for now
2.2204 - if (console) {
2.2205 - console.log("Can't set attribute " + attrName + " to " + attrValue + " error: " + err);
2.2206 - }
2.2207 - }
2.2208 - }
2.2209 -
2.2210 - // Treat "name" specially - although you can think of it as an attribute, it also needs
2.2211 - // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
2.2212 - // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
2.2213 - // entirely, and there's no strong reason to allow for such casing in HTML.
2.2214 - if (attrName === "name") {
2.2215 - ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
2.2216 - }
2.2217 - }
2.2218 - }
2.2219 - }
2.2220 -};
2.2221 -ko.bindingHandlers['checked'] = {
2.2222 - 'init': function (element, valueAccessor, allBindingsAccessor) {
2.2223 - var updateHandler = function() {
2.2224 - var valueToWrite;
2.2225 - if (element.type == "checkbox") {
2.2226 - valueToWrite = element.checked;
2.2227 - } else if ((element.type == "radio") && (element.checked)) {
2.2228 - valueToWrite = element.value;
2.2229 - } else {
2.2230 - return; // "checked" binding only responds to checkboxes and selected radio buttons
2.2231 - }
2.2232 -
2.2233 - var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
2.2234 - if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
2.2235 - // For checkboxes bound to an array, we add/remove the checkbox value to that array
2.2236 - // This works for both observable and non-observable arrays
2.2237 - var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
2.2238 - if (element.checked && (existingEntryIndex < 0))
2.2239 - modelValue.push(element.value);
2.2240 - else if ((!element.checked) && (existingEntryIndex >= 0))
2.2241 - modelValue.splice(existingEntryIndex, 1);
2.2242 - } else {
2.2243 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
2.2244 - }
2.2245 - };
2.2246 - ko.utils.registerEventHandler(element, "click", updateHandler);
2.2247 -
2.2248 - // IE 6 won't allow radio buttons to be selected unless they have a name
2.2249 - if ((element.type == "radio") && !element.name)
2.2250 - ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
2.2251 - },
2.2252 - 'update': function (element, valueAccessor) {
2.2253 - var value = ko.utils.unwrapObservable(valueAccessor());
2.2254 -
2.2255 - if (element.type == "checkbox") {
2.2256 - if (value instanceof Array) {
2.2257 - // When bound to an array, the checkbox being checked represents its value being present in that array
2.2258 - element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
2.2259 - } else {
2.2260 - // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
2.2261 - element.checked = value;
2.2262 - }
2.2263 - } else if (element.type == "radio") {
2.2264 - element.checked = (element.value == value);
2.2265 - }
2.2266 - }
2.2267 -};
2.2268 -var classesWrittenByBindingKey = '__ko__cssValue';
2.2269 -ko.bindingHandlers['css'] = {
2.2270 - 'update': function (element, valueAccessor) {
2.2271 - var value = ko.utils.unwrapObservable(valueAccessor());
2.2272 - if (typeof value == "object") {
2.2273 - for (var className in value) {
2.2274 - var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
2.2275 - ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
2.2276 - }
2.2277 - } else {
2.2278 - value = String(value || ''); // Make sure we don't try to store or set a non-string value
2.2279 - ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
2.2280 - element[classesWrittenByBindingKey] = value;
2.2281 - ko.utils.toggleDomNodeCssClass(element, value, true);
2.2282 - }
2.2283 - }
2.2284 -};
2.2285 -ko.bindingHandlers['enable'] = {
2.2286 - 'update': function (element, valueAccessor) {
2.2287 - var value = ko.utils.unwrapObservable(valueAccessor());
2.2288 - if (value && element.disabled)
2.2289 - element.removeAttribute("disabled");
2.2290 - else if ((!value) && (!element.disabled))
2.2291 - element.disabled = true;
2.2292 - }
2.2293 -};
2.2294 -
2.2295 -ko.bindingHandlers['disable'] = {
2.2296 - 'update': function (element, valueAccessor) {
2.2297 - ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
2.2298 - }
2.2299 -};
2.2300 -// For certain common events (currently just 'click'), allow a simplified data-binding syntax
2.2301 -// e.g. click:handler instead of the usual full-length event:{click:handler}
2.2302 -function makeEventHandlerShortcut(eventName) {
2.2303 - ko.bindingHandlers[eventName] = {
2.2304 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
2.2305 - var newValueAccessor = function () {
2.2306 - var result = {};
2.2307 - result[eventName] = valueAccessor();
2.2308 - return result;
2.2309 - };
2.2310 - return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
2.2311 - }
2.2312 - }
2.2313 -}
2.2314 -
2.2315 -ko.bindingHandlers['event'] = {
2.2316 - 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
2.2317 - var eventsToHandle = valueAccessor() || {};
2.2318 - for(var eventNameOutsideClosure in eventsToHandle) {
2.2319 - (function() {
2.2320 - var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
2.2321 - if (typeof eventName == "string") {
2.2322 - ko.utils.registerEventHandler(element, eventName, function (event) {
2.2323 - var handlerReturnValue;
2.2324 - var handlerFunction = valueAccessor()[eventName];
2.2325 - if (!handlerFunction)
2.2326 - return;
2.2327 - var allBindings = allBindingsAccessor();
2.2328 -
2.2329 - try {
2.2330 - // Take all the event args, and prefix with the viewmodel
2.2331 - var argsForHandler = ko.utils.makeArray(arguments);
2.2332 - argsForHandler.unshift(viewModel);
2.2333 - handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
2.2334 - } finally {
2.2335 - if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
2.2336 - if (event.preventDefault)
2.2337 - event.preventDefault();
2.2338 - else
2.2339 - event.returnValue = false;
2.2340 - }
2.2341 - }
2.2342 -
2.2343 - var bubble = allBindings[eventName + 'Bubble'] !== false;
2.2344 - if (!bubble) {
2.2345 - event.cancelBubble = true;
2.2346 - if (event.stopPropagation)
2.2347 - event.stopPropagation();
2.2348 - }
2.2349 - });
2.2350 - }
2.2351 - })();
2.2352 - }
2.2353 - }
2.2354 -};
2.2355 -// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
2.2356 -// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
2.2357 -ko.bindingHandlers['foreach'] = {
2.2358 - makeTemplateValueAccessor: function(valueAccessor) {
2.2359 - return function() {
2.2360 - var modelValue = valueAccessor(),
2.2361 - unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
2.2362 -
2.2363 - // If unwrappedValue is the array, pass in the wrapped value on its own
2.2364 - // The value will be unwrapped and tracked within the template binding
2.2365 - // (See https://github.com/SteveSanderson/knockout/issues/523)
2.2366 - if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
2.2367 - return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
2.2368 -
2.2369 - // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
2.2370 - ko.utils.unwrapObservable(modelValue);
2.2371 - return {
2.2372 - 'foreach': unwrappedValue['data'],
2.2373 - 'as': unwrappedValue['as'],
2.2374 - 'includeDestroyed': unwrappedValue['includeDestroyed'],
2.2375 - 'afterAdd': unwrappedValue['afterAdd'],
2.2376 - 'beforeRemove': unwrappedValue['beforeRemove'],
2.2377 - 'afterRender': unwrappedValue['afterRender'],
2.2378 - 'beforeMove': unwrappedValue['beforeMove'],
2.2379 - 'afterMove': unwrappedValue['afterMove'],
2.2380 - 'templateEngine': ko.nativeTemplateEngine.instance
2.2381 - };
2.2382 - };
2.2383 - },
2.2384 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.2385 - return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
2.2386 - },
2.2387 - 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.2388 - return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
2.2389 - }
2.2390 -};
2.2391 -ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
2.2392 -ko.virtualElements.allowedBindings['foreach'] = true;
2.2393 -var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
2.2394 -ko.bindingHandlers['hasfocus'] = {
2.2395 - 'init': function(element, valueAccessor, allBindingsAccessor) {
2.2396 - var handleElementFocusChange = function(isFocused) {
2.2397 - // Where possible, ignore which event was raised and determine focus state using activeElement,
2.2398 - // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
2.2399 - // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
2.2400 - // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
2.2401 - // from calling 'blur()' on the element when it loses focus.
2.2402 - // Discussion at https://github.com/SteveSanderson/knockout/pull/352
2.2403 - element[hasfocusUpdatingProperty] = true;
2.2404 - var ownerDoc = element.ownerDocument;
2.2405 - if ("activeElement" in ownerDoc) {
2.2406 - isFocused = (ownerDoc.activeElement === element);
2.2407 - }
2.2408 - var modelValue = valueAccessor();
2.2409 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true);
2.2410 - element[hasfocusUpdatingProperty] = false;
2.2411 - };
2.2412 - var handleElementFocusIn = handleElementFocusChange.bind(null, true);
2.2413 - var handleElementFocusOut = handleElementFocusChange.bind(null, false);
2.2414 -
2.2415 - ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
2.2416 - ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
2.2417 - ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
2.2418 - ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
2.2419 - },
2.2420 - 'update': function(element, valueAccessor) {
2.2421 - var value = ko.utils.unwrapObservable(valueAccessor());
2.2422 - if (!element[hasfocusUpdatingProperty]) {
2.2423 - value ? element.focus() : element.blur();
2.2424 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
2.2425 - }
2.2426 - }
2.2427 -};
2.2428 -ko.bindingHandlers['html'] = {
2.2429 - 'init': function() {
2.2430 - // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
2.2431 - return { 'controlsDescendantBindings': true };
2.2432 - },
2.2433 - 'update': function (element, valueAccessor) {
2.2434 - // setHtml will unwrap the value if needed
2.2435 - ko.utils.setHtml(element, valueAccessor());
2.2436 - }
2.2437 -};
2.2438 -var withIfDomDataKey = '__ko_withIfBindingData';
2.2439 -// Makes a binding like with or if
2.2440 -function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
2.2441 - ko.bindingHandlers[bindingKey] = {
2.2442 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.2443 - ko.utils.domData.set(element, withIfDomDataKey, {});
2.2444 - return { 'controlsDescendantBindings': true };
2.2445 - },
2.2446 - 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.2447 - var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
2.2448 - dataValue = ko.utils.unwrapObservable(valueAccessor()),
2.2449 - shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
2.2450 - isFirstRender = !withIfData.savedNodes,
2.2451 - needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
2.2452 -
2.2453 - if (needsRefresh) {
2.2454 - if (isFirstRender) {
2.2455 - withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
2.2456 - }
2.2457 -
2.2458 - if (shouldDisplay) {
2.2459 - if (!isFirstRender) {
2.2460 - ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
2.2461 - }
2.2462 - ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
2.2463 - } else {
2.2464 - ko.virtualElements.emptyNode(element);
2.2465 - }
2.2466 -
2.2467 - withIfData.didDisplayOnLastUpdate = shouldDisplay;
2.2468 - }
2.2469 - }
2.2470 - };
2.2471 - ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
2.2472 - ko.virtualElements.allowedBindings[bindingKey] = true;
2.2473 -}
2.2474 -
2.2475 -// Construct the actual binding handlers
2.2476 -makeWithIfBinding('if');
2.2477 -makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
2.2478 -makeWithIfBinding('with', true /* isWith */, false /* isNot */,
2.2479 - function(bindingContext, dataValue) {
2.2480 - return bindingContext['createChildContext'](dataValue);
2.2481 - }
2.2482 -);
2.2483 -function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
2.2484 - if (preferModelValue) {
2.2485 - if (modelValue !== ko.selectExtensions.readValue(element))
2.2486 - ko.selectExtensions.writeValue(element, modelValue);
2.2487 - }
2.2488 -
2.2489 - // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
2.2490 - // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
2.2491 - // change the model value to match the dropdown.
2.2492 - if (modelValue !== ko.selectExtensions.readValue(element))
2.2493 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
2.2494 -};
2.2495 -
2.2496 -ko.bindingHandlers['options'] = {
2.2497 - 'update': function (element, valueAccessor, allBindingsAccessor) {
2.2498 - if (ko.utils.tagNameLower(element) !== "select")
2.2499 - throw new Error("options binding applies only to SELECT elements");
2.2500 -
2.2501 - var selectWasPreviouslyEmpty = element.length == 0;
2.2502 - var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
2.2503 - return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
2.2504 - }), function (node) {
2.2505 - return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
2.2506 - });
2.2507 - var previousScrollTop = element.scrollTop;
2.2508 -
2.2509 - var value = ko.utils.unwrapObservable(valueAccessor());
2.2510 - var selectedValue = element.value;
2.2511 -
2.2512 - // Remove all existing <option>s.
2.2513 - // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
2.2514 - while (element.length > 0) {
2.2515 - ko.cleanNode(element.options[0]);
2.2516 - element.remove(0);
2.2517 - }
2.2518 -
2.2519 - if (value) {
2.2520 - var allBindings = allBindingsAccessor(),
2.2521 - includeDestroyed = allBindings['optionsIncludeDestroyed'];
2.2522 -
2.2523 - if (typeof value.length != "number")
2.2524 - value = [value];
2.2525 - if (allBindings['optionsCaption']) {
2.2526 - var option = document.createElement("option");
2.2527 - ko.utils.setHtml(option, allBindings['optionsCaption']);
2.2528 - ko.selectExtensions.writeValue(option, undefined);
2.2529 - element.appendChild(option);
2.2530 - }
2.2531 -
2.2532 - for (var i = 0, j = value.length; i < j; i++) {
2.2533 - // Skip destroyed items
2.2534 - var arrayEntry = value[i];
2.2535 - if (arrayEntry && arrayEntry['_destroy'] && !includeDestroyed)
2.2536 - continue;
2.2537 -
2.2538 - var option = document.createElement("option");
2.2539 -
2.2540 - function applyToObject(object, predicate, defaultValue) {
2.2541 - var predicateType = typeof predicate;
2.2542 - if (predicateType == "function") // Given a function; run it against the data value
2.2543 - return predicate(object);
2.2544 - else if (predicateType == "string") // Given a string; treat it as a property name on the data value
2.2545 - return object[predicate];
2.2546 - else // Given no optionsText arg; use the data value itself
2.2547 - return defaultValue;
2.2548 - }
2.2549 -
2.2550 - // Apply a value to the option element
2.2551 - var optionValue = applyToObject(arrayEntry, allBindings['optionsValue'], arrayEntry);
2.2552 - ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
2.2553 -
2.2554 - // Apply some text to the option element
2.2555 - var optionText = applyToObject(arrayEntry, allBindings['optionsText'], optionValue);
2.2556 - ko.utils.setTextContent(option, optionText);
2.2557 -
2.2558 - element.appendChild(option);
2.2559 - }
2.2560 -
2.2561 - // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
2.2562 - // That's why we first added them without selection. Now it's time to set the selection.
2.2563 - var newOptions = element.getElementsByTagName("option");
2.2564 - var countSelectionsRetained = 0;
2.2565 - for (var i = 0, j = newOptions.length; i < j; i++) {
2.2566 - if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
2.2567 - ko.utils.setOptionNodeSelectionState(newOptions[i], true);
2.2568 - countSelectionsRetained++;
2.2569 - }
2.2570 - }
2.2571 -
2.2572 - element.scrollTop = previousScrollTop;
2.2573 -
2.2574 - if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
2.2575 - // Ensure consistency between model value and selected option.
2.2576 - // If the dropdown is being populated for the first time here (or was otherwise previously empty),
2.2577 - // the dropdown selection state is meaningless, so we preserve the model value.
2.2578 - ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.peekObservable(allBindings['value']), /* preferModelValue */ true);
2.2579 - }
2.2580 -
2.2581 - // Workaround for IE9 bug
2.2582 - ko.utils.ensureSelectElementIsRenderedCorrectly(element);
2.2583 - }
2.2584 - }
2.2585 -};
2.2586 -ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
2.2587 -ko.bindingHandlers['selectedOptions'] = {
2.2588 - 'init': function (element, valueAccessor, allBindingsAccessor) {
2.2589 - ko.utils.registerEventHandler(element, "change", function () {
2.2590 - var value = valueAccessor(), valueToWrite = [];
2.2591 - ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
2.2592 - if (node.selected)
2.2593 - valueToWrite.push(ko.selectExtensions.readValue(node));
2.2594 - });
2.2595 - ko.expressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
2.2596 - });
2.2597 - },
2.2598 - 'update': function (element, valueAccessor) {
2.2599 - if (ko.utils.tagNameLower(element) != "select")
2.2600 - throw new Error("values binding applies only to SELECT elements");
2.2601 -
2.2602 - var newValue = ko.utils.unwrapObservable(valueAccessor());
2.2603 - if (newValue && typeof newValue.length == "number") {
2.2604 - ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
2.2605 - var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
2.2606 - ko.utils.setOptionNodeSelectionState(node, isSelected);
2.2607 - });
2.2608 - }
2.2609 - }
2.2610 -};
2.2611 -ko.bindingHandlers['style'] = {
2.2612 - 'update': function (element, valueAccessor) {
2.2613 - var value = ko.utils.unwrapObservable(valueAccessor() || {});
2.2614 - for (var styleName in value) {
2.2615 - if (typeof styleName == "string") {
2.2616 - var styleValue = ko.utils.unwrapObservable(value[styleName]);
2.2617 - element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
2.2618 - }
2.2619 - }
2.2620 - }
2.2621 -};
2.2622 -ko.bindingHandlers['submit'] = {
2.2623 - 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
2.2624 - if (typeof valueAccessor() != "function")
2.2625 - throw new Error("The value for a submit binding must be a function");
2.2626 - ko.utils.registerEventHandler(element, "submit", function (event) {
2.2627 - var handlerReturnValue;
2.2628 - var value = valueAccessor();
2.2629 - try { handlerReturnValue = value.call(viewModel, element); }
2.2630 - finally {
2.2631 - if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
2.2632 - if (event.preventDefault)
2.2633 - event.preventDefault();
2.2634 - else
2.2635 - event.returnValue = false;
2.2636 - }
2.2637 - }
2.2638 - });
2.2639 - }
2.2640 -};
2.2641 -ko.bindingHandlers['text'] = {
2.2642 - 'update': function (element, valueAccessor) {
2.2643 - ko.utils.setTextContent(element, valueAccessor());
2.2644 - }
2.2645 -};
2.2646 -ko.virtualElements.allowedBindings['text'] = true;
2.2647 -ko.bindingHandlers['uniqueName'] = {
2.2648 - 'init': function (element, valueAccessor) {
2.2649 - if (valueAccessor()) {
2.2650 - var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
2.2651 - ko.utils.setElementName(element, name);
2.2652 - }
2.2653 - }
2.2654 -};
2.2655 -ko.bindingHandlers['uniqueName'].currentIndex = 0;
2.2656 -ko.bindingHandlers['value'] = {
2.2657 - 'init': function (element, valueAccessor, allBindingsAccessor) {
2.2658 - // Always catch "change" event; possibly other events too if asked
2.2659 - var eventsToCatch = ["change"];
2.2660 - var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
2.2661 - var propertyChangedFired = false;
2.2662 - if (requestedEventsToCatch) {
2.2663 - if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
2.2664 - requestedEventsToCatch = [requestedEventsToCatch];
2.2665 - ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
2.2666 - eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
2.2667 - }
2.2668 -
2.2669 - var valueUpdateHandler = function() {
2.2670 - propertyChangedFired = false;
2.2671 - var modelValue = valueAccessor();
2.2672 - var elementValue = ko.selectExtensions.readValue(element);
2.2673 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
2.2674 - }
2.2675 -
2.2676 - // Workaround for https://github.com/SteveSanderson/knockout/issues/122
2.2677 - // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
2.2678 - var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
2.2679 - && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
2.2680 - if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
2.2681 - ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
2.2682 - ko.utils.registerEventHandler(element, "blur", function() {
2.2683 - if (propertyChangedFired) {
2.2684 - valueUpdateHandler();
2.2685 - }
2.2686 - });
2.2687 - }
2.2688 -
2.2689 - ko.utils.arrayForEach(eventsToCatch, function(eventName) {
2.2690 - // The syntax "after<eventname>" means "run the handler asynchronously after the event"
2.2691 - // This is useful, for example, to catch "keydown" events after the browser has updated the control
2.2692 - // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
2.2693 - var handler = valueUpdateHandler;
2.2694 - if (ko.utils.stringStartsWith(eventName, "after")) {
2.2695 - handler = function() { setTimeout(valueUpdateHandler, 0) };
2.2696 - eventName = eventName.substring("after".length);
2.2697 - }
2.2698 - ko.utils.registerEventHandler(element, eventName, handler);
2.2699 - });
2.2700 - },
2.2701 - 'update': function (element, valueAccessor) {
2.2702 - var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
2.2703 - var newValue = ko.utils.unwrapObservable(valueAccessor());
2.2704 - var elementValue = ko.selectExtensions.readValue(element);
2.2705 - var valueHasChanged = (newValue != elementValue);
2.2706 -
2.2707 - // JavaScript's 0 == "" behavious is unfortunate here as it prevents writing 0 to an empty text box (loose equality suggests the values are the same).
2.2708 - // We don't want to do a strict equality comparison as that is more confusing for developers in certain cases, so we specifically special case 0 != "" here.
2.2709 - if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
2.2710 - valueHasChanged = true;
2.2711 -
2.2712 - if (valueHasChanged) {
2.2713 - var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
2.2714 - applyValueAction();
2.2715 -
2.2716 - // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
2.2717 - // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
2.2718 - // to apply the value as well.
2.2719 - var alsoApplyAsynchronously = valueIsSelectOption;
2.2720 - if (alsoApplyAsynchronously)
2.2721 - setTimeout(applyValueAction, 0);
2.2722 - }
2.2723 -
2.2724 - // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
2.2725 - // because you're not allowed to have a model value that disagrees with a visible UI selection.
2.2726 - if (valueIsSelectOption && (element.length > 0))
2.2727 - ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
2.2728 - }
2.2729 -};
2.2730 -ko.bindingHandlers['visible'] = {
2.2731 - 'update': function (element, valueAccessor) {
2.2732 - var value = ko.utils.unwrapObservable(valueAccessor());
2.2733 - var isCurrentlyVisible = !(element.style.display == "none");
2.2734 - if (value && !isCurrentlyVisible)
2.2735 - element.style.display = "";
2.2736 - else if ((!value) && isCurrentlyVisible)
2.2737 - element.style.display = "none";
2.2738 - }
2.2739 -};
2.2740 -// 'click' is just a shorthand for the usual full-length event:{click:handler}
2.2741 -makeEventHandlerShortcut('click');
2.2742 -// If you want to make a custom template engine,
2.2743 -//
2.2744 -// [1] Inherit from this class (like ko.nativeTemplateEngine does)
2.2745 -// [2] Override 'renderTemplateSource', supplying a function with this signature:
2.2746 -//
2.2747 -// function (templateSource, bindingContext, options) {
2.2748 -// // - templateSource.text() is the text of the template you should render
2.2749 -// // - bindingContext.$data is the data you should pass into the template
2.2750 -// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
2.2751 -// // and bindingContext.$root available in the template too
2.2752 -// // - options gives you access to any other properties set on "data-bind: { template: options }"
2.2753 -// //
2.2754 -// // Return value: an array of DOM nodes
2.2755 -// }
2.2756 -//
2.2757 -// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
2.2758 -//
2.2759 -// function (script) {
2.2760 -// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
2.2761 -// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
2.2762 -// }
2.2763 -//
2.2764 -// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
2.2765 -// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
2.2766 -// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
2.2767 -
2.2768 -ko.templateEngine = function () { };
2.2769 -
2.2770 -ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
2.2771 - throw new Error("Override renderTemplateSource");
2.2772 -};
2.2773 -
2.2774 -ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
2.2775 - throw new Error("Override createJavaScriptEvaluatorBlock");
2.2776 -};
2.2777 -
2.2778 -ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
2.2779 - // Named template
2.2780 - if (typeof template == "string") {
2.2781 - templateDocument = templateDocument || document;
2.2782 - var elem = templateDocument.getElementById(template);
2.2783 - if (!elem)
2.2784 - throw new Error("Cannot find template with ID " + template);
2.2785 - return new ko.templateSources.domElement(elem);
2.2786 - } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
2.2787 - // Anonymous template
2.2788 - return new ko.templateSources.anonymousTemplate(template);
2.2789 - } else
2.2790 - throw new Error("Unknown template type: " + template);
2.2791 -};
2.2792 -
2.2793 -ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
2.2794 - var templateSource = this['makeTemplateSource'](template, templateDocument);
2.2795 - return this['renderTemplateSource'](templateSource, bindingContext, options);
2.2796 -};
2.2797 -
2.2798 -ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
2.2799 - // Skip rewriting if requested
2.2800 - if (this['allowTemplateRewriting'] === false)
2.2801 - return true;
2.2802 - return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
2.2803 -};
2.2804 -
2.2805 -ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
2.2806 - var templateSource = this['makeTemplateSource'](template, templateDocument);
2.2807 - var rewritten = rewriterCallback(templateSource['text']());
2.2808 - templateSource['text'](rewritten);
2.2809 - templateSource['data']("isRewritten", true);
2.2810 -};
2.2811 -
2.2812 -ko.exportSymbol('templateEngine', ko.templateEngine);
2.2813 -
2.2814 -ko.templateRewriting = (function () {
2.2815 - var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
2.2816 - var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
2.2817 -
2.2818 - function validateDataBindValuesForRewriting(keyValueArray) {
2.2819 - var allValidators = ko.expressionRewriting.bindingRewriteValidators;
2.2820 - for (var i = 0; i < keyValueArray.length; i++) {
2.2821 - var key = keyValueArray[i]['key'];
2.2822 - if (allValidators.hasOwnProperty(key)) {
2.2823 - var validator = allValidators[key];
2.2824 -
2.2825 - if (typeof validator === "function") {
2.2826 - var possibleErrorMessage = validator(keyValueArray[i]['value']);
2.2827 - if (possibleErrorMessage)
2.2828 - throw new Error(possibleErrorMessage);
2.2829 - } else if (!validator) {
2.2830 - throw new Error("This template engine does not support the '" + key + "' binding within its templates");
2.2831 - }
2.2832 - }
2.2833 - }
2.2834 - }
2.2835 -
2.2836 - function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
2.2837 - var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
2.2838 - validateDataBindValuesForRewriting(dataBindKeyValueArray);
2.2839 - var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray);
2.2840 -
2.2841 - // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
2.2842 - // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
2.2843 - // extra indirection.
2.2844 - var applyBindingsToNextSiblingScript =
2.2845 - "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()})";
2.2846 - return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
2.2847 - }
2.2848 -
2.2849 - return {
2.2850 - ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
2.2851 - if (!templateEngine['isTemplateRewritten'](template, templateDocument))
2.2852 - templateEngine['rewriteTemplate'](template, function (htmlString) {
2.2853 - return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
2.2854 - }, templateDocument);
2.2855 - },
2.2856 -
2.2857 - memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
2.2858 - return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
2.2859 - return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
2.2860 - }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
2.2861 - return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
2.2862 - });
2.2863 - },
2.2864 -
2.2865 - applyMemoizedBindingsToNextSibling: function (bindings) {
2.2866 - return ko.memoization.memoize(function (domNode, bindingContext) {
2.2867 - if (domNode.nextSibling)
2.2868 - ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
2.2869 - });
2.2870 - }
2.2871 - }
2.2872 -})();
2.2873 -
2.2874 -
2.2875 -// Exported only because it has to be referenced by string lookup from within rewritten template
2.2876 -ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
2.2877 -(function() {
2.2878 - // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
2.2879 - // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
2.2880 - //
2.2881 - // Two are provided by default:
2.2882 - // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
2.2883 - // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
2.2884 - // without reading/writing the actual element text content, since it will be overwritten
2.2885 - // with the rendered template output.
2.2886 - // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
2.2887 - // Template sources need to have the following functions:
2.2888 - // text() - returns the template text from your storage location
2.2889 - // text(value) - writes the supplied template text to your storage location
2.2890 - // data(key) - reads values stored using data(key, value) - see below
2.2891 - // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
2.2892 - //
2.2893 - // Optionally, template sources can also have the following functions:
2.2894 - // nodes() - returns a DOM element containing the nodes of this template, where available
2.2895 - // nodes(value) - writes the given DOM element to your storage location
2.2896 - // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
2.2897 - // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
2.2898 - //
2.2899 - // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
2.2900 - // using and overriding "makeTemplateSource" to return an instance of your custom template source.
2.2901 -
2.2902 - ko.templateSources = {};
2.2903 -
2.2904 - // ---- ko.templateSources.domElement -----
2.2905 -
2.2906 - ko.templateSources.domElement = function(element) {
2.2907 - this.domElement = element;
2.2908 - }
2.2909 -
2.2910 - ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
2.2911 - var tagNameLower = ko.utils.tagNameLower(this.domElement),
2.2912 - elemContentsProperty = tagNameLower === "script" ? "text"
2.2913 - : tagNameLower === "textarea" ? "value"
2.2914 - : "innerHTML";
2.2915 -
2.2916 - if (arguments.length == 0) {
2.2917 - return this.domElement[elemContentsProperty];
2.2918 - } else {
2.2919 - var valueToWrite = arguments[0];
2.2920 - if (elemContentsProperty === "innerHTML")
2.2921 - ko.utils.setHtml(this.domElement, valueToWrite);
2.2922 - else
2.2923 - this.domElement[elemContentsProperty] = valueToWrite;
2.2924 - }
2.2925 - };
2.2926 -
2.2927 - ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
2.2928 - if (arguments.length === 1) {
2.2929 - return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
2.2930 - } else {
2.2931 - ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
2.2932 - }
2.2933 - };
2.2934 -
2.2935 - // ---- ko.templateSources.anonymousTemplate -----
2.2936 - // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
2.2937 - // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
2.2938 - // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
2.2939 -
2.2940 - var anonymousTemplatesDomDataKey = "__ko_anon_template__";
2.2941 - ko.templateSources.anonymousTemplate = function(element) {
2.2942 - this.domElement = element;
2.2943 - }
2.2944 - ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
2.2945 - ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
2.2946 - if (arguments.length == 0) {
2.2947 - var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
2.2948 - if (templateData.textData === undefined && templateData.containerData)
2.2949 - templateData.textData = templateData.containerData.innerHTML;
2.2950 - return templateData.textData;
2.2951 - } else {
2.2952 - var valueToWrite = arguments[0];
2.2953 - ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
2.2954 - }
2.2955 - };
2.2956 - ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
2.2957 - if (arguments.length == 0) {
2.2958 - var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
2.2959 - return templateData.containerData;
2.2960 - } else {
2.2961 - var valueToWrite = arguments[0];
2.2962 - ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
2.2963 - }
2.2964 - };
2.2965 -
2.2966 - ko.exportSymbol('templateSources', ko.templateSources);
2.2967 - ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
2.2968 - ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
2.2969 -})();
2.2970 -(function () {
2.2971 - var _templateEngine;
2.2972 - ko.setTemplateEngine = function (templateEngine) {
2.2973 - if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
2.2974 - throw new Error("templateEngine must inherit from ko.templateEngine");
2.2975 - _templateEngine = templateEngine;
2.2976 - }
2.2977 -
2.2978 - function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
2.2979 - var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
2.2980 - while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
2.2981 - nextInQueue = ko.virtualElements.nextSibling(node);
2.2982 - if (node.nodeType === 1 || node.nodeType === 8)
2.2983 - action(node);
2.2984 - }
2.2985 - }
2.2986 -
2.2987 - function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
2.2988 - // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
2.2989 - // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
2.2990 - // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
2.2991 - // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
2.2992 - // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
2.2993 -
2.2994 - if (continuousNodeArray.length) {
2.2995 - var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
2.2996 -
2.2997 - // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
2.2998 - // whereas a regular applyBindings won't introduce new memoized nodes
2.2999 - invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
2.3000 - ko.applyBindings(bindingContext, node);
2.3001 - });
2.3002 - invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
2.3003 - ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
2.3004 - });
2.3005 - }
2.3006 - }
2.3007 -
2.3008 - function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
2.3009 - return nodeOrNodeArray.nodeType ? nodeOrNodeArray
2.3010 - : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
2.3011 - : null;
2.3012 - }
2.3013 -
2.3014 - function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
2.3015 - options = options || {};
2.3016 - var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
2.3017 - var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
2.3018 - var templateEngineToUse = (options['templateEngine'] || _templateEngine);
2.3019 - ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
2.3020 - var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
2.3021 -
2.3022 - // Loosely check result is an array of DOM nodes
2.3023 - if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
2.3024 - throw new Error("Template engine must return an array of DOM nodes");
2.3025 -
2.3026 - var haveAddedNodesToParent = false;
2.3027 - switch (renderMode) {
2.3028 - case "replaceChildren":
2.3029 - ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
2.3030 - haveAddedNodesToParent = true;
2.3031 - break;
2.3032 - case "replaceNode":
2.3033 - ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
2.3034 - haveAddedNodesToParent = true;
2.3035 - break;
2.3036 - case "ignoreTargetNode": break;
2.3037 - default:
2.3038 - throw new Error("Unknown renderMode: " + renderMode);
2.3039 - }
2.3040 -
2.3041 - if (haveAddedNodesToParent) {
2.3042 - activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
2.3043 - if (options['afterRender'])
2.3044 - ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
2.3045 - }
2.3046 -
2.3047 - return renderedNodesArray;
2.3048 - }
2.3049 -
2.3050 - ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
2.3051 - options = options || {};
2.3052 - if ((options['templateEngine'] || _templateEngine) == undefined)
2.3053 - throw new Error("Set a template engine before calling renderTemplate");
2.3054 - renderMode = renderMode || "replaceChildren";
2.3055 -
2.3056 - if (targetNodeOrNodeArray) {
2.3057 - var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
2.3058 -
2.3059 - var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
2.3060 - var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
2.3061 -
2.3062 - return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
2.3063 - function () {
2.3064 - // Ensure we've got a proper binding context to work with
2.3065 - var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
2.3066 - ? dataOrBindingContext
2.3067 - : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
2.3068 -
2.3069 - // Support selecting template as a function of the data being rendered
2.3070 - var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
2.3071 -
2.3072 - var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
2.3073 - if (renderMode == "replaceNode") {
2.3074 - targetNodeOrNodeArray = renderedNodesArray;
2.3075 - firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
2.3076 - }
2.3077 - },
2.3078 - null,
2.3079 - { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
2.3080 - );
2.3081 - } else {
2.3082 - // We don't yet have a DOM node to evaluate, so use a memo and render the template later when there is a DOM node
2.3083 - return ko.memoization.memoize(function (domNode) {
2.3084 - ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
2.3085 - });
2.3086 - }
2.3087 - };
2.3088 -
2.3089 - ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
2.3090 - // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
2.3091 - // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
2.3092 - var arrayItemContext;
2.3093 -
2.3094 - // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
2.3095 - var executeTemplateForArrayItem = function (arrayValue, index) {
2.3096 - // Support selecting template as a function of the data being rendered
2.3097 - arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue), options['as']);
2.3098 - arrayItemContext['$index'] = index;
2.3099 - var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
2.3100 - return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
2.3101 - }
2.3102 -
2.3103 - // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
2.3104 - var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
2.3105 - activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
2.3106 - if (options['afterRender'])
2.3107 - options['afterRender'](addedNodesArray, arrayValue);
2.3108 - };
2.3109 -
2.3110 - return ko.dependentObservable(function () {
2.3111 - var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
2.3112 - if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
2.3113 - unwrappedArray = [unwrappedArray];
2.3114 -
2.3115 - // Filter out any entries marked as destroyed
2.3116 - var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
2.3117 - return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
2.3118 - });
2.3119 -
2.3120 - // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
2.3121 - // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
2.3122 - ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
2.3123 -
2.3124 - }, null, { disposeWhenNodeIsRemoved: targetNode });
2.3125 - };
2.3126 -
2.3127 - var templateComputedDomDataKey = '__ko__templateComputedDomDataKey__';
2.3128 - function disposeOldComputedAndStoreNewOne(element, newComputed) {
2.3129 - var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
2.3130 - if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
2.3131 - oldComputed.dispose();
2.3132 - ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
2.3133 - }
2.3134 -
2.3135 - ko.bindingHandlers['template'] = {
2.3136 - 'init': function(element, valueAccessor) {
2.3137 - // Support anonymous templates
2.3138 - var bindingValue = ko.utils.unwrapObservable(valueAccessor());
2.3139 - if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
2.3140 - // It's an anonymous template - store the element contents, then clear the element
2.3141 - var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
2.3142 - container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
2.3143 - new ko.templateSources.anonymousTemplate(element)['nodes'](container);
2.3144 - }
2.3145 - return { 'controlsDescendantBindings': true };
2.3146 - },
2.3147 - 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2.3148 - var templateName = ko.utils.unwrapObservable(valueAccessor()),
2.3149 - options = {},
2.3150 - shouldDisplay = true,
2.3151 - dataValue,
2.3152 - templateComputed = null;
2.3153 -
2.3154 - if (typeof templateName != "string") {
2.3155 - options = templateName;
2.3156 - templateName = options['name'];
2.3157 -
2.3158 - // Support "if"/"ifnot" conditions
2.3159 - if ('if' in options)
2.3160 - shouldDisplay = ko.utils.unwrapObservable(options['if']);
2.3161 - if (shouldDisplay && 'ifnot' in options)
2.3162 - shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
2.3163 -
2.3164 - dataValue = ko.utils.unwrapObservable(options['data']);
2.3165 - }
2.3166 -
2.3167 - if ('foreach' in options) {
2.3168 - // Render once for each data point (treating data set as empty if shouldDisplay==false)
2.3169 - var dataArray = (shouldDisplay && options['foreach']) || [];
2.3170 - templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
2.3171 - } else if (!shouldDisplay) {
2.3172 - ko.virtualElements.emptyNode(element);
2.3173 - } else {
2.3174 - // Render once for this single data point (or use the viewModel if no data was provided)
2.3175 - var innerBindingContext = ('data' in options) ?
2.3176 - bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
2.3177 - bindingContext; // Given no explicit 'data' value, we retain the same binding context
2.3178 - templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
2.3179 - }
2.3180 -
2.3181 - // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
2.3182 - disposeOldComputedAndStoreNewOne(element, templateComputed);
2.3183 - }
2.3184 - };
2.3185 -
2.3186 - // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
2.3187 - ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
2.3188 - var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
2.3189 -
2.3190 - if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
2.3191 - return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
2.3192 -
2.3193 - if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
2.3194 - return null; // Named templates can be rewritten, so return "no error"
2.3195 - return "This template engine does not support anonymous templates nested within its templates";
2.3196 - };
2.3197 -
2.3198 - ko.virtualElements.allowedBindings['template'] = true;
2.3199 -})();
2.3200 -
2.3201 -ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
2.3202 -ko.exportSymbol('renderTemplate', ko.renderTemplate);
2.3203 -
2.3204 -ko.utils.compareArrays = (function () {
2.3205 - var statusNotInOld = 'added', statusNotInNew = 'deleted';
2.3206 -
2.3207 - // Simple calculation based on Levenshtein distance.
2.3208 - function compareArrays(oldArray, newArray, dontLimitMoves) {
2.3209 - oldArray = oldArray || [];
2.3210 - newArray = newArray || [];
2.3211 -
2.3212 - if (oldArray.length <= newArray.length)
2.3213 - return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, dontLimitMoves);
2.3214 - else
2.3215 - return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, dontLimitMoves);
2.3216 - }
2.3217 -
2.3218 - function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, dontLimitMoves) {
2.3219 - var myMin = Math.min,
2.3220 - myMax = Math.max,
2.3221 - editDistanceMatrix = [],
2.3222 - smlIndex, smlIndexMax = smlArray.length,
2.3223 - bigIndex, bigIndexMax = bigArray.length,
2.3224 - compareRange = (bigIndexMax - smlIndexMax) || 1,
2.3225 - maxDistance = smlIndexMax + bigIndexMax + 1,
2.3226 - thisRow, lastRow,
2.3227 - bigIndexMaxForRow, bigIndexMinForRow;
2.3228 -
2.3229 - for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
2.3230 - lastRow = thisRow;
2.3231 - editDistanceMatrix.push(thisRow = []);
2.3232 - bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
2.3233 - bigIndexMinForRow = myMax(0, smlIndex - 1);
2.3234 - for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
2.3235 - if (!bigIndex)
2.3236 - thisRow[bigIndex] = smlIndex + 1;
2.3237 - else if (!smlIndex) // Top row - transform empty array into new array via additions
2.3238 - thisRow[bigIndex] = bigIndex + 1;
2.3239 - else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
2.3240 - thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
2.3241 - else {
2.3242 - var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
2.3243 - var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
2.3244 - thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
2.3245 - }
2.3246 - }
2.3247 - }
2.3248 -
2.3249 - var editScript = [], meMinusOne, notInSml = [], notInBig = [];
2.3250 - for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
2.3251 - meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
2.3252 - if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
2.3253 - notInSml.push(editScript[editScript.length] = { // added
2.3254 - 'status': statusNotInSml,
2.3255 - 'value': bigArray[--bigIndex],
2.3256 - 'index': bigIndex });
2.3257 - } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
2.3258 - notInBig.push(editScript[editScript.length] = { // deleted
2.3259 - 'status': statusNotInBig,
2.3260 - 'value': smlArray[--smlIndex],
2.3261 - 'index': smlIndex });
2.3262 - } else {
2.3263 - editScript.push({
2.3264 - 'status': "retained",
2.3265 - 'value': bigArray[--bigIndex] });
2.3266 - --smlIndex;
2.3267 - }
2.3268 - }
2.3269 -
2.3270 - if (notInSml.length && notInBig.length) {
2.3271 - // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
2.3272 - // smlIndexMax keeps the time complexity of this algorithm linear.
2.3273 - var limitFailedCompares = smlIndexMax * 10, failedCompares,
2.3274 - a, d, notInSmlItem, notInBigItem;
2.3275 - // Go through the items that have been added and deleted and try to find matches between them.
2.3276 - for (failedCompares = a = 0; (dontLimitMoves || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
2.3277 - for (d = 0; notInBigItem = notInBig[d]; d++) {
2.3278 - if (notInSmlItem['value'] === notInBigItem['value']) {
2.3279 - notInSmlItem['moved'] = notInBigItem['index'];
2.3280 - notInBigItem['moved'] = notInSmlItem['index'];
2.3281 - notInBig.splice(d,1); // This item is marked as moved; so remove it from notInBig list
2.3282 - failedCompares = d = 0; // Reset failed compares count because we're checking for consecutive failures
2.3283 - break;
2.3284 - }
2.3285 - }
2.3286 - failedCompares += d;
2.3287 - }
2.3288 - }
2.3289 - return editScript.reverse();
2.3290 - }
2.3291 -
2.3292 - return compareArrays;
2.3293 -})();
2.3294 -
2.3295 -ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
2.3296 -
2.3297 -(function () {
2.3298 - // Objective:
2.3299 - // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
2.3300 - // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
2.3301 - // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
2.3302 - // so that its children is again the concatenation of the mappings of the array elements, but don't re-map any array elements that we
2.3303 - // previously mapped - retain those nodes, and just insert/delete other ones
2.3304 -
2.3305 - // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
2.3306 - // You can use this, for example, to activate bindings on those nodes.
2.3307 -
2.3308 - function fixUpNodesToBeMovedOrRemoved(contiguousNodeArray) {
2.3309 - // Before moving, deleting, or replacing a set of nodes that were previously outputted by the "map" function, we have to reconcile
2.3310 - // them against what is in the DOM right now. It may be that some of the nodes have already been removed from the document,
2.3311 - // or that new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
2.3312 - // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
2.3313 - // So, this function translates the old "map" output array into its best guess of what set of current DOM nodes should be removed.
2.3314 - //
2.3315 - // Rules:
2.3316 - // [A] Any leading nodes that aren't in the document any more should be ignored
2.3317 - // These most likely correspond to memoization nodes that were already removed during binding
2.3318 - // See https://github.com/SteveSanderson/knockout/pull/440
2.3319 - // [B] We want to output a contiguous series of nodes that are still in the document. So, ignore any nodes that
2.3320 - // have already been removed, and include any nodes that have been inserted among the previous collection
2.3321 -
2.3322 - // Rule [A]
2.3323 - while (contiguousNodeArray.length && !ko.utils.domNodeIsAttachedToDocument(contiguousNodeArray[0]))
2.3324 - contiguousNodeArray.splice(0, 1);
2.3325 -
2.3326 - // Rule [B]
2.3327 - if (contiguousNodeArray.length > 1) {
2.3328 - // Build up the actual new contiguous node set
2.3329 - var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
2.3330 - while (current !== last) {
2.3331 - current = current.nextSibling;
2.3332 - if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
2.3333 - return;
2.3334 - newContiguousSet.push(current);
2.3335 - }
2.3336 -
2.3337 - // ... then mutate the input array to match this.
2.3338 - // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
2.3339 - Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
2.3340 - }
2.3341 - return contiguousNodeArray;
2.3342 - }
2.3343 -
2.3344 - function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
2.3345 - // Map this array value inside a dependentObservable so we re-map when any dependency changes
2.3346 - var mappedNodes = [];
2.3347 - var dependentObservable = ko.dependentObservable(function() {
2.3348 - var newMappedNodes = mapping(valueToMap, index) || [];
2.3349 -
2.3350 - // On subsequent evaluations, just replace the previously-inserted DOM nodes
2.3351 - if (mappedNodes.length > 0) {
2.3352 - ko.utils.replaceDomNodes(fixUpNodesToBeMovedOrRemoved(mappedNodes), newMappedNodes);
2.3353 - if (callbackAfterAddingNodes)
2.3354 - ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
2.3355 - }
2.3356 -
2.3357 - // Replace the contents of the mappedNodes array, thereby updating the record
2.3358 - // of which nodes would be deleted if valueToMap was itself later removed
2.3359 - mappedNodes.splice(0, mappedNodes.length);
2.3360 - ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
2.3361 - }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
2.3362 - return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
2.3363 - }
2.3364 -
2.3365 - var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
2.3366 -
2.3367 - ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
2.3368 - // Compare the provided array against the previous one
2.3369 - array = array || [];
2.3370 - options = options || {};
2.3371 - var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
2.3372 - var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
2.3373 - var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
2.3374 - var editScript = ko.utils.compareArrays(lastArray, array);
2.3375 -
2.3376 - // Build the new mapping result
2.3377 - var newMappingResult = [];
2.3378 - var lastMappingResultIndex = 0;
2.3379 - var newMappingResultIndex = 0;
2.3380 -
2.3381 - var nodesToDelete = [];
2.3382 - var itemsToProcess = [];
2.3383 - var itemsForBeforeRemoveCallbacks = [];
2.3384 - var itemsForMoveCallbacks = [];
2.3385 - var itemsForAfterAddCallbacks = [];
2.3386 - var mapData;
2.3387 -
2.3388 - function itemMovedOrRetained(editScriptIndex, oldPosition) {
2.3389 - mapData = lastMappingResult[oldPosition];
2.3390 - if (newMappingResultIndex !== oldPosition)
2.3391 - itemsForMoveCallbacks[editScriptIndex] = mapData;
2.3392 - // Since updating the index might change the nodes, do so before calling fixUpNodesToBeMovedOrRemoved
2.3393 - mapData.indexObservable(newMappingResultIndex++);
2.3394 - fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes);
2.3395 - newMappingResult.push(mapData);
2.3396 - itemsToProcess.push(mapData);
2.3397 - }
2.3398 -
2.3399 - function callCallback(callback, items) {
2.3400 - if (callback) {
2.3401 - for (var i = 0, n = items.length; i < n; i++) {
2.3402 - if (items[i]) {
2.3403 - ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
2.3404 - callback(node, i, items[i].arrayEntry);
2.3405 - });
2.3406 - }
2.3407 - }
2.3408 - }
2.3409 - }
2.3410 -
2.3411 - for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
2.3412 - movedIndex = editScriptItem['moved'];
2.3413 - switch (editScriptItem['status']) {
2.3414 - case "deleted":
2.3415 - if (movedIndex === undefined) {
2.3416 - mapData = lastMappingResult[lastMappingResultIndex];
2.3417 -
2.3418 - // Stop tracking changes to the mapping for these nodes
2.3419 - if (mapData.dependentObservable)
2.3420 - mapData.dependentObservable.dispose();
2.3421 -
2.3422 - // Queue these nodes for later removal
2.3423 - nodesToDelete.push.apply(nodesToDelete, fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes));
2.3424 - if (options['beforeRemove']) {
2.3425 - itemsForBeforeRemoveCallbacks[i] = mapData;
2.3426 - itemsToProcess.push(mapData);
2.3427 - }
2.3428 - }
2.3429 - lastMappingResultIndex++;
2.3430 - break;
2.3431 -
2.3432 - case "retained":
2.3433 - itemMovedOrRetained(i, lastMappingResultIndex++);
2.3434 - break;
2.3435 -
2.3436 - case "added":
2.3437 - if (movedIndex !== undefined) {
2.3438 - itemMovedOrRetained(i, movedIndex);
2.3439 - } else {
2.3440 - mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
2.3441 - newMappingResult.push(mapData);
2.3442 - itemsToProcess.push(mapData);
2.3443 - if (!isFirstExecution)
2.3444 - itemsForAfterAddCallbacks[i] = mapData;
2.3445 - }
2.3446 - break;
2.3447 - }
2.3448 - }
2.3449 -
2.3450 - // Call beforeMove first before any changes have been made to the DOM
2.3451 - callCallback(options['beforeMove'], itemsForMoveCallbacks);
2.3452 -
2.3453 - // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
2.3454 - ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
2.3455 -
2.3456 - // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
2.3457 - for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
2.3458 - // Get nodes for newly added items
2.3459 - if (!mapData.mappedNodes)
2.3460 - ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
2.3461 -
2.3462 - // Put nodes in the right place if they aren't there already
2.3463 - for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
2.3464 - if (node !== nextNode)
2.3465 - ko.virtualElements.insertAfter(domNode, node, lastNode);
2.3466 - }
2.3467 -
2.3468 - // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
2.3469 - if (!mapData.initialized && callbackAfterAddingNodes) {
2.3470 - callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
2.3471 - mapData.initialized = true;
2.3472 - }
2.3473 - }
2.3474 -
2.3475 - // If there's a beforeRemove callback, call it after reordering.
2.3476 - // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
2.3477 - // some sort of animation, which is why we first reorder the nodes that will be removed. If the
2.3478 - // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
2.3479 - // Perhaps we'll make that change in the future if this scenario becomes more common.
2.3480 - callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
2.3481 -
2.3482 - // Finally call afterMove and afterAdd callbacks
2.3483 - callCallback(options['afterMove'], itemsForMoveCallbacks);
2.3484 - callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
2.3485 -
2.3486 - // Store a copy of the array items we just considered so we can difference it next time
2.3487 - ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
2.3488 - }
2.3489 -})();
2.3490 -
2.3491 -ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
2.3492 -ko.nativeTemplateEngine = function () {
2.3493 - this['allowTemplateRewriting'] = false;
2.3494 -}
2.3495 -
2.3496 -ko.nativeTemplateEngine.prototype = new ko.templateEngine();
2.3497 -ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
2.3498 - var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
2.3499 - templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
2.3500 - templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
2.3501 -
2.3502 - if (templateNodes) {
2.3503 - return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
2.3504 - } else {
2.3505 - var templateText = templateSource['text']();
2.3506 - return ko.utils.parseHtmlFragment(templateText);
2.3507 - }
2.3508 -};
2.3509 -
2.3510 -ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
2.3511 -ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
2.3512 -
2.3513 -ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
2.3514 -(function() {
2.3515 - ko.jqueryTmplTemplateEngine = function () {
2.3516 - // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
2.3517 - // doesn't expose a version number, so we have to infer it.
2.3518 - // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
2.3519 - // which KO internally refers to as version "2", so older versions are no longer detected.
2.3520 - var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
2.3521 - if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
2.3522 - return 0;
2.3523 - // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
2.3524 - try {
2.3525 - if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
2.3526 - // Since 1.0.0pre, custom tags should append markup to an array called "__"
2.3527 - return 2; // Final version of jquery.tmpl
2.3528 - }
2.3529 - } catch(ex) { /* Apparently not the version we were looking for */ }
2.3530 -
2.3531 - return 1; // Any older version that we don't support
2.3532 - })();
2.3533 -
2.3534 - function ensureHasReferencedJQueryTemplates() {
2.3535 - if (jQueryTmplVersion < 2)
2.3536 - throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
2.3537 - }
2.3538 -
2.3539 - function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
2.3540 - return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
2.3541 - }
2.3542 -
2.3543 - this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
2.3544 - options = options || {};
2.3545 - ensureHasReferencedJQueryTemplates();
2.3546 -
2.3547 - // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
2.3548 - var precompiled = templateSource['data']('precompiled');
2.3549 - if (!precompiled) {
2.3550 - var templateText = templateSource['text']() || "";
2.3551 - // Wrap in "with($whatever.koBindingContext) { ... }"
2.3552 - templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
2.3553 -
2.3554 - precompiled = jQuery['template'](null, templateText);
2.3555 - templateSource['data']('precompiled', precompiled);
2.3556 - }
2.3557 -
2.3558 - var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
2.3559 - var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
2.3560 -
2.3561 - var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
2.3562 - resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
2.3563 -
2.3564 - jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
2.3565 - return resultNodes;
2.3566 - };
2.3567 -
2.3568 - this['createJavaScriptEvaluatorBlock'] = function(script) {
2.3569 - return "{{ko_code ((function() { return " + script + " })()) }}";
2.3570 - };
2.3571 -
2.3572 - this['addTemplate'] = function(templateName, templateMarkup) {
2.3573 - document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
2.3574 - };
2.3575 -
2.3576 - if (jQueryTmplVersion > 0) {
2.3577 - jQuery['tmpl']['tag']['ko_code'] = {
2.3578 - open: "__.push($1 || '');"
2.3579 - };
2.3580 - jQuery['tmpl']['tag']['ko_with'] = {
2.3581 - open: "with($1) {",
2.3582 - close: "} "
2.3583 - };
2.3584 - }
2.3585 - };
2.3586 -
2.3587 - ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
2.3588 -
2.3589 - // Use this one by default *only if jquery.tmpl is referenced*
2.3590 - var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
2.3591 - if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
2.3592 - ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
2.3593 -
2.3594 - ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
2.3595 -})();
2.3596 -});
2.3597 -})(window,document,navigator,window["jQuery"]);
2.3598 -})();
2.3599 \ No newline at end of file
3.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3.2 +++ b/ko4j/src/main/resources/org/netbeans/html/ko4j/knockout-3.2.0.debug.js Tue Aug 19 15:48:05 2014 +0200
3.3 @@ -0,0 +1,5299 @@
3.4 +/*!
3.5 + * Knockout JavaScript library v3.2.0
3.6 + * (c) Steven Sanderson - http://knockoutjs.com/
3.7 + * License: MIT (http://www.opensource.org/licenses/mit-license.php)
3.8 + */
3.9 +
3.10 +(function(){
3.11 +var DEBUG=true;
3.12 +(function(undefined){
3.13 + // (0, eval)('this') is a robust way of getting a reference to the global object
3.14 + // For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023
3.15 + var window = this || (0, eval)('this'),
3.16 + document = window['document'],
3.17 + navigator = window['navigator'],
3.18 + jQueryInstance = window["jQuery"],
3.19 + JSON = window["JSON"];
3.20 +(function(factory) {
3.21 + // Support three module loading scenarios
3.22 + if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
3.23 + // [1] CommonJS/Node.js
3.24 + var target = module['exports'] || exports; // module.exports is for Node.js
3.25 + factory(target, require);
3.26 + } else if (typeof define === 'function' && define['amd']) {
3.27 + // [2] AMD anonymous module
3.28 + define(['exports', 'require'], factory);
3.29 + } else {
3.30 + // [3] No module loader (plain <script> tag) - put directly in global namespace
3.31 + factory(window['ko'] = {});
3.32 + }
3.33 +}(function(koExports, require){
3.34 +// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
3.35 +// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
3.36 +var ko = typeof koExports !== 'undefined' ? koExports : {};
3.37 +// Google Closure Compiler helpers (used only to make the minified file smaller)
3.38 +ko.exportSymbol = function(koPath, object) {
3.39 + var tokens = koPath.split(".");
3.40 +
3.41 + // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
3.42 + // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
3.43 + var target = ko;
3.44 +
3.45 + for (var i = 0; i < tokens.length - 1; i++)
3.46 + target = target[tokens[i]];
3.47 + target[tokens[tokens.length - 1]] = object;
3.48 +};
3.49 +ko.exportProperty = function(owner, publicName, object) {
3.50 + owner[publicName] = object;
3.51 +};
3.52 +ko.version = "3.2.0";
3.53 +
3.54 +ko.exportSymbol('version', ko.version);
3.55 +ko.utils = (function () {
3.56 + function objectForEach(obj, action) {
3.57 + for (var prop in obj) {
3.58 + if (obj.hasOwnProperty(prop)) {
3.59 + action(prop, obj[prop]);
3.60 + }
3.61 + }
3.62 + }
3.63 +
3.64 + function extend(target, source) {
3.65 + if (source) {
3.66 + for(var prop in source) {
3.67 + if(source.hasOwnProperty(prop)) {
3.68 + target[prop] = source[prop];
3.69 + }
3.70 + }
3.71 + }
3.72 + return target;
3.73 + }
3.74 +
3.75 + function setPrototypeOf(obj, proto) {
3.76 + obj.__proto__ = proto;
3.77 + return obj;
3.78 + }
3.79 +
3.80 + var canSetPrototype = ({ __proto__: [] } instanceof Array);
3.81 +
3.82 + // 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)
3.83 + var knownEvents = {}, knownEventTypesByEventName = {};
3.84 + var keyEventTypeName = (navigator && /Firefox\/2/i.test(navigator.userAgent)) ? 'KeyboardEvent' : 'UIEvents';
3.85 + knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
3.86 + knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
3.87 + objectForEach(knownEvents, function(eventType, knownEventsForType) {
3.88 + if (knownEventsForType.length) {
3.89 + for (var i = 0, j = knownEventsForType.length; i < j; i++)
3.90 + knownEventTypesByEventName[knownEventsForType[i]] = eventType;
3.91 + }
3.92 + });
3.93 + var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
3.94 +
3.95 + // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
3.96 + // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
3.97 + // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
3.98 + // If there is a future need to detect specific versions of IE10+, we will amend this.
3.99 + var ieVersion = document && (function() {
3.100 + var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
3.101 +
3.102 + // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
3.103 + while (
3.104 + div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
3.105 + iElems[0]
3.106 + ) {}
3.107 + return version > 4 ? version : undefined;
3.108 + }());
3.109 + var isIe6 = ieVersion === 6,
3.110 + isIe7 = ieVersion === 7;
3.111 +
3.112 + function isClickOnCheckableElement(element, eventType) {
3.113 + if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
3.114 + if (eventType.toLowerCase() != "click") return false;
3.115 + var inputType = element.type;
3.116 + return (inputType == "checkbox") || (inputType == "radio");
3.117 + }
3.118 +
3.119 + return {
3.120 + fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
3.121 +
3.122 + arrayForEach: function (array, action) {
3.123 + for (var i = 0, j = array.length; i < j; i++)
3.124 + action(array[i], i);
3.125 + },
3.126 +
3.127 + arrayIndexOf: function (array, item) {
3.128 + if (typeof Array.prototype.indexOf == "function")
3.129 + return Array.prototype.indexOf.call(array, item);
3.130 + for (var i = 0, j = array.length; i < j; i++)
3.131 + if (array[i] === item)
3.132 + return i;
3.133 + return -1;
3.134 + },
3.135 +
3.136 + arrayFirst: function (array, predicate, predicateOwner) {
3.137 + for (var i = 0, j = array.length; i < j; i++)
3.138 + if (predicate.call(predicateOwner, array[i], i))
3.139 + return array[i];
3.140 + return null;
3.141 + },
3.142 +
3.143 + arrayRemoveItem: function (array, itemToRemove) {
3.144 + var index = ko.utils.arrayIndexOf(array, itemToRemove);
3.145 + if (index > 0) {
3.146 + array.splice(index, 1);
3.147 + }
3.148 + else if (index === 0) {
3.149 + array.shift();
3.150 + }
3.151 + },
3.152 +
3.153 + arrayGetDistinctValues: function (array) {
3.154 + array = array || [];
3.155 + var result = [];
3.156 + for (var i = 0, j = array.length; i < j; i++) {
3.157 + if (ko.utils.arrayIndexOf(result, array[i]) < 0)
3.158 + result.push(array[i]);
3.159 + }
3.160 + return result;
3.161 + },
3.162 +
3.163 + arrayMap: function (array, mapping) {
3.164 + array = array || [];
3.165 + var result = [];
3.166 + for (var i = 0, j = array.length; i < j; i++)
3.167 + result.push(mapping(array[i], i));
3.168 + return result;
3.169 + },
3.170 +
3.171 + arrayFilter: function (array, predicate) {
3.172 + array = array || [];
3.173 + var result = [];
3.174 + for (var i = 0, j = array.length; i < j; i++)
3.175 + if (predicate(array[i], i))
3.176 + result.push(array[i]);
3.177 + return result;
3.178 + },
3.179 +
3.180 + arrayPushAll: function (array, valuesToPush) {
3.181 + if (valuesToPush instanceof Array)
3.182 + array.push.apply(array, valuesToPush);
3.183 + else
3.184 + for (var i = 0, j = valuesToPush.length; i < j; i++)
3.185 + array.push(valuesToPush[i]);
3.186 + return array;
3.187 + },
3.188 +
3.189 + addOrRemoveItem: function(array, value, included) {
3.190 + var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.peekObservable(array), value);
3.191 + if (existingEntryIndex < 0) {
3.192 + if (included)
3.193 + array.push(value);
3.194 + } else {
3.195 + if (!included)
3.196 + array.splice(existingEntryIndex, 1);
3.197 + }
3.198 + },
3.199 +
3.200 + canSetPrototype: canSetPrototype,
3.201 +
3.202 + extend: extend,
3.203 +
3.204 + setPrototypeOf: setPrototypeOf,
3.205 +
3.206 + setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : extend,
3.207 +
3.208 + objectForEach: objectForEach,
3.209 +
3.210 + objectMap: function(source, mapping) {
3.211 + if (!source)
3.212 + return source;
3.213 + var target = {};
3.214 + for (var prop in source) {
3.215 + if (source.hasOwnProperty(prop)) {
3.216 + target[prop] = mapping(source[prop], prop, source);
3.217 + }
3.218 + }
3.219 + return target;
3.220 + },
3.221 +
3.222 + emptyDomNode: function (domNode) {
3.223 + while (domNode.firstChild) {
3.224 + ko.removeNode(domNode.firstChild);
3.225 + }
3.226 + },
3.227 +
3.228 + moveCleanedNodesToContainerElement: function(nodes) {
3.229 + // Ensure it's a real array, as we're about to reparent the nodes and
3.230 + // we don't want the underlying collection to change while we're doing that.
3.231 + var nodesArray = ko.utils.makeArray(nodes);
3.232 +
3.233 + var container = document.createElement('div');
3.234 + for (var i = 0, j = nodesArray.length; i < j; i++) {
3.235 + container.appendChild(ko.cleanNode(nodesArray[i]));
3.236 + }
3.237 + return container;
3.238 + },
3.239 +
3.240 + cloneNodes: function (nodesArray, shouldCleanNodes) {
3.241 + for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
3.242 + var clonedNode = nodesArray[i].cloneNode(true);
3.243 + newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
3.244 + }
3.245 + return newNodesArray;
3.246 + },
3.247 +
3.248 + setDomNodeChildren: function (domNode, childNodes) {
3.249 + ko.utils.emptyDomNode(domNode);
3.250 + if (childNodes) {
3.251 + for (var i = 0, j = childNodes.length; i < j; i++)
3.252 + domNode.appendChild(childNodes[i]);
3.253 + }
3.254 + },
3.255 +
3.256 + replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
3.257 + var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
3.258 + if (nodesToReplaceArray.length > 0) {
3.259 + var insertionPoint = nodesToReplaceArray[0];
3.260 + var parent = insertionPoint.parentNode;
3.261 + for (var i = 0, j = newNodesArray.length; i < j; i++)
3.262 + parent.insertBefore(newNodesArray[i], insertionPoint);
3.263 + for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
3.264 + ko.removeNode(nodesToReplaceArray[i]);
3.265 + }
3.266 + }
3.267 + },
3.268 +
3.269 + fixUpContinuousNodeArray: function(continuousNodeArray, parentNode) {
3.270 + // Before acting on a set of nodes that were previously outputted by a template function, we have to reconcile
3.271 + // them against what is in the DOM right now. It may be that some of the nodes have already been removed, or that
3.272 + // new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
3.273 + // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
3.274 + // So, this function translates the old "map" output array into its best guess of the set of current DOM nodes.
3.275 + //
3.276 + // Rules:
3.277 + // [A] Any leading nodes that have been removed should be ignored
3.278 + // These most likely correspond to memoization nodes that were already removed during binding
3.279 + // See https://github.com/SteveSanderson/knockout/pull/440
3.280 + // [B] We want to output a continuous series of nodes. So, ignore any nodes that have already been removed,
3.281 + // and include any nodes that have been inserted among the previous collection
3.282 +
3.283 + if (continuousNodeArray.length) {
3.284 + // The parent node can be a virtual element; so get the real parent node
3.285 + parentNode = (parentNode.nodeType === 8 && parentNode.parentNode) || parentNode;
3.286 +
3.287 + // Rule [A]
3.288 + while (continuousNodeArray.length && continuousNodeArray[0].parentNode !== parentNode)
3.289 + continuousNodeArray.shift();
3.290 +
3.291 + // Rule [B]
3.292 + if (continuousNodeArray.length > 1) {
3.293 + var current = continuousNodeArray[0], last = continuousNodeArray[continuousNodeArray.length - 1];
3.294 + // Replace with the actual new continuous node set
3.295 + continuousNodeArray.length = 0;
3.296 + while (current !== last) {
3.297 + continuousNodeArray.push(current);
3.298 + current = current.nextSibling;
3.299 + if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
3.300 + return;
3.301 + }
3.302 + continuousNodeArray.push(last);
3.303 + }
3.304 + }
3.305 + return continuousNodeArray;
3.306 + },
3.307 +
3.308 + setOptionNodeSelectionState: function (optionNode, isSelected) {
3.309 + // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
3.310 + if (ieVersion < 7)
3.311 + optionNode.setAttribute("selected", isSelected);
3.312 + else
3.313 + optionNode.selected = isSelected;
3.314 + },
3.315 +
3.316 + stringTrim: function (string) {
3.317 + return string === null || string === undefined ? '' :
3.318 + string.trim ?
3.319 + string.trim() :
3.320 + string.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
3.321 + },
3.322 +
3.323 + stringStartsWith: function (string, startsWith) {
3.324 + string = string || "";
3.325 + if (startsWith.length > string.length)
3.326 + return false;
3.327 + return string.substring(0, startsWith.length) === startsWith;
3.328 + },
3.329 +
3.330 + domNodeIsContainedBy: function (node, containedByNode) {
3.331 + if (node === containedByNode)
3.332 + return true;
3.333 + if (node.nodeType === 11)
3.334 + return false; // Fixes issue #1162 - can't use node.contains for document fragments on IE8
3.335 + if (containedByNode.contains)
3.336 + return containedByNode.contains(node.nodeType === 3 ? node.parentNode : node);
3.337 + if (containedByNode.compareDocumentPosition)
3.338 + return (containedByNode.compareDocumentPosition(node) & 16) == 16;
3.339 + while (node && node != containedByNode) {
3.340 + node = node.parentNode;
3.341 + }
3.342 + return !!node;
3.343 + },
3.344 +
3.345 + domNodeIsAttachedToDocument: function (node) {
3.346 + return ko.utils.domNodeIsContainedBy(node, node.ownerDocument.documentElement);
3.347 + },
3.348 +
3.349 + anyDomNodeIsAttachedToDocument: function(nodes) {
3.350 + return !!ko.utils.arrayFirst(nodes, ko.utils.domNodeIsAttachedToDocument);
3.351 + },
3.352 +
3.353 + tagNameLower: function(element) {
3.354 + // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
3.355 + // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
3.356 + // we don't need to do the .toLowerCase() as it will always be lower case anyway.
3.357 + return element && element.tagName && element.tagName.toLowerCase();
3.358 + },
3.359 +
3.360 + registerEventHandler: function (element, eventType, handler) {
3.361 + var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
3.362 + if (!mustUseAttachEvent && jQueryInstance) {
3.363 + jQueryInstance(element)['bind'](eventType, handler);
3.364 + } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
3.365 + element.addEventListener(eventType, handler, false);
3.366 + else if (typeof element.attachEvent != "undefined") {
3.367 + var attachEventHandler = function (event) { handler.call(element, event); },
3.368 + attachEventName = "on" + eventType;
3.369 + element.attachEvent(attachEventName, attachEventHandler);
3.370 +
3.371 + // IE does not dispose attachEvent handlers automatically (unlike with addEventListener)
3.372 + // so to avoid leaks, we have to remove them manually. See bug #856
3.373 + ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
3.374 + element.detachEvent(attachEventName, attachEventHandler);
3.375 + });
3.376 + } else
3.377 + throw new Error("Browser doesn't support addEventListener or attachEvent");
3.378 + },
3.379 +
3.380 + triggerEvent: function (element, eventType) {
3.381 + if (!(element && element.nodeType))
3.382 + throw new Error("element must be a DOM node when calling triggerEvent");
3.383 +
3.384 + // For click events on checkboxes and radio buttons, jQuery toggles the element checked state *after* the
3.385 + // event handler runs instead of *before*. (This was fixed in 1.9 for checkboxes but not for radio buttons.)
3.386 + // IE doesn't change the checked state when you trigger the click event using "fireEvent".
3.387 + // In both cases, we'll use the click method instead.
3.388 + var useClickWorkaround = isClickOnCheckableElement(element, eventType);
3.389 +
3.390 + if (jQueryInstance && !useClickWorkaround) {
3.391 + jQueryInstance(element)['trigger'](eventType);
3.392 + } else if (typeof document.createEvent == "function") {
3.393 + if (typeof element.dispatchEvent == "function") {
3.394 + var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
3.395 + var event = document.createEvent(eventCategory);
3.396 + event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
3.397 + element.dispatchEvent(event);
3.398 + }
3.399 + else
3.400 + throw new Error("The supplied element doesn't support dispatchEvent");
3.401 + } else if (useClickWorkaround && element.click) {
3.402 + element.click();
3.403 + } else if (typeof element.fireEvent != "undefined") {
3.404 + element.fireEvent("on" + eventType);
3.405 + } else {
3.406 + throw new Error("Browser doesn't support triggering events");
3.407 + }
3.408 + },
3.409 +
3.410 + unwrapObservable: function (value) {
3.411 + return ko.isObservable(value) ? value() : value;
3.412 + },
3.413 +
3.414 + peekObservable: function (value) {
3.415 + return ko.isObservable(value) ? value.peek() : value;
3.416 + },
3.417 +
3.418 + toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
3.419 + if (classNames) {
3.420 + var cssClassNameRegex = /\S+/g,
3.421 + currentClassNames = node.className.match(cssClassNameRegex) || [];
3.422 + ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
3.423 + ko.utils.addOrRemoveItem(currentClassNames, className, shouldHaveClass);
3.424 + });
3.425 + node.className = currentClassNames.join(" ");
3.426 + }
3.427 + },
3.428 +
3.429 + setTextContent: function(element, textContent) {
3.430 + var value = ko.utils.unwrapObservable(textContent);
3.431 + if ((value === null) || (value === undefined))
3.432 + value = "";
3.433 +
3.434 + // We need there to be exactly one child: a text node.
3.435 + // If there are no children, more than one, or if it's not a text node,
3.436 + // we'll clear everything and create a single text node.
3.437 + var innerTextNode = ko.virtualElements.firstChild(element);
3.438 + if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
3.439 + ko.virtualElements.setDomNodeChildren(element, [element.ownerDocument.createTextNode(value)]);
3.440 + } else {
3.441 + innerTextNode.data = value;
3.442 + }
3.443 +
3.444 + ko.utils.forceRefresh(element);
3.445 + },
3.446 +
3.447 + setElementName: function(element, name) {
3.448 + element.name = name;
3.449 +
3.450 + // Workaround IE 6/7 issue
3.451 + // - https://github.com/SteveSanderson/knockout/issues/197
3.452 + // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
3.453 + if (ieVersion <= 7) {
3.454 + try {
3.455 + element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
3.456 + }
3.457 + catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
3.458 + }
3.459 + },
3.460 +
3.461 + forceRefresh: function(node) {
3.462 + // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
3.463 + if (ieVersion >= 9) {
3.464 + // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
3.465 + var elem = node.nodeType == 1 ? node : node.parentNode;
3.466 + if (elem.style)
3.467 + elem.style.zoom = elem.style.zoom;
3.468 + }
3.469 + },
3.470 +
3.471 + ensureSelectElementIsRenderedCorrectly: function(selectElement) {
3.472 + // 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.
3.473 + // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
3.474 + // Also fixes IE7 and IE8 bug that causes selects to be zero width if enclosed by 'if' or 'with'. (See issue #839)
3.475 + if (ieVersion) {
3.476 + var originalWidth = selectElement.style.width;
3.477 + selectElement.style.width = 0;
3.478 + selectElement.style.width = originalWidth;
3.479 + }
3.480 + },
3.481 +
3.482 + range: function (min, max) {
3.483 + min = ko.utils.unwrapObservable(min);
3.484 + max = ko.utils.unwrapObservable(max);
3.485 + var result = [];
3.486 + for (var i = min; i <= max; i++)
3.487 + result.push(i);
3.488 + return result;
3.489 + },
3.490 +
3.491 + makeArray: function(arrayLikeObject) {
3.492 + var result = [];
3.493 + for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
3.494 + result.push(arrayLikeObject[i]);
3.495 + };
3.496 + return result;
3.497 + },
3.498 +
3.499 + isIe6 : isIe6,
3.500 + isIe7 : isIe7,
3.501 + ieVersion : ieVersion,
3.502 +
3.503 + getFormFields: function(form, fieldName) {
3.504 + var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
3.505 + var isMatchingField = (typeof fieldName == 'string')
3.506 + ? function(field) { return field.name === fieldName }
3.507 + : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
3.508 + var matches = [];
3.509 + for (var i = fields.length - 1; i >= 0; i--) {
3.510 + if (isMatchingField(fields[i]))
3.511 + matches.push(fields[i]);
3.512 + };
3.513 + return matches;
3.514 + },
3.515 +
3.516 + parseJson: function (jsonString) {
3.517 + if (typeof jsonString == "string") {
3.518 + jsonString = ko.utils.stringTrim(jsonString);
3.519 + if (jsonString) {
3.520 + if (JSON && JSON.parse) // Use native parsing where available
3.521 + return JSON.parse(jsonString);
3.522 + return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
3.523 + }
3.524 + }
3.525 + return null;
3.526 + },
3.527 +
3.528 + stringifyJson: function (data, replacer, space) { // replacer and space are optional
3.529 + if (!JSON || !JSON.stringify)
3.530 + 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");
3.531 + return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
3.532 + },
3.533 +
3.534 + postJson: function (urlOrForm, data, options) {
3.535 + options = options || {};
3.536 + var params = options['params'] || {};
3.537 + var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
3.538 + var url = urlOrForm;
3.539 +
3.540 + // If we were given a form, use its 'action' URL and pick out any requested field values
3.541 + if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
3.542 + var originalForm = urlOrForm;
3.543 + url = originalForm.action;
3.544 + for (var i = includeFields.length - 1; i >= 0; i--) {
3.545 + var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
3.546 + for (var j = fields.length - 1; j >= 0; j--)
3.547 + params[fields[j].name] = fields[j].value;
3.548 + }
3.549 + }
3.550 +
3.551 + data = ko.utils.unwrapObservable(data);
3.552 + var form = document.createElement("form");
3.553 + form.style.display = "none";
3.554 + form.action = url;
3.555 + form.method = "post";
3.556 + for (var key in data) {
3.557 + // Since 'data' this is a model object, we include all properties including those inherited from its prototype
3.558 + var input = document.createElement("input");
3.559 + input.type = "hidden";
3.560 + input.name = key;
3.561 + input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
3.562 + form.appendChild(input);
3.563 + }
3.564 + objectForEach(params, function(key, value) {
3.565 + var input = document.createElement("input");
3.566 + input.type = "hidden";
3.567 + input.name = key;
3.568 + input.value = value;
3.569 + form.appendChild(input);
3.570 + });
3.571 + document.body.appendChild(form);
3.572 + options['submitter'] ? options['submitter'](form) : form.submit();
3.573 + setTimeout(function () { form.parentNode.removeChild(form); }, 0);
3.574 + }
3.575 + }
3.576 +}());
3.577 +
3.578 +ko.exportSymbol('utils', ko.utils);
3.579 +ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
3.580 +ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
3.581 +ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
3.582 +ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
3.583 +ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
3.584 +ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
3.585 +ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
3.586 +ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
3.587 +ko.exportSymbol('utils.extend', ko.utils.extend);
3.588 +ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
3.589 +ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
3.590 +ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
3.591 +ko.exportSymbol('utils.postJson', ko.utils.postJson);
3.592 +ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
3.593 +ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
3.594 +ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
3.595 +ko.exportSymbol('utils.range', ko.utils.range);
3.596 +ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
3.597 +ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
3.598 +ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
3.599 +ko.exportSymbol('utils.objectForEach', ko.utils.objectForEach);
3.600 +ko.exportSymbol('utils.addOrRemoveItem', ko.utils.addOrRemoveItem);
3.601 +ko.exportSymbol('unwrap', ko.utils.unwrapObservable); // Convenient shorthand, because this is used so commonly
3.602 +
3.603 +if (!Function.prototype['bind']) {
3.604 + // 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)
3.605 + // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
3.606 + Function.prototype['bind'] = function (object) {
3.607 + var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
3.608 + return function () {
3.609 + return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
3.610 + };
3.611 + };
3.612 +}
3.613 +
3.614 +ko.utils.domData = new (function () {
3.615 + var uniqueId = 0;
3.616 + var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
3.617 + var dataStore = {};
3.618 +
3.619 + function getAll(node, createIfNotFound) {
3.620 + var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
3.621 + var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
3.622 + if (!hasExistingDataStore) {
3.623 + if (!createIfNotFound)
3.624 + return undefined;
3.625 + dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
3.626 + dataStore[dataStoreKey] = {};
3.627 + }
3.628 + return dataStore[dataStoreKey];
3.629 + }
3.630 +
3.631 + return {
3.632 + get: function (node, key) {
3.633 + var allDataForNode = getAll(node, false);
3.634 + return allDataForNode === undefined ? undefined : allDataForNode[key];
3.635 + },
3.636 + set: function (node, key, value) {
3.637 + if (value === undefined) {
3.638 + // Make sure we don't actually create a new domData key if we are actually deleting a value
3.639 + if (getAll(node, false) === undefined)
3.640 + return;
3.641 + }
3.642 + var allDataForNode = getAll(node, true);
3.643 + allDataForNode[key] = value;
3.644 + },
3.645 + clear: function (node) {
3.646 + var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
3.647 + if (dataStoreKey) {
3.648 + delete dataStore[dataStoreKey];
3.649 + node[dataStoreKeyExpandoPropertyName] = null;
3.650 + return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
3.651 + }
3.652 + return false;
3.653 + },
3.654 +
3.655 + nextKey: function () {
3.656 + return (uniqueId++) + dataStoreKeyExpandoPropertyName;
3.657 + }
3.658 + };
3.659 +})();
3.660 +
3.661 +ko.exportSymbol('utils.domData', ko.utils.domData);
3.662 +ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
3.663 +
3.664 +ko.utils.domNodeDisposal = new (function () {
3.665 + var domDataKey = ko.utils.domData.nextKey();
3.666 + var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
3.667 + var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
3.668 +
3.669 + function getDisposeCallbacksCollection(node, createIfNotFound) {
3.670 + var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
3.671 + if ((allDisposeCallbacks === undefined) && createIfNotFound) {
3.672 + allDisposeCallbacks = [];
3.673 + ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
3.674 + }
3.675 + return allDisposeCallbacks;
3.676 + }
3.677 + function destroyCallbacksCollection(node) {
3.678 + ko.utils.domData.set(node, domDataKey, undefined);
3.679 + }
3.680 +
3.681 + function cleanSingleNode(node) {
3.682 + // Run all the dispose callbacks
3.683 + var callbacks = getDisposeCallbacksCollection(node, false);
3.684 + if (callbacks) {
3.685 + callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
3.686 + for (var i = 0; i < callbacks.length; i++)
3.687 + callbacks[i](node);
3.688 + }
3.689 +
3.690 + // Erase the DOM data
3.691 + ko.utils.domData.clear(node);
3.692 +
3.693 + // Perform cleanup needed by external libraries (currently only jQuery, but can be extended)
3.694 + ko.utils.domNodeDisposal["cleanExternalData"](node);
3.695 +
3.696 + // Clear any immediate-child comment nodes, as these wouldn't have been found by
3.697 + // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
3.698 + if (cleanableNodeTypesWithDescendants[node.nodeType])
3.699 + cleanImmediateCommentTypeChildren(node);
3.700 + }
3.701 +
3.702 + function cleanImmediateCommentTypeChildren(nodeWithChildren) {
3.703 + var child, nextChild = nodeWithChildren.firstChild;
3.704 + while (child = nextChild) {
3.705 + nextChild = child.nextSibling;
3.706 + if (child.nodeType === 8)
3.707 + cleanSingleNode(child);
3.708 + }
3.709 + }
3.710 +
3.711 + return {
3.712 + addDisposeCallback : function(node, callback) {
3.713 + if (typeof callback != "function")
3.714 + throw new Error("Callback must be a function");
3.715 + getDisposeCallbacksCollection(node, true).push(callback);
3.716 + },
3.717 +
3.718 + removeDisposeCallback : function(node, callback) {
3.719 + var callbacksCollection = getDisposeCallbacksCollection(node, false);
3.720 + if (callbacksCollection) {
3.721 + ko.utils.arrayRemoveItem(callbacksCollection, callback);
3.722 + if (callbacksCollection.length == 0)
3.723 + destroyCallbacksCollection(node);
3.724 + }
3.725 + },
3.726 +
3.727 + cleanNode : function(node) {
3.728 + // First clean this node, where applicable
3.729 + if (cleanableNodeTypes[node.nodeType]) {
3.730 + cleanSingleNode(node);
3.731 +
3.732 + // ... then its descendants, where applicable
3.733 + if (cleanableNodeTypesWithDescendants[node.nodeType]) {
3.734 + // Clone the descendants list in case it changes during iteration
3.735 + var descendants = [];
3.736 + ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
3.737 + for (var i = 0, j = descendants.length; i < j; i++)
3.738 + cleanSingleNode(descendants[i]);
3.739 + }
3.740 + }
3.741 + return node;
3.742 + },
3.743 +
3.744 + removeNode : function(node) {
3.745 + ko.cleanNode(node);
3.746 + if (node.parentNode)
3.747 + node.parentNode.removeChild(node);
3.748 + },
3.749 +
3.750 + "cleanExternalData" : function (node) {
3.751 + // Special support for jQuery here because it's so commonly used.
3.752 + // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
3.753 + // so notify it to tear down any resources associated with the node & descendants here.
3.754 + if (jQueryInstance && (typeof jQueryInstance['cleanData'] == "function"))
3.755 + jQueryInstance['cleanData']([node]);
3.756 + }
3.757 + }
3.758 +})();
3.759 +ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
3.760 +ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
3.761 +ko.exportSymbol('cleanNode', ko.cleanNode);
3.762 +ko.exportSymbol('removeNode', ko.removeNode);
3.763 +ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
3.764 +ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
3.765 +ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
3.766 +(function () {
3.767 + var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
3.768 +
3.769 + function simpleHtmlParse(html) {
3.770 + // Based on jQuery's "clean" function, but only accounting for table-related elements.
3.771 + // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
3.772 +
3.773 + // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
3.774 + // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
3.775 + // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
3.776 + // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
3.777 +
3.778 + // Trim whitespace, otherwise indexOf won't work as expected
3.779 + var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
3.780 +
3.781 + // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
3.782 + var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
3.783 + !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
3.784 + (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
3.785 + /* anything else */ [0, "", ""];
3.786 +
3.787 + // Go to html and back, then peel off extra wrappers
3.788 + // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
3.789 + var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
3.790 + if (typeof window['innerShiv'] == "function") {
3.791 + div.appendChild(window['innerShiv'](markup));
3.792 + } else {
3.793 + div.innerHTML = markup;
3.794 + }
3.795 +
3.796 + // Move to the right depth
3.797 + while (wrap[0]--)
3.798 + div = div.lastChild;
3.799 +
3.800 + return ko.utils.makeArray(div.lastChild.childNodes);
3.801 + }
3.802 +
3.803 + function jQueryHtmlParse(html) {
3.804 + // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
3.805 + if (jQueryInstance['parseHTML']) {
3.806 + return jQueryInstance['parseHTML'](html) || []; // Ensure we always return an array and never null
3.807 + } else {
3.808 + // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
3.809 + var elems = jQueryInstance['clean']([html]);
3.810 +
3.811 + // 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.
3.812 + // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
3.813 + // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
3.814 + if (elems && elems[0]) {
3.815 + // Find the top-most parent element that's a direct child of a document fragment
3.816 + var elem = elems[0];
3.817 + while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
3.818 + elem = elem.parentNode;
3.819 + // ... then detach it
3.820 + if (elem.parentNode)
3.821 + elem.parentNode.removeChild(elem);
3.822 + }
3.823 +
3.824 + return elems;
3.825 + }
3.826 + }
3.827 +
3.828 + ko.utils.parseHtmlFragment = function(html) {
3.829 + return jQueryInstance ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
3.830 + : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
3.831 + };
3.832 +
3.833 + ko.utils.setHtml = function(node, html) {
3.834 + ko.utils.emptyDomNode(node);
3.835 +
3.836 + // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
3.837 + html = ko.utils.unwrapObservable(html);
3.838 +
3.839 + if ((html !== null) && (html !== undefined)) {
3.840 + if (typeof html != 'string')
3.841 + html = html.toString();
3.842 +
3.843 + // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
3.844 + // for example <tr> elements which are not normally allowed to exist on their own.
3.845 + // If you've referenced jQuery we'll use that rather than duplicating its code.
3.846 + if (jQueryInstance) {
3.847 + jQueryInstance(node)['html'](html);
3.848 + } else {
3.849 + // ... otherwise, use KO's own parsing logic.
3.850 + var parsedNodes = ko.utils.parseHtmlFragment(html);
3.851 + for (var i = 0; i < parsedNodes.length; i++)
3.852 + node.appendChild(parsedNodes[i]);
3.853 + }
3.854 + }
3.855 + };
3.856 +})();
3.857 +
3.858 +ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
3.859 +ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
3.860 +
3.861 +ko.memoization = (function () {
3.862 + var memos = {};
3.863 +
3.864 + function randomMax8HexChars() {
3.865 + return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
3.866 + }
3.867 + function generateRandomId() {
3.868 + return randomMax8HexChars() + randomMax8HexChars();
3.869 + }
3.870 + function findMemoNodes(rootNode, appendToArray) {
3.871 + if (!rootNode)
3.872 + return;
3.873 + if (rootNode.nodeType == 8) {
3.874 + var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
3.875 + if (memoId != null)
3.876 + appendToArray.push({ domNode: rootNode, memoId: memoId });
3.877 + } else if (rootNode.nodeType == 1) {
3.878 + for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
3.879 + findMemoNodes(childNodes[i], appendToArray);
3.880 + }
3.881 + }
3.882 +
3.883 + return {
3.884 + memoize: function (callback) {
3.885 + if (typeof callback != "function")
3.886 + throw new Error("You can only pass a function to ko.memoization.memoize()");
3.887 + var memoId = generateRandomId();
3.888 + memos[memoId] = callback;
3.889 + return "<!--[ko_memo:" + memoId + "]-->";
3.890 + },
3.891 +
3.892 + unmemoize: function (memoId, callbackParams) {
3.893 + var callback = memos[memoId];
3.894 + if (callback === undefined)
3.895 + throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
3.896 + try {
3.897 + callback.apply(null, callbackParams || []);
3.898 + return true;
3.899 + }
3.900 + finally { delete memos[memoId]; }
3.901 + },
3.902 +
3.903 + unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
3.904 + var memos = [];
3.905 + findMemoNodes(domNode, memos);
3.906 + for (var i = 0, j = memos.length; i < j; i++) {
3.907 + var node = memos[i].domNode;
3.908 + var combinedParams = [node];
3.909 + if (extraCallbackParamsArray)
3.910 + ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
3.911 + ko.memoization.unmemoize(memos[i].memoId, combinedParams);
3.912 + node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
3.913 + if (node.parentNode)
3.914 + 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)
3.915 + }
3.916 + },
3.917 +
3.918 + parseMemoText: function (memoText) {
3.919 + var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
3.920 + return match ? match[1] : null;
3.921 + }
3.922 + };
3.923 +})();
3.924 +
3.925 +ko.exportSymbol('memoization', ko.memoization);
3.926 +ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
3.927 +ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
3.928 +ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
3.929 +ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
3.930 +ko.extenders = {
3.931 + 'throttle': function(target, timeout) {
3.932 + // Throttling means two things:
3.933 +
3.934 + // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
3.935 + // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
3.936 + target['throttleEvaluation'] = timeout;
3.937 +
3.938 + // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
3.939 + // so the target cannot change value synchronously or faster than a certain rate
3.940 + var writeTimeoutInstance = null;
3.941 + return ko.dependentObservable({
3.942 + 'read': target,
3.943 + 'write': function(value) {
3.944 + clearTimeout(writeTimeoutInstance);
3.945 + writeTimeoutInstance = setTimeout(function() {
3.946 + target(value);
3.947 + }, timeout);
3.948 + }
3.949 + });
3.950 + },
3.951 +
3.952 + 'rateLimit': function(target, options) {
3.953 + var timeout, method, limitFunction;
3.954 +
3.955 + if (typeof options == 'number') {
3.956 + timeout = options;
3.957 + } else {
3.958 + timeout = options['timeout'];
3.959 + method = options['method'];
3.960 + }
3.961 +
3.962 + limitFunction = method == 'notifyWhenChangesStop' ? debounce : throttle;
3.963 + target.limit(function(callback) {
3.964 + return limitFunction(callback, timeout);
3.965 + });
3.966 + },
3.967 +
3.968 + 'notify': function(target, notifyWhen) {
3.969 + target["equalityComparer"] = notifyWhen == "always" ?
3.970 + null : // null equalityComparer means to always notify
3.971 + valuesArePrimitiveAndEqual;
3.972 + }
3.973 +};
3.974 +
3.975 +var primitiveTypes = { 'undefined':1, 'boolean':1, 'number':1, 'string':1 };
3.976 +function valuesArePrimitiveAndEqual(a, b) {
3.977 + var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
3.978 + return oldValueIsPrimitive ? (a === b) : false;
3.979 +}
3.980 +
3.981 +function throttle(callback, timeout) {
3.982 + var timeoutInstance;
3.983 + return function () {
3.984 + if (!timeoutInstance) {
3.985 + timeoutInstance = setTimeout(function() {
3.986 + timeoutInstance = undefined;
3.987 + callback();
3.988 + }, timeout);
3.989 + }
3.990 + };
3.991 +}
3.992 +
3.993 +function debounce(callback, timeout) {
3.994 + var timeoutInstance;
3.995 + return function () {
3.996 + clearTimeout(timeoutInstance);
3.997 + timeoutInstance = setTimeout(callback, timeout);
3.998 + };
3.999 +}
3.1000 +
3.1001 +function applyExtenders(requestedExtenders) {
3.1002 + var target = this;
3.1003 + if (requestedExtenders) {
3.1004 + ko.utils.objectForEach(requestedExtenders, function(key, value) {
3.1005 + var extenderHandler = ko.extenders[key];
3.1006 + if (typeof extenderHandler == 'function') {
3.1007 + target = extenderHandler(target, value) || target;
3.1008 + }
3.1009 + });
3.1010 + }
3.1011 + return target;
3.1012 +}
3.1013 +
3.1014 +ko.exportSymbol('extenders', ko.extenders);
3.1015 +
3.1016 +ko.subscription = function (target, callback, disposeCallback) {
3.1017 + this.target = target;
3.1018 + this.callback = callback;
3.1019 + this.disposeCallback = disposeCallback;
3.1020 + this.isDisposed = false;
3.1021 + ko.exportProperty(this, 'dispose', this.dispose);
3.1022 +};
3.1023 +ko.subscription.prototype.dispose = function () {
3.1024 + this.isDisposed = true;
3.1025 + this.disposeCallback();
3.1026 +};
3.1027 +
3.1028 +ko.subscribable = function () {
3.1029 + ko.utils.setPrototypeOfOrExtend(this, ko.subscribable['fn']);
3.1030 + this._subscriptions = {};
3.1031 +}
3.1032 +
3.1033 +var defaultEvent = "change";
3.1034 +
3.1035 +var ko_subscribable_fn = {
3.1036 + subscribe: function (callback, callbackTarget, event) {
3.1037 + var self = this;
3.1038 +
3.1039 + event = event || defaultEvent;
3.1040 + var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
3.1041 +
3.1042 + var subscription = new ko.subscription(self, boundCallback, function () {
3.1043 + ko.utils.arrayRemoveItem(self._subscriptions[event], subscription);
3.1044 + if (self.afterSubscriptionRemove)
3.1045 + self.afterSubscriptionRemove(event);
3.1046 + });
3.1047 +
3.1048 + if (self.beforeSubscriptionAdd)
3.1049 + self.beforeSubscriptionAdd(event);
3.1050 +
3.1051 + if (!self._subscriptions[event])
3.1052 + self._subscriptions[event] = [];
3.1053 + self._subscriptions[event].push(subscription);
3.1054 +
3.1055 + return subscription;
3.1056 + },
3.1057 +
3.1058 + "notifySubscribers": function (valueToNotify, event) {
3.1059 + event = event || defaultEvent;
3.1060 + if (this.hasSubscriptionsForEvent(event)) {
3.1061 + try {
3.1062 + ko.dependencyDetection.begin(); // Begin suppressing dependency detection (by setting the top frame to undefined)
3.1063 + for (var a = this._subscriptions[event].slice(0), i = 0, subscription; subscription = a[i]; ++i) {
3.1064 + // In case a subscription was disposed during the arrayForEach cycle, check
3.1065 + // for isDisposed on each subscription before invoking its callback
3.1066 + if (!subscription.isDisposed)
3.1067 + subscription.callback(valueToNotify);
3.1068 + }
3.1069 + } finally {
3.1070 + ko.dependencyDetection.end(); // End suppressing dependency detection
3.1071 + }
3.1072 + }
3.1073 + },
3.1074 +
3.1075 + limit: function(limitFunction) {
3.1076 + var self = this, selfIsObservable = ko.isObservable(self),
3.1077 + isPending, previousValue, pendingValue, beforeChange = 'beforeChange';
3.1078 +
3.1079 + if (!self._origNotifySubscribers) {
3.1080 + self._origNotifySubscribers = self["notifySubscribers"];
3.1081 + self["notifySubscribers"] = function(value, event) {
3.1082 + if (!event || event === defaultEvent) {
3.1083 + self._rateLimitedChange(value);
3.1084 + } else if (event === beforeChange) {
3.1085 + self._rateLimitedBeforeChange(value);
3.1086 + } else {
3.1087 + self._origNotifySubscribers(value, event);
3.1088 + }
3.1089 + };
3.1090 + }
3.1091 +
3.1092 + var finish = limitFunction(function() {
3.1093 + // If an observable provided a reference to itself, access it to get the latest value.
3.1094 + // This allows computed observables to delay calculating their value until needed.
3.1095 + if (selfIsObservable && pendingValue === self) {
3.1096 + pendingValue = self();
3.1097 + }
3.1098 + isPending = false;
3.1099 + if (self.isDifferent(previousValue, pendingValue)) {
3.1100 + self._origNotifySubscribers(previousValue = pendingValue);
3.1101 + }
3.1102 + });
3.1103 +
3.1104 + self._rateLimitedChange = function(value) {
3.1105 + isPending = true;
3.1106 + pendingValue = value;
3.1107 + finish();
3.1108 + };
3.1109 + self._rateLimitedBeforeChange = function(value) {
3.1110 + if (!isPending) {
3.1111 + previousValue = value;
3.1112 + self._origNotifySubscribers(value, beforeChange);
3.1113 + }
3.1114 + };
3.1115 + },
3.1116 +
3.1117 + hasSubscriptionsForEvent: function(event) {
3.1118 + return this._subscriptions[event] && this._subscriptions[event].length;
3.1119 + },
3.1120 +
3.1121 + getSubscriptionsCount: function () {
3.1122 + var total = 0;
3.1123 + ko.utils.objectForEach(this._subscriptions, function(eventName, subscriptions) {
3.1124 + total += subscriptions.length;
3.1125 + });
3.1126 + return total;
3.1127 + },
3.1128 +
3.1129 + isDifferent: function(oldValue, newValue) {
3.1130 + return !this['equalityComparer'] || !this['equalityComparer'](oldValue, newValue);
3.1131 + },
3.1132 +
3.1133 + extend: applyExtenders
3.1134 +};
3.1135 +
3.1136 +ko.exportProperty(ko_subscribable_fn, 'subscribe', ko_subscribable_fn.subscribe);
3.1137 +ko.exportProperty(ko_subscribable_fn, 'extend', ko_subscribable_fn.extend);
3.1138 +ko.exportProperty(ko_subscribable_fn, 'getSubscriptionsCount', ko_subscribable_fn.getSubscriptionsCount);
3.1139 +
3.1140 +// For browsers that support proto assignment, we overwrite the prototype of each
3.1141 +// observable instance. Since observables are functions, we need Function.prototype
3.1142 +// to still be in the prototype chain.
3.1143 +if (ko.utils.canSetPrototype) {
3.1144 + ko.utils.setPrototypeOf(ko_subscribable_fn, Function.prototype);
3.1145 +}
3.1146 +
3.1147 +ko.subscribable['fn'] = ko_subscribable_fn;
3.1148 +
3.1149 +
3.1150 +ko.isSubscribable = function (instance) {
3.1151 + return instance != null && typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
3.1152 +};
3.1153 +
3.1154 +ko.exportSymbol('subscribable', ko.subscribable);
3.1155 +ko.exportSymbol('isSubscribable', ko.isSubscribable);
3.1156 +
3.1157 +ko.computedContext = ko.dependencyDetection = (function () {
3.1158 + var outerFrames = [],
3.1159 + currentFrame,
3.1160 + lastId = 0;
3.1161 +
3.1162 + // Return a unique ID that can be assigned to an observable for dependency tracking.
3.1163 + // Theoretically, you could eventually overflow the number storage size, resulting
3.1164 + // in duplicate IDs. But in JavaScript, the largest exact integral value is 2^53
3.1165 + // or 9,007,199,254,740,992. If you created 1,000,000 IDs per second, it would
3.1166 + // take over 285 years to reach that number.
3.1167 + // Reference http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html
3.1168 + function getId() {
3.1169 + return ++lastId;
3.1170 + }
3.1171 +
3.1172 + function begin(options) {
3.1173 + outerFrames.push(currentFrame);
3.1174 + currentFrame = options;
3.1175 + }
3.1176 +
3.1177 + function end() {
3.1178 + currentFrame = outerFrames.pop();
3.1179 + }
3.1180 +
3.1181 + return {
3.1182 + begin: begin,
3.1183 +
3.1184 + end: end,
3.1185 +
3.1186 + registerDependency: function (subscribable) {
3.1187 + if (currentFrame) {
3.1188 + if (!ko.isSubscribable(subscribable))
3.1189 + throw new Error("Only subscribable things can act as dependencies");
3.1190 + currentFrame.callback(subscribable, subscribable._id || (subscribable._id = getId()));
3.1191 + }
3.1192 + },
3.1193 +
3.1194 + ignore: function (callback, callbackTarget, callbackArgs) {
3.1195 + try {
3.1196 + begin();
3.1197 + return callback.apply(callbackTarget, callbackArgs || []);
3.1198 + } finally {
3.1199 + end();
3.1200 + }
3.1201 + },
3.1202 +
3.1203 + getDependenciesCount: function () {
3.1204 + if (currentFrame)
3.1205 + return currentFrame.computed.getDependenciesCount();
3.1206 + },
3.1207 +
3.1208 + isInitial: function() {
3.1209 + if (currentFrame)
3.1210 + return currentFrame.isInitial;
3.1211 + }
3.1212 + };
3.1213 +})();
3.1214 +
3.1215 +ko.exportSymbol('computedContext', ko.computedContext);
3.1216 +ko.exportSymbol('computedContext.getDependenciesCount', ko.computedContext.getDependenciesCount);
3.1217 +ko.exportSymbol('computedContext.isInitial', ko.computedContext.isInitial);
3.1218 +ko.exportSymbol('computedContext.isSleeping', ko.computedContext.isSleeping);
3.1219 +ko.observable = function (initialValue) {
3.1220 + var _latestValue = initialValue;
3.1221 +
3.1222 + function observable() {
3.1223 + if (arguments.length > 0) {
3.1224 + // Write
3.1225 +
3.1226 + // Ignore writes if the value hasn't changed
3.1227 + if (observable.isDifferent(_latestValue, arguments[0])) {
3.1228 + observable.valueWillMutate();
3.1229 + _latestValue = arguments[0];
3.1230 + if (DEBUG) observable._latestValue = _latestValue;
3.1231 + observable.valueHasMutated();
3.1232 + }
3.1233 + return this; // Permits chained assignments
3.1234 + }
3.1235 + else {
3.1236 + // Read
3.1237 + ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
3.1238 + return _latestValue;
3.1239 + }
3.1240 + }
3.1241 + ko.subscribable.call(observable);
3.1242 + ko.utils.setPrototypeOfOrExtend(observable, ko.observable['fn']);
3.1243 +
3.1244 + if (DEBUG) observable._latestValue = _latestValue;
3.1245 + observable.peek = function() { return _latestValue };
3.1246 + observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
3.1247 + observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
3.1248 +
3.1249 + ko.exportProperty(observable, 'peek', observable.peek);
3.1250 + ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
3.1251 + ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
3.1252 +
3.1253 + return observable;
3.1254 +}
3.1255 +
3.1256 +ko.observable['fn'] = {
3.1257 + "equalityComparer": valuesArePrimitiveAndEqual
3.1258 +};
3.1259 +
3.1260 +var protoProperty = ko.observable.protoProperty = "__ko_proto__";
3.1261 +ko.observable['fn'][protoProperty] = ko.observable;
3.1262 +
3.1263 +// Note that for browsers that don't support proto assignment, the
3.1264 +// inheritance chain is created manually in the ko.observable constructor
3.1265 +if (ko.utils.canSetPrototype) {
3.1266 + ko.utils.setPrototypeOf(ko.observable['fn'], ko.subscribable['fn']);
3.1267 +}
3.1268 +
3.1269 +ko.hasPrototype = function(instance, prototype) {
3.1270 + if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
3.1271 + if (instance[protoProperty] === prototype) return true;
3.1272 + return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
3.1273 +};
3.1274 +
3.1275 +ko.isObservable = function (instance) {
3.1276 + return ko.hasPrototype(instance, ko.observable);
3.1277 +}
3.1278 +ko.isWriteableObservable = function (instance) {
3.1279 + // Observable
3.1280 + if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
3.1281 + return true;
3.1282 + // Writeable dependent observable
3.1283 + if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
3.1284 + return true;
3.1285 + // Anything else
3.1286 + return false;
3.1287 +}
3.1288 +
3.1289 +
3.1290 +ko.exportSymbol('observable', ko.observable);
3.1291 +ko.exportSymbol('isObservable', ko.isObservable);
3.1292 +ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
3.1293 +ko.exportSymbol('isWritableObservable', ko.isWriteableObservable);
3.1294 +ko.observableArray = function (initialValues) {
3.1295 + initialValues = initialValues || [];
3.1296 +
3.1297 + if (typeof initialValues != 'object' || !('length' in initialValues))
3.1298 + throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
3.1299 +
3.1300 + var result = ko.observable(initialValues);
3.1301 + ko.utils.setPrototypeOfOrExtend(result, ko.observableArray['fn']);
3.1302 + return result.extend({'trackArrayChanges':true});
3.1303 +};
3.1304 +
3.1305 +ko.observableArray['fn'] = {
3.1306 + 'remove': function (valueOrPredicate) {
3.1307 + var underlyingArray = this.peek();
3.1308 + var removedValues = [];
3.1309 + var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
3.1310 + for (var i = 0; i < underlyingArray.length; i++) {
3.1311 + var value = underlyingArray[i];
3.1312 + if (predicate(value)) {
3.1313 + if (removedValues.length === 0) {
3.1314 + this.valueWillMutate();
3.1315 + }
3.1316 + removedValues.push(value);
3.1317 + underlyingArray.splice(i, 1);
3.1318 + i--;
3.1319 + }
3.1320 + }
3.1321 + if (removedValues.length) {
3.1322 + this.valueHasMutated();
3.1323 + }
3.1324 + return removedValues;
3.1325 + },
3.1326 +
3.1327 + 'removeAll': function (arrayOfValues) {
3.1328 + // If you passed zero args, we remove everything
3.1329 + if (arrayOfValues === undefined) {
3.1330 + var underlyingArray = this.peek();
3.1331 + var allValues = underlyingArray.slice(0);
3.1332 + this.valueWillMutate();
3.1333 + underlyingArray.splice(0, underlyingArray.length);
3.1334 + this.valueHasMutated();
3.1335 + return allValues;
3.1336 + }
3.1337 + // If you passed an arg, we interpret it as an array of entries to remove
3.1338 + if (!arrayOfValues)
3.1339 + return [];
3.1340 + return this['remove'](function (value) {
3.1341 + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
3.1342 + });
3.1343 + },
3.1344 +
3.1345 + 'destroy': function (valueOrPredicate) {
3.1346 + var underlyingArray = this.peek();
3.1347 + var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
3.1348 + this.valueWillMutate();
3.1349 + for (var i = underlyingArray.length - 1; i >= 0; i--) {
3.1350 + var value = underlyingArray[i];
3.1351 + if (predicate(value))
3.1352 + underlyingArray[i]["_destroy"] = true;
3.1353 + }
3.1354 + this.valueHasMutated();
3.1355 + },
3.1356 +
3.1357 + 'destroyAll': function (arrayOfValues) {
3.1358 + // If you passed zero args, we destroy everything
3.1359 + if (arrayOfValues === undefined)
3.1360 + return this['destroy'](function() { return true });
3.1361 +
3.1362 + // If you passed an arg, we interpret it as an array of entries to destroy
3.1363 + if (!arrayOfValues)
3.1364 + return [];
3.1365 + return this['destroy'](function (value) {
3.1366 + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
3.1367 + });
3.1368 + },
3.1369 +
3.1370 + 'indexOf': function (item) {
3.1371 + var underlyingArray = this();
3.1372 + return ko.utils.arrayIndexOf(underlyingArray, item);
3.1373 + },
3.1374 +
3.1375 + 'replace': function(oldItem, newItem) {
3.1376 + var index = this['indexOf'](oldItem);
3.1377 + if (index >= 0) {
3.1378 + this.valueWillMutate();
3.1379 + this.peek()[index] = newItem;
3.1380 + this.valueHasMutated();
3.1381 + }
3.1382 + }
3.1383 +};
3.1384 +
3.1385 +// Populate ko.observableArray.fn with read/write functions from native arrays
3.1386 +// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
3.1387 +// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
3.1388 +ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
3.1389 + ko.observableArray['fn'][methodName] = function () {
3.1390 + // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
3.1391 + // (for consistency with mutating regular observables)
3.1392 + var underlyingArray = this.peek();
3.1393 + this.valueWillMutate();
3.1394 + this.cacheDiffForKnownOperation(underlyingArray, methodName, arguments);
3.1395 + var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
3.1396 + this.valueHasMutated();
3.1397 + return methodCallResult;
3.1398 + };
3.1399 +});
3.1400 +
3.1401 +// Populate ko.observableArray.fn with read-only functions from native arrays
3.1402 +ko.utils.arrayForEach(["slice"], function (methodName) {
3.1403 + ko.observableArray['fn'][methodName] = function () {
3.1404 + var underlyingArray = this();
3.1405 + return underlyingArray[methodName].apply(underlyingArray, arguments);
3.1406 + };
3.1407 +});
3.1408 +
3.1409 +// Note that for browsers that don't support proto assignment, the
3.1410 +// inheritance chain is created manually in the ko.observableArray constructor
3.1411 +if (ko.utils.canSetPrototype) {
3.1412 + ko.utils.setPrototypeOf(ko.observableArray['fn'], ko.observable['fn']);
3.1413 +}
3.1414 +
3.1415 +ko.exportSymbol('observableArray', ko.observableArray);
3.1416 +var arrayChangeEventName = 'arrayChange';
3.1417 +ko.extenders['trackArrayChanges'] = function(target) {
3.1418 + // Only modify the target observable once
3.1419 + if (target.cacheDiffForKnownOperation) {
3.1420 + return;
3.1421 + }
3.1422 + var trackingChanges = false,
3.1423 + cachedDiff = null,
3.1424 + pendingNotifications = 0,
3.1425 + underlyingSubscribeFunction = target.subscribe;
3.1426 +
3.1427 + // Intercept "subscribe" calls, and for array change events, ensure change tracking is enabled
3.1428 + target.subscribe = target['subscribe'] = function(callback, callbackTarget, event) {
3.1429 + if (event === arrayChangeEventName) {
3.1430 + trackChanges();
3.1431 + }
3.1432 + return underlyingSubscribeFunction.apply(this, arguments);
3.1433 + };
3.1434 +
3.1435 + function trackChanges() {
3.1436 + // Calling 'trackChanges' multiple times is the same as calling it once
3.1437 + if (trackingChanges) {
3.1438 + return;
3.1439 + }
3.1440 +
3.1441 + trackingChanges = true;
3.1442 +
3.1443 + // Intercept "notifySubscribers" to track how many times it was called.
3.1444 + var underlyingNotifySubscribersFunction = target['notifySubscribers'];
3.1445 + target['notifySubscribers'] = function(valueToNotify, event) {
3.1446 + if (!event || event === defaultEvent) {
3.1447 + ++pendingNotifications;
3.1448 + }
3.1449 + return underlyingNotifySubscribersFunction.apply(this, arguments);
3.1450 + };
3.1451 +
3.1452 + // Each time the array changes value, capture a clone so that on the next
3.1453 + // change it's possible to produce a diff
3.1454 + var previousContents = [].concat(target.peek() || []);
3.1455 + cachedDiff = null;
3.1456 + target.subscribe(function(currentContents) {
3.1457 + // Make a copy of the current contents and ensure it's an array
3.1458 + currentContents = [].concat(currentContents || []);
3.1459 +
3.1460 + // Compute the diff and issue notifications, but only if someone is listening
3.1461 + if (target.hasSubscriptionsForEvent(arrayChangeEventName)) {
3.1462 + var changes = getChanges(previousContents, currentContents);
3.1463 + if (changes.length) {
3.1464 + target['notifySubscribers'](changes, arrayChangeEventName);
3.1465 + }
3.1466 + }
3.1467 +
3.1468 + // Eliminate references to the old, removed items, so they can be GCed
3.1469 + previousContents = currentContents;
3.1470 + cachedDiff = null;
3.1471 + pendingNotifications = 0;
3.1472 + });
3.1473 + }
3.1474 +
3.1475 + function getChanges(previousContents, currentContents) {
3.1476 + // We try to re-use cached diffs.
3.1477 + // The scenarios where pendingNotifications > 1 are when using rate-limiting or the Deferred Updates
3.1478 + // plugin, which without this check would not be compatible with arrayChange notifications. Normally,
3.1479 + // notifications are issued immediately so we wouldn't be queueing up more than one.
3.1480 + if (!cachedDiff || pendingNotifications > 1) {
3.1481 + cachedDiff = ko.utils.compareArrays(previousContents, currentContents, { 'sparse': true });
3.1482 + }
3.1483 +
3.1484 + return cachedDiff;
3.1485 + }
3.1486 +
3.1487 + target.cacheDiffForKnownOperation = function(rawArray, operationName, args) {
3.1488 + // Only run if we're currently tracking changes for this observable array
3.1489 + // and there aren't any pending deferred notifications.
3.1490 + if (!trackingChanges || pendingNotifications) {
3.1491 + return;
3.1492 + }
3.1493 + var diff = [],
3.1494 + arrayLength = rawArray.length,
3.1495 + argsLength = args.length,
3.1496 + offset = 0;
3.1497 +
3.1498 + function pushDiff(status, value, index) {
3.1499 + return diff[diff.length] = { 'status': status, 'value': value, 'index': index };
3.1500 + }
3.1501 + switch (operationName) {
3.1502 + case 'push':
3.1503 + offset = arrayLength;
3.1504 + case 'unshift':
3.1505 + for (var index = 0; index < argsLength; index++) {
3.1506 + pushDiff('added', args[index], offset + index);
3.1507 + }
3.1508 + break;
3.1509 +
3.1510 + case 'pop':
3.1511 + offset = arrayLength - 1;
3.1512 + case 'shift':
3.1513 + if (arrayLength) {
3.1514 + pushDiff('deleted', rawArray[offset], offset);
3.1515 + }
3.1516 + break;
3.1517 +
3.1518 + case 'splice':
3.1519 + // Negative start index means 'from end of array'. After that we clamp to [0...arrayLength].
3.1520 + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
3.1521 + var startIndex = Math.min(Math.max(0, args[0] < 0 ? arrayLength + args[0] : args[0]), arrayLength),
3.1522 + endDeleteIndex = argsLength === 1 ? arrayLength : Math.min(startIndex + (args[1] || 0), arrayLength),
3.1523 + endAddIndex = startIndex + argsLength - 2,
3.1524 + endIndex = Math.max(endDeleteIndex, endAddIndex),
3.1525 + additions = [], deletions = [];
3.1526 + for (var index = startIndex, argsIndex = 2; index < endIndex; ++index, ++argsIndex) {
3.1527 + if (index < endDeleteIndex)
3.1528 + deletions.push(pushDiff('deleted', rawArray[index], index));
3.1529 + if (index < endAddIndex)
3.1530 + additions.push(pushDiff('added', args[argsIndex], index));
3.1531 + }
3.1532 + ko.utils.findMovesInArrayComparison(deletions, additions);
3.1533 + break;
3.1534 +
3.1535 + default:
3.1536 + return;
3.1537 + }
3.1538 + cachedDiff = diff;
3.1539 + };
3.1540 +};
3.1541 +ko.computed = ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
3.1542 + var _latestValue,
3.1543 + _needsEvaluation = true,
3.1544 + _isBeingEvaluated = false,
3.1545 + _suppressDisposalUntilDisposeWhenReturnsFalse = false,
3.1546 + _isDisposed = false,
3.1547 + readFunction = evaluatorFunctionOrOptions,
3.1548 + pure = false,
3.1549 + isSleeping = false;
3.1550 +
3.1551 + if (readFunction && typeof readFunction == "object") {
3.1552 + // Single-parameter syntax - everything is on this "options" param
3.1553 + options = readFunction;
3.1554 + readFunction = options["read"];
3.1555 + } else {
3.1556 + // Multi-parameter syntax - construct the options according to the params passed
3.1557 + options = options || {};
3.1558 + if (!readFunction)
3.1559 + readFunction = options["read"];
3.1560 + }
3.1561 + if (typeof readFunction != "function")
3.1562 + throw new Error("Pass a function that returns the value of the ko.computed");
3.1563 +
3.1564 + function addSubscriptionToDependency(subscribable, id) {
3.1565 + if (!_subscriptionsToDependencies[id]) {
3.1566 + _subscriptionsToDependencies[id] = subscribable.subscribe(evaluatePossiblyAsync);
3.1567 + ++_dependenciesCount;
3.1568 + }
3.1569 + }
3.1570 +
3.1571 + function disposeAllSubscriptionsToDependencies() {
3.1572 + ko.utils.objectForEach(_subscriptionsToDependencies, function (id, subscription) {
3.1573 + subscription.dispose();
3.1574 + });
3.1575 + _subscriptionsToDependencies = {};
3.1576 + }
3.1577 +
3.1578 + function disposeComputed() {
3.1579 + disposeAllSubscriptionsToDependencies();
3.1580 + _dependenciesCount = 0;
3.1581 + _isDisposed = true;
3.1582 + _needsEvaluation = false;
3.1583 + }
3.1584 +
3.1585 + function evaluatePossiblyAsync() {
3.1586 + var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
3.1587 + if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
3.1588 + clearTimeout(evaluationTimeoutInstance);
3.1589 + evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
3.1590 + } else if (dependentObservable._evalRateLimited) {
3.1591 + dependentObservable._evalRateLimited();
3.1592 + } else {
3.1593 + evaluateImmediate();
3.1594 + }
3.1595 + }
3.1596 +
3.1597 + function evaluateImmediate(suppressChangeNotification) {
3.1598 + if (_isBeingEvaluated) {
3.1599 + if (pure) {
3.1600 + throw Error("A 'pure' computed must not be called recursively");
3.1601 + }
3.1602 + // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
3.1603 + // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
3.1604 + // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
3.1605 + // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
3.1606 + return;
3.1607 + }
3.1608 +
3.1609 + // Do not evaluate (and possibly capture new dependencies) if disposed
3.1610 + if (_isDisposed) {
3.1611 + return;
3.1612 + }
3.1613 +
3.1614 + if (disposeWhen && disposeWhen()) {
3.1615 + // See comment below about _suppressDisposalUntilDisposeWhenReturnsFalse
3.1616 + if (!_suppressDisposalUntilDisposeWhenReturnsFalse) {
3.1617 + dispose();
3.1618 + return;
3.1619 + }
3.1620 + } else {
3.1621 + // It just did return false, so we can stop suppressing now
3.1622 + _suppressDisposalUntilDisposeWhenReturnsFalse = false;
3.1623 + }
3.1624 +
3.1625 + _isBeingEvaluated = true;
3.1626 +
3.1627 + // When sleeping, recalculate the value and return.
3.1628 + if (isSleeping) {
3.1629 + try {
3.1630 + var dependencyTracking = {};
3.1631 + ko.dependencyDetection.begin({
3.1632 + callback: function (subscribable, id) {
3.1633 + if (!dependencyTracking[id]) {
3.1634 + dependencyTracking[id] = 1;
3.1635 + ++_dependenciesCount;
3.1636 + }
3.1637 + },
3.1638 + computed: dependentObservable,
3.1639 + isInitial: undefined
3.1640 + });
3.1641 + _dependenciesCount = 0;
3.1642 + _latestValue = readFunction.call(evaluatorFunctionTarget);
3.1643 + } finally {
3.1644 + ko.dependencyDetection.end();
3.1645 + _isBeingEvaluated = false;
3.1646 + }
3.1647 + } else {
3.1648 + try {
3.1649 + // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
3.1650 + // Then, during evaluation, we cross off any that are in fact still being used.
3.1651 + var disposalCandidates = _subscriptionsToDependencies, disposalCount = _dependenciesCount;
3.1652 + ko.dependencyDetection.begin({
3.1653 + callback: function(subscribable, id) {
3.1654 + if (!_isDisposed) {
3.1655 + if (disposalCount && disposalCandidates[id]) {
3.1656 + // Don't want to dispose this subscription, as it's still being used
3.1657 + _subscriptionsToDependencies[id] = disposalCandidates[id];
3.1658 + ++_dependenciesCount;
3.1659 + delete disposalCandidates[id];
3.1660 + --disposalCount;
3.1661 + } else {
3.1662 + // Brand new subscription - add it
3.1663 + addSubscriptionToDependency(subscribable, id);
3.1664 + }
3.1665 + }
3.1666 + },
3.1667 + computed: dependentObservable,
3.1668 + isInitial: pure ? undefined : !_dependenciesCount // If we're evaluating when there are no previous dependencies, it must be the first time
3.1669 + });
3.1670 +
3.1671 + _subscriptionsToDependencies = {};
3.1672 + _dependenciesCount = 0;
3.1673 +
3.1674 + try {
3.1675 + var newValue = evaluatorFunctionTarget ? readFunction.call(evaluatorFunctionTarget) : readFunction();
3.1676 +
3.1677 + } finally {
3.1678 + ko.dependencyDetection.end();
3.1679 +
3.1680 + // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
3.1681 + if (disposalCount) {
3.1682 + ko.utils.objectForEach(disposalCandidates, function(id, toDispose) {
3.1683 + toDispose.dispose();
3.1684 + });
3.1685 + }
3.1686 +
3.1687 + _needsEvaluation = false;
3.1688 + }
3.1689 +
3.1690 + if (dependentObservable.isDifferent(_latestValue, newValue)) {
3.1691 + dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
3.1692 +
3.1693 + _latestValue = newValue;
3.1694 + if (DEBUG) dependentObservable._latestValue = _latestValue;
3.1695 +
3.1696 + if (suppressChangeNotification !== true) { // Check for strict true value since setTimeout in Firefox passes a numeric value to the function
3.1697 + dependentObservable["notifySubscribers"](_latestValue);
3.1698 + }
3.1699 + }
3.1700 + } finally {
3.1701 + _isBeingEvaluated = false;
3.1702 + }
3.1703 + }
3.1704 +
3.1705 + if (!_dependenciesCount)
3.1706 + dispose();
3.1707 + }
3.1708 +
3.1709 + function dependentObservable() {
3.1710 + if (arguments.length > 0) {
3.1711 + if (typeof writeFunction === "function") {
3.1712 + // Writing a value
3.1713 + writeFunction.apply(evaluatorFunctionTarget, arguments);
3.1714 + } else {
3.1715 + 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.");
3.1716 + }
3.1717 + return this; // Permits chained assignments
3.1718 + } else {
3.1719 + // Reading the value
3.1720 + ko.dependencyDetection.registerDependency(dependentObservable);
3.1721 + if (_needsEvaluation)
3.1722 + evaluateImmediate(true /* suppressChangeNotification */);
3.1723 + return _latestValue;
3.1724 + }
3.1725 + }
3.1726 +
3.1727 + function peek() {
3.1728 + // Peek won't re-evaluate, except to get the initial value when "deferEvaluation" is set, or while the computed is sleeping.
3.1729 + // Those are the only times that both of these conditions will be satisfied.
3.1730 + if (_needsEvaluation && !_dependenciesCount)
3.1731 + evaluateImmediate(true /* suppressChangeNotification */);
3.1732 + return _latestValue;
3.1733 + }
3.1734 +
3.1735 + function isActive() {
3.1736 + return _needsEvaluation || _dependenciesCount > 0;
3.1737 + }
3.1738 +
3.1739 + // By here, "options" is always non-null
3.1740 + var writeFunction = options["write"],
3.1741 + disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
3.1742 + disposeWhenOption = options["disposeWhen"] || options.disposeWhen,
3.1743 + disposeWhen = disposeWhenOption,
3.1744 + dispose = disposeComputed,
3.1745 + _subscriptionsToDependencies = {},
3.1746 + _dependenciesCount = 0,
3.1747 + evaluationTimeoutInstance = null;
3.1748 +
3.1749 + if (!evaluatorFunctionTarget)
3.1750 + evaluatorFunctionTarget = options["owner"];
3.1751 +
3.1752 + ko.subscribable.call(dependentObservable);
3.1753 + ko.utils.setPrototypeOfOrExtend(dependentObservable, ko.dependentObservable['fn']);
3.1754 +
3.1755 + dependentObservable.peek = peek;
3.1756 + dependentObservable.getDependenciesCount = function () { return _dependenciesCount; };
3.1757 + dependentObservable.hasWriteFunction = typeof options["write"] === "function";
3.1758 + dependentObservable.dispose = function () { dispose(); };
3.1759 + dependentObservable.isActive = isActive;
3.1760 +
3.1761 + // Replace the limit function with one that delays evaluation as well.
3.1762 + var originalLimit = dependentObservable.limit;
3.1763 + dependentObservable.limit = function(limitFunction) {
3.1764 + originalLimit.call(dependentObservable, limitFunction);
3.1765 + dependentObservable._evalRateLimited = function() {
3.1766 + dependentObservable._rateLimitedBeforeChange(_latestValue);
3.1767 +
3.1768 + _needsEvaluation = true; // Mark as dirty
3.1769 +
3.1770 + // Pass the observable to the rate-limit code, which will access it when
3.1771 + // it's time to do the notification.
3.1772 + dependentObservable._rateLimitedChange(dependentObservable);
3.1773 + }
3.1774 + };
3.1775 +
3.1776 + if (options['pure']) {
3.1777 + pure = true;
3.1778 + isSleeping = true; // Starts off sleeping; will awake on the first subscription
3.1779 + dependentObservable.beforeSubscriptionAdd = function () {
3.1780 + // If asleep, wake up the computed and evaluate to register any dependencies.
3.1781 + if (isSleeping) {
3.1782 + isSleeping = false;
3.1783 + evaluateImmediate(true /* suppressChangeNotification */);
3.1784 + }
3.1785 + }
3.1786 + dependentObservable.afterSubscriptionRemove = function () {
3.1787 + if (!dependentObservable.getSubscriptionsCount()) {
3.1788 + disposeAllSubscriptionsToDependencies();
3.1789 + isSleeping = _needsEvaluation = true;
3.1790 + }
3.1791 + }
3.1792 + } else if (options['deferEvaluation']) {
3.1793 + // This will force a computed with deferEvaluation to evaluate when the first subscriptions is registered.
3.1794 + dependentObservable.beforeSubscriptionAdd = function () {
3.1795 + peek();
3.1796 + delete dependentObservable.beforeSubscriptionAdd;
3.1797 + }
3.1798 + }
3.1799 +
3.1800 + ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
3.1801 + ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
3.1802 + ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
3.1803 + ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
3.1804 +
3.1805 + // Add a "disposeWhen" callback that, on each evaluation, disposes if the node was removed without using ko.removeNode.
3.1806 + if (disposeWhenNodeIsRemoved) {
3.1807 + // Since this computed is associated with a DOM node, and we don't want to dispose the computed
3.1808 + // until the DOM node is *removed* from the document (as opposed to never having been in the document),
3.1809 + // we'll prevent disposal until "disposeWhen" first returns false.
3.1810 + _suppressDisposalUntilDisposeWhenReturnsFalse = true;
3.1811 +
3.1812 + // Only watch for the node's disposal if the value really is a node. It might not be,
3.1813 + // e.g., { disposeWhenNodeIsRemoved: true } can be used to opt into the "only dispose
3.1814 + // after first false result" behaviour even if there's no specific node to watch. This
3.1815 + // technique is intended for KO's internal use only and shouldn't be documented or used
3.1816 + // by application code, as it's likely to change in a future version of KO.
3.1817 + if (disposeWhenNodeIsRemoved.nodeType) {
3.1818 + disposeWhen = function () {
3.1819 + return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || (disposeWhenOption && disposeWhenOption());
3.1820 + };
3.1821 + }
3.1822 + }
3.1823 +
3.1824 + // Evaluate, unless sleeping or deferEvaluation is true
3.1825 + if (!isSleeping && !options['deferEvaluation'])
3.1826 + evaluateImmediate();
3.1827 +
3.1828 + // Attach a DOM node disposal callback so that the computed will be proactively disposed as soon as the node is
3.1829 + // removed using ko.removeNode. But skip if isActive is false (there will never be any dependencies to dispose).
3.1830 + if (disposeWhenNodeIsRemoved && isActive() && disposeWhenNodeIsRemoved.nodeType) {
3.1831 + dispose = function() {
3.1832 + ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, dispose);
3.1833 + disposeComputed();
3.1834 + };
3.1835 + ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
3.1836 + }
3.1837 +
3.1838 + return dependentObservable;
3.1839 +};
3.1840 +
3.1841 +ko.isComputed = function(instance) {
3.1842 + return ko.hasPrototype(instance, ko.dependentObservable);
3.1843 +};
3.1844 +
3.1845 +var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
3.1846 +ko.dependentObservable[protoProp] = ko.observable;
3.1847 +
3.1848 +ko.dependentObservable['fn'] = {
3.1849 + "equalityComparer": valuesArePrimitiveAndEqual
3.1850 +};
3.1851 +ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
3.1852 +
3.1853 +// Note that for browsers that don't support proto assignment, the
3.1854 +// inheritance chain is created manually in the ko.dependentObservable constructor
3.1855 +if (ko.utils.canSetPrototype) {
3.1856 + ko.utils.setPrototypeOf(ko.dependentObservable['fn'], ko.subscribable['fn']);
3.1857 +}
3.1858 +
3.1859 +ko.exportSymbol('dependentObservable', ko.dependentObservable);
3.1860 +ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
3.1861 +ko.exportSymbol('isComputed', ko.isComputed);
3.1862 +
3.1863 +ko.pureComputed = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget) {
3.1864 + if (typeof evaluatorFunctionOrOptions === 'function') {
3.1865 + return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget, {'pure':true});
3.1866 + } else {
3.1867 + evaluatorFunctionOrOptions = ko.utils.extend({}, evaluatorFunctionOrOptions); // make a copy of the parameter object
3.1868 + evaluatorFunctionOrOptions['pure'] = true;
3.1869 + return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget);
3.1870 + }
3.1871 +}
3.1872 +ko.exportSymbol('pureComputed', ko.pureComputed);
3.1873 +
3.1874 +(function() {
3.1875 + var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
3.1876 +
3.1877 + ko.toJS = function(rootObject) {
3.1878 + if (arguments.length == 0)
3.1879 + throw new Error("When calling ko.toJS, pass the object you want to convert.");
3.1880 +
3.1881 + // We just unwrap everything at every level in the object graph
3.1882 + return mapJsObjectGraph(rootObject, function(valueToMap) {
3.1883 + // Loop because an observable's value might in turn be another observable wrapper
3.1884 + for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
3.1885 + valueToMap = valueToMap();
3.1886 + return valueToMap;
3.1887 + });
3.1888 + };
3.1889 +
3.1890 + ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
3.1891 + var plainJavaScriptObject = ko.toJS(rootObject);
3.1892 + return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
3.1893 + };
3.1894 +
3.1895 + function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
3.1896 + visitedObjects = visitedObjects || new objectLookup();
3.1897 +
3.1898 + rootObject = mapInputCallback(rootObject);
3.1899 + var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date)) && (!(rootObject instanceof String)) && (!(rootObject instanceof Number)) && (!(rootObject instanceof Boolean));
3.1900 + if (!canHaveProperties)
3.1901 + return rootObject;
3.1902 +
3.1903 + var outputProperties = rootObject instanceof Array ? [] : {};
3.1904 + visitedObjects.save(rootObject, outputProperties);
3.1905 +
3.1906 + visitPropertiesOrArrayEntries(rootObject, function(indexer) {
3.1907 + var propertyValue = mapInputCallback(rootObject[indexer]);
3.1908 +
3.1909 + switch (typeof propertyValue) {
3.1910 + case "boolean":
3.1911 + case "number":
3.1912 + case "string":
3.1913 + case "function":
3.1914 + outputProperties[indexer] = propertyValue;
3.1915 + break;
3.1916 + case "object":
3.1917 + case "undefined":
3.1918 + var previouslyMappedValue = visitedObjects.get(propertyValue);
3.1919 + outputProperties[indexer] = (previouslyMappedValue !== undefined)
3.1920 + ? previouslyMappedValue
3.1921 + : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
3.1922 + break;
3.1923 + }
3.1924 + });
3.1925 +
3.1926 + return outputProperties;
3.1927 + }
3.1928 +
3.1929 + function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
3.1930 + if (rootObject instanceof Array) {
3.1931 + for (var i = 0; i < rootObject.length; i++)
3.1932 + visitorCallback(i);
3.1933 +
3.1934 + // For arrays, also respect toJSON property for custom mappings (fixes #278)
3.1935 + if (typeof rootObject['toJSON'] == 'function')
3.1936 + visitorCallback('toJSON');
3.1937 + } else {
3.1938 + for (var propertyName in rootObject) {
3.1939 + visitorCallback(propertyName);
3.1940 + }
3.1941 + }
3.1942 + };
3.1943 +
3.1944 + function objectLookup() {
3.1945 + this.keys = [];
3.1946 + this.values = [];
3.1947 + };
3.1948 +
3.1949 + objectLookup.prototype = {
3.1950 + constructor: objectLookup,
3.1951 + save: function(key, value) {
3.1952 + var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
3.1953 + if (existingIndex >= 0)
3.1954 + this.values[existingIndex] = value;
3.1955 + else {
3.1956 + this.keys.push(key);
3.1957 + this.values.push(value);
3.1958 + }
3.1959 + },
3.1960 + get: function(key) {
3.1961 + var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
3.1962 + return (existingIndex >= 0) ? this.values[existingIndex] : undefined;
3.1963 + }
3.1964 + };
3.1965 +})();
3.1966 +
3.1967 +ko.exportSymbol('toJS', ko.toJS);
3.1968 +ko.exportSymbol('toJSON', ko.toJSON);
3.1969 +(function () {
3.1970 + var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
3.1971 +
3.1972 + // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
3.1973 + // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
3.1974 + // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
3.1975 + ko.selectExtensions = {
3.1976 + readValue : function(element) {
3.1977 + switch (ko.utils.tagNameLower(element)) {
3.1978 + case 'option':
3.1979 + if (element[hasDomDataExpandoProperty] === true)
3.1980 + return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
3.1981 + return ko.utils.ieVersion <= 7
3.1982 + ? (element.getAttributeNode('value') && element.getAttributeNode('value').specified ? element.value : element.text)
3.1983 + : element.value;
3.1984 + case 'select':
3.1985 + return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
3.1986 + default:
3.1987 + return element.value;
3.1988 + }
3.1989 + },
3.1990 +
3.1991 + writeValue: function(element, value, allowUnset) {
3.1992 + switch (ko.utils.tagNameLower(element)) {
3.1993 + case 'option':
3.1994 + switch(typeof value) {
3.1995 + case "string":
3.1996 + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
3.1997 + if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
3.1998 + delete element[hasDomDataExpandoProperty];
3.1999 + }
3.2000 + element.value = value;
3.2001 + break;
3.2002 + default:
3.2003 + // Store arbitrary object using DomData
3.2004 + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
3.2005 + element[hasDomDataExpandoProperty] = true;
3.2006 +
3.2007 + // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
3.2008 + element.value = typeof value === "number" ? value : "";
3.2009 + break;
3.2010 + }
3.2011 + break;
3.2012 + case 'select':
3.2013 + if (value === "" || value === null) // A blank string or null value will select the caption
3.2014 + value = undefined;
3.2015 + var selection = -1;
3.2016 + for (var i = 0, n = element.options.length, optionValue; i < n; ++i) {
3.2017 + optionValue = ko.selectExtensions.readValue(element.options[i]);
3.2018 + // Include special check to handle selecting a caption with a blank string value
3.2019 + if (optionValue == value || (optionValue == "" && value === undefined)) {
3.2020 + selection = i;
3.2021 + break;
3.2022 + }
3.2023 + }
3.2024 + if (allowUnset || selection >= 0 || (value === undefined && element.size > 1)) {
3.2025 + element.selectedIndex = selection;
3.2026 + }
3.2027 + break;
3.2028 + default:
3.2029 + if ((value === null) || (value === undefined))
3.2030 + value = "";
3.2031 + element.value = value;
3.2032 + break;
3.2033 + }
3.2034 + }
3.2035 + };
3.2036 +})();
3.2037 +
3.2038 +ko.exportSymbol('selectExtensions', ko.selectExtensions);
3.2039 +ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
3.2040 +ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
3.2041 +ko.expressionRewriting = (function () {
3.2042 + var javaScriptReservedWords = ["true", "false", "null", "undefined"];
3.2043 +
3.2044 + // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
3.2045 + // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
3.2046 + // This also will not properly handle nested brackets (e.g., obj1[obj2['prop']]; see #911).
3.2047 + var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
3.2048 +
3.2049 + function getWriteableValue(expression) {
3.2050 + if (ko.utils.arrayIndexOf(javaScriptReservedWords, expression) >= 0)
3.2051 + return false;
3.2052 + var match = expression.match(javaScriptAssignmentTarget);
3.2053 + return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
3.2054 + }
3.2055 +
3.2056 + // The following regular expressions will be used to split an object-literal string into tokens
3.2057 +
3.2058 + // These two match strings, either with double quotes or single quotes
3.2059 + var stringDouble = '"(?:[^"\\\\]|\\\\.)*"',
3.2060 + stringSingle = "'(?:[^'\\\\]|\\\\.)*'",
3.2061 + // Matches a regular expression (text enclosed by slashes), but will also match sets of divisions
3.2062 + // as a regular expression (this is handled by the parsing loop below).
3.2063 + stringRegexp = '/(?:[^/\\\\]|\\\\.)*/\w*',
3.2064 + // These characters have special meaning to the parser and must not appear in the middle of a
3.2065 + // token, except as part of a string.
3.2066 + specials = ',"\'{}()/:[\\]',
3.2067 + // Match text (at least two characters) that does not contain any of the above special characters,
3.2068 + // although some of the special characters are allowed to start it (all but the colon and comma).
3.2069 + // The text can contain spaces, but leading or trailing spaces are skipped.
3.2070 + everyThingElse = '[^\\s:,/][^' + specials + ']*[^\\s' + specials + ']',
3.2071 + // Match any non-space character not matched already. This will match colons and commas, since they're
3.2072 + // not matched by "everyThingElse", but will also match any other single character that wasn't already
3.2073 + // matched (for example: in "a: 1, b: 2", each of the non-space characters will be matched by oneNotSpace).
3.2074 + oneNotSpace = '[^\\s]',
3.2075 +
3.2076 + // Create the actual regular expression by or-ing the above strings. The order is important.
3.2077 + bindingToken = RegExp(stringDouble + '|' + stringSingle + '|' + stringRegexp + '|' + everyThingElse + '|' + oneNotSpace, 'g'),
3.2078 +
3.2079 + // Match end of previous token to determine whether a slash is a division or regex.
3.2080 + divisionLookBehind = /[\])"'A-Za-z0-9_$]+$/,
3.2081 + keywordRegexLookBehind = {'in':1,'return':1,'typeof':1};
3.2082 +
3.2083 + function parseObjectLiteral(objectLiteralString) {
3.2084 + // Trim leading and trailing spaces from the string
3.2085 + var str = ko.utils.stringTrim(objectLiteralString);
3.2086 +
3.2087 + // Trim braces '{' surrounding the whole object literal
3.2088 + if (str.charCodeAt(0) === 123) str = str.slice(1, -1);
3.2089 +
3.2090 + // Split into tokens
3.2091 + var result = [], toks = str.match(bindingToken), key, values, depth = 0;
3.2092 +
3.2093 + if (toks) {
3.2094 + // Append a comma so that we don't need a separate code block to deal with the last item
3.2095 + toks.push(',');
3.2096 +
3.2097 + for (var i = 0, tok; tok = toks[i]; ++i) {
3.2098 + var c = tok.charCodeAt(0);
3.2099 + // A comma signals the end of a key/value pair if depth is zero
3.2100 + if (c === 44) { // ","
3.2101 + if (depth <= 0) {
3.2102 + if (key)
3.2103 + result.push(values ? {key: key, value: values.join('')} : {'unknown': key});
3.2104 + key = values = depth = 0;
3.2105 + continue;
3.2106 + }
3.2107 + // Simply skip the colon that separates the name and value
3.2108 + } else if (c === 58) { // ":"
3.2109 + if (!values)
3.2110 + continue;
3.2111 + // A set of slashes is initially matched as a regular expression, but could be division
3.2112 + } else if (c === 47 && i && tok.length > 1) { // "/"
3.2113 + // Look at the end of the previous token to determine if the slash is actually division
3.2114 + var match = toks[i-1].match(divisionLookBehind);
3.2115 + if (match && !keywordRegexLookBehind[match[0]]) {
3.2116 + // The slash is actually a division punctuator; re-parse the remainder of the string (not including the slash)
3.2117 + str = str.substr(str.indexOf(tok) + 1);
3.2118 + toks = str.match(bindingToken);
3.2119 + toks.push(',');
3.2120 + i = -1;
3.2121 + // Continue with just the slash
3.2122 + tok = '/';
3.2123 + }
3.2124 + // Increment depth for parentheses, braces, and brackets so that interior commas are ignored
3.2125 + } else if (c === 40 || c === 123 || c === 91) { // '(', '{', '['
3.2126 + ++depth;
3.2127 + } else if (c === 41 || c === 125 || c === 93) { // ')', '}', ']'
3.2128 + --depth;
3.2129 + // The key must be a single token; if it's a string, trim the quotes
3.2130 + } else if (!key && !values) {
3.2131 + key = (c === 34 || c === 39) /* '"', "'" */ ? tok.slice(1, -1) : tok;
3.2132 + continue;
3.2133 + }
3.2134 + if (values)
3.2135 + values.push(tok);
3.2136 + else
3.2137 + values = [tok];
3.2138 + }
3.2139 + }
3.2140 + return result;
3.2141 + }
3.2142 +
3.2143 + // Two-way bindings include a write function that allow the handler to update the value even if it's not an observable.
3.2144 + var twoWayBindings = {};
3.2145 +
3.2146 + function preProcessBindings(bindingsStringOrKeyValueArray, bindingOptions) {
3.2147 + bindingOptions = bindingOptions || {};
3.2148 +
3.2149 + function processKeyValue(key, val) {
3.2150 + var writableVal;
3.2151 + function callPreprocessHook(obj) {
3.2152 + return (obj && obj['preprocess']) ? (val = obj['preprocess'](val, key, processKeyValue)) : true;
3.2153 + }
3.2154 + if (!bindingParams) {
3.2155 + if (!callPreprocessHook(ko['getBindingHandler'](key)))
3.2156 + return;
3.2157 +
3.2158 + if (twoWayBindings[key] && (writableVal = getWriteableValue(val))) {
3.2159 + // For two-way bindings, provide a write method in case the value
3.2160 + // isn't a writable observable.
3.2161 + propertyAccessorResultStrings.push("'" + key + "':function(_z){" + writableVal + "=_z}");
3.2162 + }
3.2163 + }
3.2164 + // Values are wrapped in a function so that each value can be accessed independently
3.2165 + if (makeValueAccessors) {
3.2166 + val = 'function(){return ' + val + ' }';
3.2167 + }
3.2168 + resultStrings.push("'" + key + "':" + val);
3.2169 + }
3.2170 +
3.2171 + var resultStrings = [],
3.2172 + propertyAccessorResultStrings = [],
3.2173 + makeValueAccessors = bindingOptions['valueAccessors'],
3.2174 + bindingParams = bindingOptions['bindingParams'],
3.2175 + keyValueArray = typeof bindingsStringOrKeyValueArray === "string" ?
3.2176 + parseObjectLiteral(bindingsStringOrKeyValueArray) : bindingsStringOrKeyValueArray;
3.2177 +
3.2178 + ko.utils.arrayForEach(keyValueArray, function(keyValue) {
3.2179 + processKeyValue(keyValue.key || keyValue['unknown'], keyValue.value);
3.2180 + });
3.2181 +
3.2182 + if (propertyAccessorResultStrings.length)
3.2183 + processKeyValue('_ko_property_writers', "{" + propertyAccessorResultStrings.join(",") + " }");
3.2184 +
3.2185 + return resultStrings.join(",");
3.2186 + }
3.2187 +
3.2188 + return {
3.2189 + bindingRewriteValidators: [],
3.2190 +
3.2191 + twoWayBindings: twoWayBindings,
3.2192 +
3.2193 + parseObjectLiteral: parseObjectLiteral,
3.2194 +
3.2195 + preProcessBindings: preProcessBindings,
3.2196 +
3.2197 + keyValueArrayContainsKey: function(keyValueArray, key) {
3.2198 + for (var i = 0; i < keyValueArray.length; i++)
3.2199 + if (keyValueArray[i]['key'] == key)
3.2200 + return true;
3.2201 + return false;
3.2202 + },
3.2203 +
3.2204 + // Internal, private KO utility for updating model properties from within bindings
3.2205 + // property: If the property being updated is (or might be) an observable, pass it here
3.2206 + // If it turns out to be a writable observable, it will be written to directly
3.2207 + // allBindings: An object with a get method to retrieve bindings in the current execution context.
3.2208 + // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
3.2209 + // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
3.2210 + // value: The value to be written
3.2211 + // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
3.2212 + // it is !== existing value on that writable observable
3.2213 + writeValueToProperty: function(property, allBindings, key, value, checkIfDifferent) {
3.2214 + if (!property || !ko.isObservable(property)) {
3.2215 + var propWriters = allBindings.get('_ko_property_writers');
3.2216 + if (propWriters && propWriters[key])
3.2217 + propWriters[key](value);
3.2218 + } else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {
3.2219 + property(value);
3.2220 + }
3.2221 + }
3.2222 + };
3.2223 +})();
3.2224 +
3.2225 +ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
3.2226 +ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
3.2227 +ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
3.2228 +ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
3.2229 +
3.2230 +// Making bindings explicitly declare themselves as "two way" isn't ideal in the long term (it would be better if
3.2231 +// all bindings could use an official 'property writer' API without needing to declare that they might). However,
3.2232 +// since this is not, and has never been, a public API (_ko_property_writers was never documented), it's acceptable
3.2233 +// as an internal implementation detail in the short term.
3.2234 +// For those developers who rely on _ko_property_writers in their custom bindings, we expose _twoWayBindings as an
3.2235 +// undocumented feature that makes it relatively easy to upgrade to KO 3.0. However, this is still not an official
3.2236 +// public API, and we reserve the right to remove it at any time if we create a real public property writers API.
3.2237 +ko.exportSymbol('expressionRewriting._twoWayBindings', ko.expressionRewriting.twoWayBindings);
3.2238 +
3.2239 +// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
3.2240 +// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
3.2241 +ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
3.2242 +ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);
3.2243 +(function() {
3.2244 + // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
3.2245 + // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
3.2246 + // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
3.2247 + // of that virtual hierarchy
3.2248 + //
3.2249 + // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
3.2250 + // without having to scatter special cases all over the binding and templating code.
3.2251 +
3.2252 + // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
3.2253 + // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
3.2254 + // So, use node.text where available, and node.nodeValue elsewhere
3.2255 + var commentNodesHaveTextProperty = document && document.createComment("test").text === "<!--test-->";
3.2256 +
3.2257 + var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/;
3.2258 + var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
3.2259 + var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
3.2260 +
3.2261 + function isStartComment(node) {
3.2262 + return (node.nodeType == 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
3.2263 + }
3.2264 +
3.2265 + function isEndComment(node) {
3.2266 + return (node.nodeType == 8) && endCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
3.2267 + }
3.2268 +
3.2269 + function getVirtualChildren(startComment, allowUnbalanced) {
3.2270 + var currentNode = startComment;
3.2271 + var depth = 1;
3.2272 + var children = [];
3.2273 + while (currentNode = currentNode.nextSibling) {
3.2274 + if (isEndComment(currentNode)) {
3.2275 + depth--;
3.2276 + if (depth === 0)
3.2277 + return children;
3.2278 + }
3.2279 +
3.2280 + children.push(currentNode);
3.2281 +
3.2282 + if (isStartComment(currentNode))
3.2283 + depth++;
3.2284 + }
3.2285 + if (!allowUnbalanced)
3.2286 + throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
3.2287 + return null;
3.2288 + }
3.2289 +
3.2290 + function getMatchingEndComment(startComment, allowUnbalanced) {
3.2291 + var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
3.2292 + if (allVirtualChildren) {
3.2293 + if (allVirtualChildren.length > 0)
3.2294 + return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
3.2295 + return startComment.nextSibling;
3.2296 + } else
3.2297 + return null; // Must have no matching end comment, and allowUnbalanced is true
3.2298 + }
3.2299 +
3.2300 + function getUnbalancedChildTags(node) {
3.2301 + // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
3.2302 + // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
3.2303 + var childNode = node.firstChild, captureRemaining = null;
3.2304 + if (childNode) {
3.2305 + do {
3.2306 + if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
3.2307 + captureRemaining.push(childNode);
3.2308 + else if (isStartComment(childNode)) {
3.2309 + var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
3.2310 + if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
3.2311 + childNode = matchingEndComment;
3.2312 + else
3.2313 + captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
3.2314 + } else if (isEndComment(childNode)) {
3.2315 + captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
3.2316 + }
3.2317 + } while (childNode = childNode.nextSibling);
3.2318 + }
3.2319 + return captureRemaining;
3.2320 + }
3.2321 +
3.2322 + ko.virtualElements = {
3.2323 + allowedBindings: {},
3.2324 +
3.2325 + childNodes: function(node) {
3.2326 + return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
3.2327 + },
3.2328 +
3.2329 + emptyNode: function(node) {
3.2330 + if (!isStartComment(node))
3.2331 + ko.utils.emptyDomNode(node);
3.2332 + else {
3.2333 + var virtualChildren = ko.virtualElements.childNodes(node);
3.2334 + for (var i = 0, j = virtualChildren.length; i < j; i++)
3.2335 + ko.removeNode(virtualChildren[i]);
3.2336 + }
3.2337 + },
3.2338 +
3.2339 + setDomNodeChildren: function(node, childNodes) {
3.2340 + if (!isStartComment(node))
3.2341 + ko.utils.setDomNodeChildren(node, childNodes);
3.2342 + else {
3.2343 + ko.virtualElements.emptyNode(node);
3.2344 + var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
3.2345 + for (var i = 0, j = childNodes.length; i < j; i++)
3.2346 + endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
3.2347 + }
3.2348 + },
3.2349 +
3.2350 + prepend: function(containerNode, nodeToPrepend) {
3.2351 + if (!isStartComment(containerNode)) {
3.2352 + if (containerNode.firstChild)
3.2353 + containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
3.2354 + else
3.2355 + containerNode.appendChild(nodeToPrepend);
3.2356 + } else {
3.2357 + // Start comments must always have a parent and at least one following sibling (the end comment)
3.2358 + containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
3.2359 + }
3.2360 + },
3.2361 +
3.2362 + insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
3.2363 + if (!insertAfterNode) {
3.2364 + ko.virtualElements.prepend(containerNode, nodeToInsert);
3.2365 + } else if (!isStartComment(containerNode)) {
3.2366 + // Insert after insertion point
3.2367 + if (insertAfterNode.nextSibling)
3.2368 + containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
3.2369 + else
3.2370 + containerNode.appendChild(nodeToInsert);
3.2371 + } else {
3.2372 + // Children of start comments must always have a parent and at least one following sibling (the end comment)
3.2373 + containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
3.2374 + }
3.2375 + },
3.2376 +
3.2377 + firstChild: function(node) {
3.2378 + if (!isStartComment(node))
3.2379 + return node.firstChild;
3.2380 + if (!node.nextSibling || isEndComment(node.nextSibling))
3.2381 + return null;
3.2382 + return node.nextSibling;
3.2383 + },
3.2384 +
3.2385 + nextSibling: function(node) {
3.2386 + if (isStartComment(node))
3.2387 + node = getMatchingEndComment(node);
3.2388 + if (node.nextSibling && isEndComment(node.nextSibling))
3.2389 + return null;
3.2390 + return node.nextSibling;
3.2391 + },
3.2392 +
3.2393 + hasBindingValue: isStartComment,
3.2394 +
3.2395 + virtualNodeBindingValue: function(node) {
3.2396 + var regexMatch = (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
3.2397 + return regexMatch ? regexMatch[1] : null;
3.2398 + },
3.2399 +
3.2400 + normaliseVirtualElementDomStructure: function(elementVerified) {
3.2401 + // Workaround for https://github.com/SteveSanderson/knockout/issues/155
3.2402 + // (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
3.2403 + // that are direct descendants of <ul> into the preceding <li>)
3.2404 + if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
3.2405 + return;
3.2406 +
3.2407 + // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
3.2408 + // must be intended to appear *after* that child, so move them there.
3.2409 + var childNode = elementVerified.firstChild;
3.2410 + if (childNode) {
3.2411 + do {
3.2412 + if (childNode.nodeType === 1) {
3.2413 + var unbalancedTags = getUnbalancedChildTags(childNode);
3.2414 + if (unbalancedTags) {
3.2415 + // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
3.2416 + var nodeToInsertBefore = childNode.nextSibling;
3.2417 + for (var i = 0; i < unbalancedTags.length; i++) {
3.2418 + if (nodeToInsertBefore)
3.2419 + elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
3.2420 + else
3.2421 + elementVerified.appendChild(unbalancedTags[i]);
3.2422 + }
3.2423 + }
3.2424 + }
3.2425 + } while (childNode = childNode.nextSibling);
3.2426 + }
3.2427 + }
3.2428 + };
3.2429 +})();
3.2430 +ko.exportSymbol('virtualElements', ko.virtualElements);
3.2431 +ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
3.2432 +ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
3.2433 +//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
3.2434 +ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
3.2435 +//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
3.2436 +ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
3.2437 +ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
3.2438 +(function() {
3.2439 + var defaultBindingAttributeName = "data-bind";
3.2440 +
3.2441 + ko.bindingProvider = function() {
3.2442 + this.bindingCache = {};
3.2443 + };
3.2444 +
3.2445 + ko.utils.extend(ko.bindingProvider.prototype, {
3.2446 + 'nodeHasBindings': function(node) {
3.2447 + switch (node.nodeType) {
3.2448 + case 1: // Element
3.2449 + return node.getAttribute(defaultBindingAttributeName) != null
3.2450 + || ko.components['getComponentNameForNode'](node);
3.2451 + case 8: // Comment node
3.2452 + return ko.virtualElements.hasBindingValue(node);
3.2453 + default: return false;
3.2454 + }
3.2455 + },
3.2456 +
3.2457 + 'getBindings': function(node, bindingContext) {
3.2458 + var bindingsString = this['getBindingsString'](node, bindingContext),
3.2459 + parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
3.2460 + return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ false);
3.2461 + },
3.2462 +
3.2463 + 'getBindingAccessors': function(node, bindingContext) {
3.2464 + var bindingsString = this['getBindingsString'](node, bindingContext),
3.2465 + parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node, { 'valueAccessors': true }) : null;
3.2466 + return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ true);
3.2467 + },
3.2468 +
3.2469 + // The following function is only used internally by this default provider.
3.2470 + // It's not part of the interface definition for a general binding provider.
3.2471 + 'getBindingsString': function(node, bindingContext) {
3.2472 + switch (node.nodeType) {
3.2473 + case 1: return node.getAttribute(defaultBindingAttributeName); // Element
3.2474 + case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
3.2475 + default: return null;
3.2476 + }
3.2477 + },
3.2478 +
3.2479 + // The following function is only used internally by this default provider.
3.2480 + // It's not part of the interface definition for a general binding provider.
3.2481 + 'parseBindingsString': function(bindingsString, bindingContext, node, options) {
3.2482 + try {
3.2483 + var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache, options);
3.2484 + return bindingFunction(bindingContext, node);
3.2485 + } catch (ex) {
3.2486 + ex.message = "Unable to parse bindings.\nBindings value: " + bindingsString + "\nMessage: " + ex.message;
3.2487 + throw ex;
3.2488 + }
3.2489 + }
3.2490 + });
3.2491 +
3.2492 + ko.bindingProvider['instance'] = new ko.bindingProvider();
3.2493 +
3.2494 + function createBindingsStringEvaluatorViaCache(bindingsString, cache, options) {
3.2495 + var cacheKey = bindingsString + (options && options['valueAccessors'] || '');
3.2496 + return cache[cacheKey]
3.2497 + || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, options));
3.2498 + }
3.2499 +
3.2500 + function createBindingsStringEvaluator(bindingsString, options) {
3.2501 + // Build the source for a function that evaluates "expression"
3.2502 + // For each scope variable, add an extra level of "with" nesting
3.2503 + // Example result: with(sc1) { with(sc0) { return (expression) } }
3.2504 + var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString, options),
3.2505 + functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
3.2506 + return new Function("$context", "$element", functionBody);
3.2507 + }
3.2508 +})();
3.2509 +
3.2510 +ko.exportSymbol('bindingProvider', ko.bindingProvider);
3.2511 +(function () {
3.2512 + ko.bindingHandlers = {};
3.2513 +
3.2514 + // The following element types will not be recursed into during binding. In the future, we
3.2515 + // may consider adding <template> to this list, because such elements' contents are always
3.2516 + // intended to be bound in a different context from where they appear in the document.
3.2517 + var bindingDoesNotRecurseIntoElementTypes = {
3.2518 + // Don't want bindings that operate on text nodes to mutate <script> contents,
3.2519 + // because it's unexpected and a potential XSS issue
3.2520 + 'script': true
3.2521 + };
3.2522 +
3.2523 + // Use an overridable method for retrieving binding handlers so that a plugins may support dynamically created handlers
3.2524 + ko['getBindingHandler'] = function(bindingKey) {
3.2525 + return ko.bindingHandlers[bindingKey];
3.2526 + };
3.2527 +
3.2528 + // The ko.bindingContext constructor is only called directly to create the root context. For child
3.2529 + // contexts, use bindingContext.createChildContext or bindingContext.extend.
3.2530 + ko.bindingContext = function(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback) {
3.2531 +
3.2532 + // The binding context object includes static properties for the current, parent, and root view models.
3.2533 + // If a view model is actually stored in an observable, the corresponding binding context object, and
3.2534 + // any child contexts, must be updated when the view model is changed.
3.2535 + function updateContext() {
3.2536 + // Most of the time, the context will directly get a view model object, but if a function is given,
3.2537 + // we call the function to retrieve the view model. If the function accesses any obsevables or returns
3.2538 + // an observable, the dependency is tracked, and those observables can later cause the binding
3.2539 + // context to be updated.
3.2540 + var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
3.2541 + dataItem = ko.utils.unwrapObservable(dataItemOrObservable);
3.2542 +
3.2543 + if (parentContext) {
3.2544 + // When a "parent" context is given, register a dependency on the parent context. Thus whenever the
3.2545 + // parent context is updated, this context will also be updated.
3.2546 + if (parentContext._subscribable)
3.2547 + parentContext._subscribable();
3.2548 +
3.2549 + // Copy $root and any custom properties from the parent context
3.2550 + ko.utils.extend(self, parentContext);
3.2551 +
3.2552 + // Because the above copy overwrites our own properties, we need to reset them.
3.2553 + // During the first execution, "subscribable" isn't set, so don't bother doing the update then.
3.2554 + if (subscribable) {
3.2555 + self._subscribable = subscribable;
3.2556 + }
3.2557 + } else {
3.2558 + self['$parents'] = [];
3.2559 + self['$root'] = dataItem;
3.2560 +
3.2561 + // Export 'ko' in the binding context so it will be available in bindings and templates
3.2562 + // even if 'ko' isn't exported as a global, such as when using an AMD loader.
3.2563 + // See https://github.com/SteveSanderson/knockout/issues/490
3.2564 + self['ko'] = ko;
3.2565 + }
3.2566 + self['$rawData'] = dataItemOrObservable;
3.2567 + self['$data'] = dataItem;
3.2568 + if (dataItemAlias)
3.2569 + self[dataItemAlias] = dataItem;
3.2570 +
3.2571 + // The extendCallback function is provided when creating a child context or extending a context.
3.2572 + // It handles the specific actions needed to finish setting up the binding context. Actions in this
3.2573 + // function could also add dependencies to this binding context.
3.2574 + if (extendCallback)
3.2575 + extendCallback(self, parentContext, dataItem);
3.2576 +
3.2577 + return self['$data'];
3.2578 + }
3.2579 + function disposeWhen() {
3.2580 + return nodes && !ko.utils.anyDomNodeIsAttachedToDocument(nodes);
3.2581 + }
3.2582 +
3.2583 + var self = this,
3.2584 + isFunc = typeof(dataItemOrAccessor) == "function" && !ko.isObservable(dataItemOrAccessor),
3.2585 + nodes,
3.2586 + subscribable = ko.dependentObservable(updateContext, null, { disposeWhen: disposeWhen, disposeWhenNodeIsRemoved: true });
3.2587 +
3.2588 + // At this point, the binding context has been initialized, and the "subscribable" computed observable is
3.2589 + // subscribed to any observables that were accessed in the process. If there is nothing to track, the
3.2590 + // computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
3.2591 + // the context object.
3.2592 + if (subscribable.isActive()) {
3.2593 + self._subscribable = subscribable;
3.2594 +
3.2595 + // Always notify because even if the model ($data) hasn't changed, other context properties might have changed
3.2596 + subscribable['equalityComparer'] = null;
3.2597 +
3.2598 + // We need to be able to dispose of this computed observable when it's no longer needed. This would be
3.2599 + // easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
3.2600 + // we cannot assume that those nodes have any relation to each other. So instead we track any node that
3.2601 + // the context is attached to, and dispose the computed when all of those nodes have been cleaned.
3.2602 +
3.2603 + // Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
3.2604 + nodes = [];
3.2605 + subscribable._addNode = function(node) {
3.2606 + nodes.push(node);
3.2607 + ko.utils.domNodeDisposal.addDisposeCallback(node, function(node) {
3.2608 + ko.utils.arrayRemoveItem(nodes, node);
3.2609 + if (!nodes.length) {
3.2610 + subscribable.dispose();
3.2611 + self._subscribable = subscribable = undefined;
3.2612 + }
3.2613 + });
3.2614 + };
3.2615 + }
3.2616 + }
3.2617 +
3.2618 + // Extend the binding context hierarchy with a new view model object. If the parent context is watching
3.2619 + // any obsevables, the new child context will automatically get a dependency on the parent context.
3.2620 + // But this does not mean that the $data value of the child context will also get updated. If the child
3.2621 + // view model also depends on the parent view model, you must provide a function that returns the correct
3.2622 + // view model on each update.
3.2623 + ko.bindingContext.prototype['createChildContext'] = function (dataItemOrAccessor, dataItemAlias, extendCallback) {
3.2624 + return new ko.bindingContext(dataItemOrAccessor, this, dataItemAlias, function(self, parentContext) {
3.2625 + // Extend the context hierarchy by setting the appropriate pointers
3.2626 + self['$parentContext'] = parentContext;
3.2627 + self['$parent'] = parentContext['$data'];
3.2628 + self['$parents'] = (parentContext['$parents'] || []).slice(0);
3.2629 + self['$parents'].unshift(self['$parent']);
3.2630 + if (extendCallback)
3.2631 + extendCallback(self);
3.2632 + });
3.2633 + };
3.2634 +
3.2635 + // Extend the binding context with new custom properties. This doesn't change the context hierarchy.
3.2636 + // Similarly to "child" contexts, provide a function here to make sure that the correct values are set
3.2637 + // when an observable view model is updated.
3.2638 + ko.bindingContext.prototype['extend'] = function(properties) {
3.2639 + // If the parent context references an observable view model, "_subscribable" will always be the
3.2640 + // latest view model object. If not, "_subscribable" isn't set, and we can use the static "$data" value.
3.2641 + return new ko.bindingContext(this._subscribable || this['$data'], this, null, function(self, parentContext) {
3.2642 + // This "child" context doesn't directly track a parent observable view model,
3.2643 + // so we need to manually set the $rawData value to match the parent.
3.2644 + self['$rawData'] = parentContext['$rawData'];
3.2645 + ko.utils.extend(self, typeof(properties) == "function" ? properties() : properties);
3.2646 + });
3.2647 + };
3.2648 +
3.2649 + // Returns the valueAccesor function for a binding value
3.2650 + function makeValueAccessor(value) {
3.2651 + return function() {
3.2652 + return value;
3.2653 + };
3.2654 + }
3.2655 +
3.2656 + // Returns the value of a valueAccessor function
3.2657 + function evaluateValueAccessor(valueAccessor) {
3.2658 + return valueAccessor();
3.2659 + }
3.2660 +
3.2661 + // Given a function that returns bindings, create and return a new object that contains
3.2662 + // binding value-accessors functions. Each accessor function calls the original function
3.2663 + // so that it always gets the latest value and all dependencies are captured. This is used
3.2664 + // by ko.applyBindingsToNode and getBindingsAndMakeAccessors.
3.2665 + function makeAccessorsFromFunction(callback) {
3.2666 + return ko.utils.objectMap(ko.dependencyDetection.ignore(callback), function(value, key) {
3.2667 + return function() {
3.2668 + return callback()[key];
3.2669 + };
3.2670 + });
3.2671 + }
3.2672 +
3.2673 + // Given a bindings function or object, create and return a new object that contains
3.2674 + // binding value-accessors functions. This is used by ko.applyBindingsToNode.
3.2675 + function makeBindingAccessors(bindings, context, node) {
3.2676 + if (typeof bindings === 'function') {
3.2677 + return makeAccessorsFromFunction(bindings.bind(null, context, node));
3.2678 + } else {
3.2679 + return ko.utils.objectMap(bindings, makeValueAccessor);
3.2680 + }
3.2681 + }
3.2682 +
3.2683 + // This function is used if the binding provider doesn't include a getBindingAccessors function.
3.2684 + // It must be called with 'this' set to the provider instance.
3.2685 + function getBindingsAndMakeAccessors(node, context) {
3.2686 + return makeAccessorsFromFunction(this['getBindings'].bind(this, node, context));
3.2687 + }
3.2688 +
3.2689 + function validateThatBindingIsAllowedForVirtualElements(bindingName) {
3.2690 + var validator = ko.virtualElements.allowedBindings[bindingName];
3.2691 + if (!validator)
3.2692 + throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
3.2693 + }
3.2694 +
3.2695 + function applyBindingsToDescendantsInternal (bindingContext, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
3.2696 + var currentChild,
3.2697 + nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement),
3.2698 + provider = ko.bindingProvider['instance'],
3.2699 + preprocessNode = provider['preprocessNode'];
3.2700 +
3.2701 + // Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's
3.2702 + // possible to insert new siblings after it, and/or replace the node with a different one. This can be used to
3.2703 + // implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that
3.2704 + // trigger insertion of <template> contents at that point in the document.
3.2705 + if (preprocessNode) {
3.2706 + while (currentChild = nextInQueue) {
3.2707 + nextInQueue = ko.virtualElements.nextSibling(currentChild);
3.2708 + preprocessNode.call(provider, currentChild);
3.2709 + }
3.2710 + // Reset nextInQueue for the next loop
3.2711 + nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
3.2712 + }
3.2713 +
3.2714 + while (currentChild = nextInQueue) {
3.2715 + // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
3.2716 + nextInQueue = ko.virtualElements.nextSibling(currentChild);
3.2717 + applyBindingsToNodeAndDescendantsInternal(bindingContext, currentChild, bindingContextsMayDifferFromDomParentElement);
3.2718 + }
3.2719 + }
3.2720 +
3.2721 + function applyBindingsToNodeAndDescendantsInternal (bindingContext, nodeVerified, bindingContextMayDifferFromDomParentElement) {
3.2722 + var shouldBindDescendants = true;
3.2723 +
3.2724 + // Perf optimisation: Apply bindings only if...
3.2725 + // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
3.2726 + // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
3.2727 + // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
3.2728 + var isElement = (nodeVerified.nodeType === 1);
3.2729 + if (isElement) // Workaround IE <= 8 HTML parsing weirdness
3.2730 + ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
3.2731 +
3.2732 + var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
3.2733 + || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
3.2734 + if (shouldApplyBindings)
3.2735 + shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, bindingContext, bindingContextMayDifferFromDomParentElement)['shouldBindDescendants'];
3.2736 +
3.2737 + if (shouldBindDescendants && !bindingDoesNotRecurseIntoElementTypes[ko.utils.tagNameLower(nodeVerified)]) {
3.2738 + // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
3.2739 + // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
3.2740 + // hence bindingContextsMayDifferFromDomParentElement is false
3.2741 + // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
3.2742 + // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
3.2743 + // hence bindingContextsMayDifferFromDomParentElement is true
3.2744 + applyBindingsToDescendantsInternal(bindingContext, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
3.2745 + }
3.2746 + }
3.2747 +
3.2748 + var boundElementDomDataKey = ko.utils.domData.nextKey();
3.2749 +
3.2750 +
3.2751 + function topologicalSortBindings(bindings) {
3.2752 + // Depth-first sort
3.2753 + var result = [], // The list of key/handler pairs that we will return
3.2754 + bindingsConsidered = {}, // A temporary record of which bindings are already in 'result'
3.2755 + cyclicDependencyStack = []; // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it
3.2756 + ko.utils.objectForEach(bindings, function pushBinding(bindingKey) {
3.2757 + if (!bindingsConsidered[bindingKey]) {
3.2758 + var binding = ko['getBindingHandler'](bindingKey);
3.2759 + if (binding) {
3.2760 + // First add dependencies (if any) of the current binding
3.2761 + if (binding['after']) {
3.2762 + cyclicDependencyStack.push(bindingKey);
3.2763 + ko.utils.arrayForEach(binding['after'], function(bindingDependencyKey) {
3.2764 + if (bindings[bindingDependencyKey]) {
3.2765 + if (ko.utils.arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) {
3.2766 + throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + cyclicDependencyStack.join(", "));
3.2767 + } else {
3.2768 + pushBinding(bindingDependencyKey);
3.2769 + }
3.2770 + }
3.2771 + });
3.2772 + cyclicDependencyStack.length--;
3.2773 + }
3.2774 + // Next add the current binding
3.2775 + result.push({ key: bindingKey, handler: binding });
3.2776 + }
3.2777 + bindingsConsidered[bindingKey] = true;
3.2778 + }
3.2779 + });
3.2780 +
3.2781 + return result;
3.2782 + }
3.2783 +
3.2784 + function applyBindingsToNodeInternal(node, sourceBindings, bindingContext, bindingContextMayDifferFromDomParentElement) {
3.2785 + // Prevent multiple applyBindings calls for the same node, except when a binding value is specified
3.2786 + var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
3.2787 + if (!sourceBindings) {
3.2788 + if (alreadyBound) {
3.2789 + throw Error("You cannot apply bindings multiple times to the same element.");
3.2790 + }
3.2791 + ko.utils.domData.set(node, boundElementDomDataKey, true);
3.2792 + }
3.2793 +
3.2794 + // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
3.2795 + // we can easily recover it just by scanning up the node's ancestors in the DOM
3.2796 + // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
3.2797 + if (!alreadyBound && bindingContextMayDifferFromDomParentElement)
3.2798 + ko.storedBindingContextForNode(node, bindingContext);
3.2799 +
3.2800 + // Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings
3.2801 + var bindings;
3.2802 + if (sourceBindings && typeof sourceBindings !== 'function') {
3.2803 + bindings = sourceBindings;
3.2804 + } else {
3.2805 + var provider = ko.bindingProvider['instance'],
3.2806 + getBindings = provider['getBindingAccessors'] || getBindingsAndMakeAccessors;
3.2807 +
3.2808 + // Get the binding from the provider within a computed observable so that we can update the bindings whenever
3.2809 + // the binding context is updated or if the binding provider accesses observables.
3.2810 + var bindingsUpdater = ko.dependentObservable(
3.2811 + function() {
3.2812 + bindings = sourceBindings ? sourceBindings(bindingContext, node) : getBindings.call(provider, node, bindingContext);
3.2813 + // Register a dependency on the binding context to support obsevable view models.
3.2814 + if (bindings && bindingContext._subscribable)
3.2815 + bindingContext._subscribable();
3.2816 + return bindings;
3.2817 + },
3.2818 + null, { disposeWhenNodeIsRemoved: node }
3.2819 + );
3.2820 +
3.2821 + if (!bindings || !bindingsUpdater.isActive())
3.2822 + bindingsUpdater = null;
3.2823 + }
3.2824 +
3.2825 + var bindingHandlerThatControlsDescendantBindings;
3.2826 + if (bindings) {
3.2827 + // Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding
3.2828 + // context update), just return the value accessor from the binding. Otherwise, return a function that always gets
3.2829 + // the latest binding value and registers a dependency on the binding updater.
3.2830 + var getValueAccessor = bindingsUpdater
3.2831 + ? function(bindingKey) {
3.2832 + return function() {
3.2833 + return evaluateValueAccessor(bindingsUpdater()[bindingKey]);
3.2834 + };
3.2835 + } : function(bindingKey) {
3.2836 + return bindings[bindingKey];
3.2837 + };
3.2838 +
3.2839 + // Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated
3.2840 + function allBindings() {
3.2841 + return ko.utils.objectMap(bindingsUpdater ? bindingsUpdater() : bindings, evaluateValueAccessor);
3.2842 + }
3.2843 + // The following is the 3.x allBindings API
3.2844 + allBindings['get'] = function(key) {
3.2845 + return bindings[key] && evaluateValueAccessor(getValueAccessor(key));
3.2846 + };
3.2847 + allBindings['has'] = function(key) {
3.2848 + return key in bindings;
3.2849 + };
3.2850 +
3.2851 + // First put the bindings into the right order
3.2852 + var orderedBindings = topologicalSortBindings(bindings);
3.2853 +
3.2854 + // Go through the sorted bindings, calling init and update for each
3.2855 + ko.utils.arrayForEach(orderedBindings, function(bindingKeyAndHandler) {
3.2856 + // Note that topologicalSortBindings has already filtered out any nonexistent binding handlers,
3.2857 + // so bindingKeyAndHandler.handler will always be nonnull.
3.2858 + var handlerInitFn = bindingKeyAndHandler.handler["init"],
3.2859 + handlerUpdateFn = bindingKeyAndHandler.handler["update"],
3.2860 + bindingKey = bindingKeyAndHandler.key;
3.2861 +
3.2862 + if (node.nodeType === 8) {
3.2863 + validateThatBindingIsAllowedForVirtualElements(bindingKey);
3.2864 + }
3.2865 +
3.2866 + try {
3.2867 + // Run init, ignoring any dependencies
3.2868 + if (typeof handlerInitFn == "function") {
3.2869 + ko.dependencyDetection.ignore(function() {
3.2870 + var initResult = handlerInitFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
3.2871 +
3.2872 + // If this binding handler claims to control descendant bindings, make a note of this
3.2873 + if (initResult && initResult['controlsDescendantBindings']) {
3.2874 + if (bindingHandlerThatControlsDescendantBindings !== undefined)
3.2875 + 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.");
3.2876 + bindingHandlerThatControlsDescendantBindings = bindingKey;
3.2877 + }
3.2878 + });
3.2879 + }
3.2880 +
3.2881 + // Run update in its own computed wrapper
3.2882 + if (typeof handlerUpdateFn == "function") {
3.2883 + ko.dependentObservable(
3.2884 + function() {
3.2885 + handlerUpdateFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
3.2886 + },
3.2887 + null,
3.2888 + { disposeWhenNodeIsRemoved: node }
3.2889 + );
3.2890 + }
3.2891 + } catch (ex) {
3.2892 + ex.message = "Unable to process binding \"" + bindingKey + ": " + bindings[bindingKey] + "\"\nMessage: " + ex.message;
3.2893 + throw ex;
3.2894 + }
3.2895 + });
3.2896 + }
3.2897 +
3.2898 + return {
3.2899 + 'shouldBindDescendants': bindingHandlerThatControlsDescendantBindings === undefined
3.2900 + };
3.2901 + };
3.2902 +
3.2903 + var storedBindingContextDomDataKey = ko.utils.domData.nextKey();
3.2904 + ko.storedBindingContextForNode = function (node, bindingContext) {
3.2905 + if (arguments.length == 2) {
3.2906 + ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
3.2907 + if (bindingContext._subscribable)
3.2908 + bindingContext._subscribable._addNode(node);
3.2909 + } else {
3.2910 + return ko.utils.domData.get(node, storedBindingContextDomDataKey);
3.2911 + }
3.2912 + }
3.2913 +
3.2914 + function getBindingContext(viewModelOrBindingContext) {
3.2915 + return viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
3.2916 + ? viewModelOrBindingContext
3.2917 + : new ko.bindingContext(viewModelOrBindingContext);
3.2918 + }
3.2919 +
3.2920 + ko.applyBindingAccessorsToNode = function (node, bindings, viewModelOrBindingContext) {
3.2921 + if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
3.2922 + ko.virtualElements.normaliseVirtualElementDomStructure(node);
3.2923 + return applyBindingsToNodeInternal(node, bindings, getBindingContext(viewModelOrBindingContext), true);
3.2924 + };
3.2925 +
3.2926 + ko.applyBindingsToNode = function (node, bindings, viewModelOrBindingContext) {
3.2927 + var context = getBindingContext(viewModelOrBindingContext);
3.2928 + return ko.applyBindingAccessorsToNode(node, makeBindingAccessors(bindings, context, node), context);
3.2929 + };
3.2930 +
3.2931 + ko.applyBindingsToDescendants = function(viewModelOrBindingContext, rootNode) {
3.2932 + if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
3.2933 + applyBindingsToDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
3.2934 + };
3.2935 +
3.2936 + ko.applyBindings = function (viewModelOrBindingContext, rootNode) {
3.2937 + // If jQuery is loaded after Knockout, we won't initially have access to it. So save it here.
3.2938 + if (!jQueryInstance && window['jQuery']) {
3.2939 + jQueryInstance = window['jQuery'];
3.2940 + }
3.2941 +
3.2942 + if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
3.2943 + throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
3.2944 + rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
3.2945 +
3.2946 + applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
3.2947 + };
3.2948 +
3.2949 + // Retrieving binding context from arbitrary nodes
3.2950 + ko.contextFor = function(node) {
3.2951 + // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
3.2952 + switch (node.nodeType) {
3.2953 + case 1:
3.2954 + case 8:
3.2955 + var context = ko.storedBindingContextForNode(node);
3.2956 + if (context) return context;
3.2957 + if (node.parentNode) return ko.contextFor(node.parentNode);
3.2958 + break;
3.2959 + }
3.2960 + return undefined;
3.2961 + };
3.2962 + ko.dataFor = function(node) {
3.2963 + var context = ko.contextFor(node);
3.2964 + return context ? context['$data'] : undefined;
3.2965 + };
3.2966 +
3.2967 + ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
3.2968 + ko.exportSymbol('applyBindings', ko.applyBindings);
3.2969 + ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
3.2970 + ko.exportSymbol('applyBindingAccessorsToNode', ko.applyBindingAccessorsToNode);
3.2971 + ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
3.2972 + ko.exportSymbol('contextFor', ko.contextFor);
3.2973 + ko.exportSymbol('dataFor', ko.dataFor);
3.2974 +})();
3.2975 +(function(undefined) {
3.2976 + var loadingSubscribablesCache = {}, // Tracks component loads that are currently in flight
3.2977 + loadedDefinitionsCache = {}; // Tracks component loads that have already completed
3.2978 +
3.2979 + ko.components = {
3.2980 + get: function(componentName, callback) {
3.2981 + var cachedDefinition = getObjectOwnProperty(loadedDefinitionsCache, componentName);
3.2982 + if (cachedDefinition) {
3.2983 + // It's already loaded and cached. Reuse the same definition object.
3.2984 + // Note that for API consistency, even cache hits complete asynchronously.
3.2985 + setTimeout(function() { callback(cachedDefinition) }, 0);
3.2986 + } else {
3.2987 + // Join the loading process that is already underway, or start a new one.
3.2988 + loadComponentAndNotify(componentName, callback);
3.2989 + }
3.2990 + },
3.2991 +
3.2992 + clearCachedDefinition: function(componentName) {
3.2993 + delete loadedDefinitionsCache[componentName];
3.2994 + },
3.2995 +
3.2996 + _getFirstResultFromLoaders: getFirstResultFromLoaders
3.2997 + };
3.2998 +
3.2999 + function getObjectOwnProperty(obj, propName) {
3.3000 + return obj.hasOwnProperty(propName) ? obj[propName] : undefined;
3.3001 + }
3.3002 +
3.3003 + function loadComponentAndNotify(componentName, callback) {
3.3004 + var subscribable = getObjectOwnProperty(loadingSubscribablesCache, componentName),
3.3005 + completedAsync;
3.3006 + if (!subscribable) {
3.3007 + // It's not started loading yet. Start loading, and when it's done, move it to loadedDefinitionsCache.
3.3008 + subscribable = loadingSubscribablesCache[componentName] = new ko.subscribable();
3.3009 + beginLoadingComponent(componentName, function(definition) {
3.3010 + loadedDefinitionsCache[componentName] = definition;
3.3011 + delete loadingSubscribablesCache[componentName];
3.3012 +
3.3013 + // For API consistency, all loads complete asynchronously. However we want to avoid
3.3014 + // adding an extra setTimeout if it's unnecessary (i.e., the completion is already
3.3015 + // async) since setTimeout(..., 0) still takes about 16ms or more on most browsers.
3.3016 + if (completedAsync) {
3.3017 + subscribable['notifySubscribers'](definition);
3.3018 + } else {
3.3019 + setTimeout(function() {
3.3020 + subscribable['notifySubscribers'](definition);
3.3021 + }, 0);
3.3022 + }
3.3023 + });
3.3024 + completedAsync = true;
3.3025 + }
3.3026 + subscribable.subscribe(callback);
3.3027 + }
3.3028 +
3.3029 + function beginLoadingComponent(componentName, callback) {
3.3030 + getFirstResultFromLoaders('getConfig', [componentName], function(config) {
3.3031 + if (config) {
3.3032 + // We have a config, so now load its definition
3.3033 + getFirstResultFromLoaders('loadComponent', [componentName, config], function(definition) {
3.3034 + callback(definition);
3.3035 + });
3.3036 + } else {
3.3037 + // The component has no config - it's unknown to all the loaders.
3.3038 + // Note that this is not an error (e.g., a module loading error) - that would abort the
3.3039 + // process and this callback would not run. For this callback to run, all loaders must
3.3040 + // have confirmed they don't know about this component.
3.3041 + callback(null);
3.3042 + }
3.3043 + });
3.3044 + }
3.3045 +
3.3046 + function getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders) {
3.3047 + // On the first call in the stack, start with the full set of loaders
3.3048 + if (!candidateLoaders) {
3.3049 + candidateLoaders = ko.components['loaders'].slice(0); // Use a copy, because we'll be mutating this array
3.3050 + }
3.3051 +
3.3052 + // Try the next candidate
3.3053 + var currentCandidateLoader = candidateLoaders.shift();
3.3054 + if (currentCandidateLoader) {
3.3055 + var methodInstance = currentCandidateLoader[methodName];
3.3056 + if (methodInstance) {
3.3057 + var wasAborted = false,
3.3058 + synchronousReturnValue = methodInstance.apply(currentCandidateLoader, argsExceptCallback.concat(function(result) {
3.3059 + if (wasAborted) {
3.3060 + callback(null);
3.3061 + } else if (result !== null) {
3.3062 + // This candidate returned a value. Use it.
3.3063 + callback(result);
3.3064 + } else {
3.3065 + // Try the next candidate
3.3066 + getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);
3.3067 + }
3.3068 + }));
3.3069 +
3.3070 + // Currently, loaders may not return anything synchronously. This leaves open the possibility
3.3071 + // that we'll extend the API to support synchronous return values in the future. It won't be
3.3072 + // a breaking change, because currently no loader is allowed to return anything except undefined.
3.3073 + if (synchronousReturnValue !== undefined) {
3.3074 + wasAborted = true;
3.3075 +
3.3076 + // Method to suppress exceptions will remain undocumented. This is only to keep
3.3077 + // KO's specs running tidily, since we can observe the loading got aborted without
3.3078 + // having exceptions cluttering up the console too.
3.3079 + if (!currentCandidateLoader['suppressLoaderExceptions']) {
3.3080 + throw new Error('Component loaders must supply values by invoking the callback, not by returning values synchronously.');
3.3081 + }
3.3082 + }
3.3083 + } else {
3.3084 + // This candidate doesn't have the relevant handler. Synchronously move on to the next one.
3.3085 + getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);
3.3086 + }
3.3087 + } else {
3.3088 + // No candidates returned a value
3.3089 + callback(null);
3.3090 + }
3.3091 + }
3.3092 +
3.3093 + // Reference the loaders via string name so it's possible for developers
3.3094 + // to replace the whole array by assigning to ko.components.loaders
3.3095 + ko.components['loaders'] = [];
3.3096 +
3.3097 + ko.exportSymbol('components', ko.components);
3.3098 + ko.exportSymbol('components.get', ko.components.get);
3.3099 + ko.exportSymbol('components.clearCachedDefinition', ko.components.clearCachedDefinition);
3.3100 +})();
3.3101 +(function(undefined) {
3.3102 +
3.3103 + // The default loader is responsible for two things:
3.3104 + // 1. Maintaining the default in-memory registry of component configuration objects
3.3105 + // (i.e., the thing you're writing to when you call ko.components.register(someName, ...))
3.3106 + // 2. Answering requests for components by fetching configuration objects
3.3107 + // from that default in-memory registry and resolving them into standard
3.3108 + // component definition objects (of the form { createViewModel: ..., template: ... })
3.3109 + // Custom loaders may override either of these facilities, i.e.,
3.3110 + // 1. To supply configuration objects from some other source (e.g., conventions)
3.3111 + // 2. Or, to resolve configuration objects by loading viewmodels/templates via arbitrary logic.
3.3112 +
3.3113 + var defaultConfigRegistry = {};
3.3114 +
3.3115 + ko.components.register = function(componentName, config) {
3.3116 + if (!config) {
3.3117 + throw new Error('Invalid configuration for ' + componentName);
3.3118 + }
3.3119 +
3.3120 + if (ko.components.isRegistered(componentName)) {
3.3121 + throw new Error('Component ' + componentName + ' is already registered');
3.3122 + }
3.3123 +
3.3124 + defaultConfigRegistry[componentName] = config;
3.3125 + }
3.3126 +
3.3127 + ko.components.isRegistered = function(componentName) {
3.3128 + return componentName in defaultConfigRegistry;
3.3129 + }
3.3130 +
3.3131 + ko.components.unregister = function(componentName) {
3.3132 + delete defaultConfigRegistry[componentName];
3.3133 + ko.components.clearCachedDefinition(componentName);
3.3134 + }
3.3135 +
3.3136 + ko.components.defaultLoader = {
3.3137 + 'getConfig': function(componentName, callback) {
3.3138 + var result = defaultConfigRegistry.hasOwnProperty(componentName)
3.3139 + ? defaultConfigRegistry[componentName]
3.3140 + : null;
3.3141 + callback(result);
3.3142 + },
3.3143 +
3.3144 + 'loadComponent': function(componentName, config, callback) {
3.3145 + var errorCallback = makeErrorCallback(componentName);
3.3146 + possiblyGetConfigFromAmd(errorCallback, config, function(loadedConfig) {
3.3147 + resolveConfig(componentName, errorCallback, loadedConfig, callback);
3.3148 + });
3.3149 + },
3.3150 +
3.3151 + 'loadTemplate': function(componentName, templateConfig, callback) {
3.3152 + resolveTemplate(makeErrorCallback(componentName), templateConfig, callback);
3.3153 + },
3.3154 +
3.3155 + 'loadViewModel': function(componentName, viewModelConfig, callback) {
3.3156 + resolveViewModel(makeErrorCallback(componentName), viewModelConfig, callback);
3.3157 + }
3.3158 + };
3.3159 +
3.3160 + var createViewModelKey = 'createViewModel';
3.3161 +
3.3162 + // Takes a config object of the form { template: ..., viewModel: ... }, and asynchronously convert it
3.3163 + // into the standard component definition format:
3.3164 + // { template: <ArrayOfDomNodes>, createViewModel: function(params, componentInfo) { ... } }.
3.3165 + // Since both template and viewModel may need to be resolved asynchronously, both tasks are performed
3.3166 + // in parallel, and the results joined when both are ready. We don't depend on any promises infrastructure,
3.3167 + // so this is implemented manually below.
3.3168 + function resolveConfig(componentName, errorCallback, config, callback) {
3.3169 + var result = {},
3.3170 + makeCallBackWhenZero = 2,
3.3171 + tryIssueCallback = function() {
3.3172 + if (--makeCallBackWhenZero === 0) {
3.3173 + callback(result);
3.3174 + }
3.3175 + },
3.3176 + templateConfig = config['template'],
3.3177 + viewModelConfig = config['viewModel'];
3.3178 +
3.3179 + if (templateConfig) {
3.3180 + possiblyGetConfigFromAmd(errorCallback, templateConfig, function(loadedConfig) {
3.3181 + ko.components._getFirstResultFromLoaders('loadTemplate', [componentName, loadedConfig], function(resolvedTemplate) {
3.3182 + result['template'] = resolvedTemplate;
3.3183 + tryIssueCallback();
3.3184 + });
3.3185 + });
3.3186 + } else {
3.3187 + tryIssueCallback();
3.3188 + }
3.3189 +
3.3190 + if (viewModelConfig) {
3.3191 + possiblyGetConfigFromAmd(errorCallback, viewModelConfig, function(loadedConfig) {
3.3192 + ko.components._getFirstResultFromLoaders('loadViewModel', [componentName, loadedConfig], function(resolvedViewModel) {
3.3193 + result[createViewModelKey] = resolvedViewModel;
3.3194 + tryIssueCallback();
3.3195 + });
3.3196 + });
3.3197 + } else {
3.3198 + tryIssueCallback();
3.3199 + }
3.3200 + }
3.3201 +
3.3202 + function resolveTemplate(errorCallback, templateConfig, callback) {
3.3203 + if (typeof templateConfig === 'string') {
3.3204 + // Markup - parse it
3.3205 + callback(ko.utils.parseHtmlFragment(templateConfig));
3.3206 + } else if (templateConfig instanceof Array) {
3.3207 + // Assume already an array of DOM nodes - pass through unchanged
3.3208 + callback(templateConfig);
3.3209 + } else if (isDocumentFragment(templateConfig)) {
3.3210 + // Document fragment - use its child nodes
3.3211 + callback(ko.utils.makeArray(templateConfig.childNodes));
3.3212 + } else if (templateConfig['element']) {
3.3213 + var element = templateConfig['element'];
3.3214 + if (isDomElement(element)) {
3.3215 + // Element instance - copy its child nodes
3.3216 + callback(cloneNodesFromTemplateSourceElement(element));
3.3217 + } else if (typeof element === 'string') {
3.3218 + // Element ID - find it, then copy its child nodes
3.3219 + var elemInstance = document.getElementById(element);
3.3220 + if (elemInstance) {
3.3221 + callback(cloneNodesFromTemplateSourceElement(elemInstance));
3.3222 + } else {
3.3223 + errorCallback('Cannot find element with ID ' + element);
3.3224 + }
3.3225 + } else {
3.3226 + errorCallback('Unknown element type: ' + element);
3.3227 + }
3.3228 + } else {
3.3229 + errorCallback('Unknown template value: ' + templateConfig);
3.3230 + }
3.3231 + }
3.3232 +
3.3233 + function resolveViewModel(errorCallback, viewModelConfig, callback) {
3.3234 + if (typeof viewModelConfig === 'function') {
3.3235 + // Constructor - convert to standard factory function format
3.3236 + // By design, this does *not* supply componentInfo to the constructor, as the intent is that
3.3237 + // componentInfo contains non-viewmodel data (e.g., the component's element) that should only
3.3238 + // be used in factory functions, not viewmodel constructors.
3.3239 + callback(function (params /*, componentInfo */) {
3.3240 + return new viewModelConfig(params);
3.3241 + });
3.3242 + } else if (typeof viewModelConfig[createViewModelKey] === 'function') {
3.3243 + // Already a factory function - use it as-is
3.3244 + callback(viewModelConfig[createViewModelKey]);
3.3245 + } else if ('instance' in viewModelConfig) {
3.3246 + // Fixed object instance - promote to createViewModel format for API consistency
3.3247 + var fixedInstance = viewModelConfig['instance'];
3.3248 + callback(function (params, componentInfo) {
3.3249 + return fixedInstance;
3.3250 + });
3.3251 + } else if ('viewModel' in viewModelConfig) {
3.3252 + // Resolved AMD module whose value is of the form { viewModel: ... }
3.3253 + resolveViewModel(errorCallback, viewModelConfig['viewModel'], callback);
3.3254 + } else {
3.3255 + errorCallback('Unknown viewModel value: ' + viewModelConfig);
3.3256 + }
3.3257 + }
3.3258 +
3.3259 + function cloneNodesFromTemplateSourceElement(elemInstance) {
3.3260 + switch (ko.utils.tagNameLower(elemInstance)) {
3.3261 + case 'script':
3.3262 + return ko.utils.parseHtmlFragment(elemInstance.text);
3.3263 + case 'textarea':
3.3264 + return ko.utils.parseHtmlFragment(elemInstance.value);
3.3265 + case 'template':
3.3266 + // For browsers with proper <template> element support (i.e., where the .content property
3.3267 + // gives a document fragment), use that document fragment.
3.3268 + if (isDocumentFragment(elemInstance.content)) {
3.3269 + return ko.utils.cloneNodes(elemInstance.content.childNodes);
3.3270 + }
3.3271 + }
3.3272 +
3.3273 + // Regular elements such as <div>, and <template> elements on old browsers that don't really
3.3274 + // understand <template> and just treat it as a regular container
3.3275 + return ko.utils.cloneNodes(elemInstance.childNodes);
3.3276 + }
3.3277 +
3.3278 + function isDomElement(obj) {
3.3279 + if (window['HTMLElement']) {
3.3280 + return obj instanceof HTMLElement;
3.3281 + } else {
3.3282 + return obj && obj.tagName && obj.nodeType === 1;
3.3283 + }
3.3284 + }
3.3285 +
3.3286 + function isDocumentFragment(obj) {
3.3287 + if (window['DocumentFragment']) {
3.3288 + return obj instanceof DocumentFragment;
3.3289 + } else {
3.3290 + return obj && obj.nodeType === 11;
3.3291 + }
3.3292 + }
3.3293 +
3.3294 + function possiblyGetConfigFromAmd(errorCallback, config, callback) {
3.3295 + if (typeof config['require'] === 'string') {
3.3296 + // The config is the value of an AMD module
3.3297 + if (require || window['require']) {
3.3298 + (require || window['require'])([config['require']], callback);
3.3299 + } else {
3.3300 + errorCallback('Uses require, but no AMD loader is present');
3.3301 + }
3.3302 + } else {
3.3303 + callback(config);
3.3304 + }
3.3305 + }
3.3306 +
3.3307 + function makeErrorCallback(componentName) {
3.3308 + return function (message) {
3.3309 + throw new Error('Component \'' + componentName + '\': ' + message);
3.3310 + };
3.3311 + }
3.3312 +
3.3313 + ko.exportSymbol('components.register', ko.components.register);
3.3314 + ko.exportSymbol('components.isRegistered', ko.components.isRegistered);
3.3315 + ko.exportSymbol('components.unregister', ko.components.unregister);
3.3316 +
3.3317 + // Expose the default loader so that developers can directly ask it for configuration
3.3318 + // or to resolve configuration
3.3319 + ko.exportSymbol('components.defaultLoader', ko.components.defaultLoader);
3.3320 +
3.3321 + // By default, the default loader is the only registered component loader
3.3322 + ko.components['loaders'].push(ko.components.defaultLoader);
3.3323 +
3.3324 + // Privately expose the underlying config registry for use in old-IE shim
3.3325 + ko.components._allRegisteredComponents = defaultConfigRegistry;
3.3326 +})();
3.3327 +(function (undefined) {
3.3328 + // Overridable API for determining which component name applies to a given node. By overriding this,
3.3329 + // you can for example map specific tagNames to components that are not preregistered.
3.3330 + ko.components['getComponentNameForNode'] = function(node) {
3.3331 + var tagNameLower = ko.utils.tagNameLower(node);
3.3332 + return ko.components.isRegistered(tagNameLower) && tagNameLower;
3.3333 + };
3.3334 +
3.3335 + ko.components.addBindingsForCustomElement = function(allBindings, node, bindingContext, valueAccessors) {
3.3336 + // Determine if it's really a custom element matching a component
3.3337 + if (node.nodeType === 1) {
3.3338 + var componentName = ko.components['getComponentNameForNode'](node);
3.3339 + if (componentName) {
3.3340 + // It does represent a component, so add a component binding for it
3.3341 + allBindings = allBindings || {};
3.3342 +
3.3343 + if (allBindings['component']) {
3.3344 + // Avoid silently overwriting some other 'component' binding that may already be on the element
3.3345 + throw new Error('Cannot use the "component" binding on a custom element matching a component');
3.3346 + }
3.3347 +
3.3348 + var componentBindingValue = { 'name': componentName, 'params': getComponentParamsFromCustomElement(node, bindingContext) };
3.3349 +
3.3350 + allBindings['component'] = valueAccessors
3.3351 + ? function() { return componentBindingValue; }
3.3352 + : componentBindingValue;
3.3353 + }
3.3354 + }
3.3355 +
3.3356 + return allBindings;
3.3357 + }
3.3358 +
3.3359 + var nativeBindingProviderInstance = new ko.bindingProvider();
3.3360 +
3.3361 + function getComponentParamsFromCustomElement(elem, bindingContext) {
3.3362 + var paramsAttribute = elem.getAttribute('params');
3.3363 +
3.3364 + if (paramsAttribute) {
3.3365 + var params = nativeBindingProviderInstance['parseBindingsString'](paramsAttribute, bindingContext, elem, { 'valueAccessors': true, 'bindingParams': true }),
3.3366 + rawParamComputedValues = ko.utils.objectMap(params, function(paramValue, paramName) {
3.3367 + return ko.computed(paramValue, null, { disposeWhenNodeIsRemoved: elem });
3.3368 + }),
3.3369 + result = ko.utils.objectMap(rawParamComputedValues, function(paramValueComputed, paramName) {
3.3370 + // Does the evaluation of the parameter value unwrap any observables?
3.3371 + if (!paramValueComputed.isActive()) {
3.3372 + // No it doesn't, so there's no need for any computed wrapper. Just pass through the supplied value directly.
3.3373 + // Example: "someVal: firstName, age: 123" (whether or not firstName is an observable/computed)
3.3374 + return paramValueComputed.peek();
3.3375 + } else {
3.3376 + // Yes it does. Supply a computed property that unwraps both the outer (binding expression)
3.3377 + // level of observability, and any inner (resulting model value) level of observability.
3.3378 + // This means the component doesn't have to worry about multiple unwrapping.
3.3379 + return ko.computed(function() {
3.3380 + return ko.utils.unwrapObservable(paramValueComputed());
3.3381 + }, null, { disposeWhenNodeIsRemoved: elem });
3.3382 + }
3.3383 + });
3.3384 +
3.3385 + // Give access to the raw computeds, as long as that wouldn't overwrite any custom param also called '$raw'
3.3386 + // This is in case the developer wants to react to outer (binding) observability separately from inner
3.3387 + // (model value) observability, or in case the model value observable has subobservables.
3.3388 + if (!result.hasOwnProperty('$raw')) {
3.3389 + result['$raw'] = rawParamComputedValues;
3.3390 + }
3.3391 +
3.3392 + return result;
3.3393 + } else {
3.3394 + // For consistency, absence of a "params" attribute is treated the same as the presence of
3.3395 + // any empty one. Otherwise component viewmodels need special code to check whether or not
3.3396 + // 'params' or 'params.$raw' is null/undefined before reading subproperties, which is annoying.
3.3397 + return { '$raw': {} };
3.3398 + }
3.3399 + }
3.3400 +
3.3401 + // --------------------------------------------------------------------------------
3.3402 + // Compatibility code for older (pre-HTML5) IE browsers
3.3403 +
3.3404 + if (ko.utils.ieVersion < 9) {
3.3405 + // Whenever you preregister a component, enable it as a custom element in the current document
3.3406 + ko.components['register'] = (function(originalFunction) {
3.3407 + return function(componentName) {
3.3408 + document.createElement(componentName); // Allows IE<9 to parse markup containing the custom element
3.3409 + return originalFunction.apply(this, arguments);
3.3410 + }
3.3411 + })(ko.components['register']);
3.3412 +
3.3413 + // Whenever you create a document fragment, enable all preregistered component names as custom elements
3.3414 + // This is needed to make innerShiv/jQuery HTML parsing correctly handle the custom elements
3.3415 + document.createDocumentFragment = (function(originalFunction) {
3.3416 + return function() {
3.3417 + var newDocFrag = originalFunction(),
3.3418 + allComponents = ko.components._allRegisteredComponents;
3.3419 + for (var componentName in allComponents) {
3.3420 + if (allComponents.hasOwnProperty(componentName)) {
3.3421 + newDocFrag.createElement(componentName);
3.3422 + }
3.3423 + }
3.3424 + return newDocFrag;
3.3425 + };
3.3426 + })(document.createDocumentFragment);
3.3427 + }
3.3428 +})();(function(undefined) {
3.3429 +
3.3430 + var componentLoadingOperationUniqueId = 0;
3.3431 +
3.3432 + ko.bindingHandlers['component'] = {
3.3433 + 'init': function(element, valueAccessor, ignored1, ignored2, bindingContext) {
3.3434 + var currentViewModel,
3.3435 + currentLoadingOperationId,
3.3436 + disposeAssociatedComponentViewModel = function () {
3.3437 + var currentViewModelDispose = currentViewModel && currentViewModel['dispose'];
3.3438 + if (typeof currentViewModelDispose === 'function') {
3.3439 + currentViewModelDispose.call(currentViewModel);
3.3440 + }
3.3441 +
3.3442 + // Any in-flight loading operation is no longer relevant, so make sure we ignore its completion
3.3443 + currentLoadingOperationId = null;
3.3444 + };
3.3445 +
3.3446 + ko.utils.domNodeDisposal.addDisposeCallback(element, disposeAssociatedComponentViewModel);
3.3447 +
3.3448 + ko.computed(function () {
3.3449 + var value = ko.utils.unwrapObservable(valueAccessor()),
3.3450 + componentName, componentParams;
3.3451 +
3.3452 + if (typeof value === 'string') {
3.3453 + componentName = value;
3.3454 + } else {
3.3455 + componentName = ko.utils.unwrapObservable(value['name']);
3.3456 + componentParams = ko.utils.unwrapObservable(value['params']);
3.3457 + }
3.3458 +
3.3459 + if (!componentName) {
3.3460 + throw new Error('No component name specified');
3.3461 + }
3.3462 +
3.3463 + var loadingOperationId = currentLoadingOperationId = ++componentLoadingOperationUniqueId;
3.3464 + ko.components.get(componentName, function(componentDefinition) {
3.3465 + // If this is not the current load operation for this element, ignore it.
3.3466 + if (currentLoadingOperationId !== loadingOperationId) {
3.3467 + return;
3.3468 + }
3.3469 +
3.3470 + // Clean up previous state
3.3471 + disposeAssociatedComponentViewModel();
3.3472 +
3.3473 + // Instantiate and bind new component. Implicitly this cleans any old DOM nodes.
3.3474 + if (!componentDefinition) {
3.3475 + throw new Error('Unknown component \'' + componentName + '\'');
3.3476 + }
3.3477 + cloneTemplateIntoElement(componentName, componentDefinition, element);
3.3478 + var componentViewModel = createViewModel(componentDefinition, element, componentParams),
3.3479 + childBindingContext = bindingContext['createChildContext'](componentViewModel);
3.3480 + currentViewModel = componentViewModel;
3.3481 + ko.applyBindingsToDescendants(childBindingContext, element);
3.3482 + });
3.3483 + }, null, { disposeWhenNodeIsRemoved: element });
3.3484 +
3.3485 + return { 'controlsDescendantBindings': true };
3.3486 + }
3.3487 + };
3.3488 +
3.3489 + ko.virtualElements.allowedBindings['component'] = true;
3.3490 +
3.3491 + function cloneTemplateIntoElement(componentName, componentDefinition, element) {
3.3492 + var template = componentDefinition['template'];
3.3493 + if (!template) {
3.3494 + throw new Error('Component \'' + componentName + '\' has no template');
3.3495 + }
3.3496 +
3.3497 + var clonedNodesArray = ko.utils.cloneNodes(template);
3.3498 + ko.virtualElements.setDomNodeChildren(element, clonedNodesArray);
3.3499 + }
3.3500 +
3.3501 + function createViewModel(componentDefinition, element, componentParams) {
3.3502 + var componentViewModelFactory = componentDefinition['createViewModel'];
3.3503 + return componentViewModelFactory
3.3504 + ? componentViewModelFactory.call(componentDefinition, componentParams, { element: element })
3.3505 + : componentParams; // Template-only component
3.3506 + }
3.3507 +
3.3508 +})();
3.3509 +var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
3.3510 +ko.bindingHandlers['attr'] = {
3.3511 + 'update': function(element, valueAccessor, allBindings) {
3.3512 + var value = ko.utils.unwrapObservable(valueAccessor()) || {};
3.3513 + ko.utils.objectForEach(value, function(attrName, attrValue) {
3.3514 + attrValue = ko.utils.unwrapObservable(attrValue);
3.3515 +
3.3516 + // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
3.3517 + // when someProp is a "no value"-like value (strictly null, false, or undefined)
3.3518 + // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
3.3519 + var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
3.3520 + if (toRemove)
3.3521 + element.removeAttribute(attrName);
3.3522 +
3.3523 + // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
3.3524 + // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
3.3525 + // but instead of figuring out the mode, we'll just set the attribute through the Javascript
3.3526 + // property for IE <= 8.
3.3527 + if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
3.3528 + attrName = attrHtmlToJavascriptMap[attrName];
3.3529 + if (toRemove)
3.3530 + element.removeAttribute(attrName);
3.3531 + else
3.3532 + element[attrName] = attrValue;
3.3533 + } else if (!toRemove) {
3.3534 + element.setAttribute(attrName, attrValue.toString());
3.3535 + }
3.3536 +
3.3537 + // Treat "name" specially - although you can think of it as an attribute, it also needs
3.3538 + // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
3.3539 + // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
3.3540 + // entirely, and there's no strong reason to allow for such casing in HTML.
3.3541 + if (attrName === "name") {
3.3542 + ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
3.3543 + }
3.3544 + });
3.3545 + }
3.3546 +};
3.3547 +(function() {
3.3548 +
3.3549 +ko.bindingHandlers['checked'] = {
3.3550 + 'after': ['value', 'attr'],
3.3551 + 'init': function (element, valueAccessor, allBindings) {
3.3552 + var checkedValue = ko.pureComputed(function() {
3.3553 + // Treat "value" like "checkedValue" when it is included with "checked" binding
3.3554 + if (allBindings['has']('checkedValue')) {
3.3555 + return ko.utils.unwrapObservable(allBindings.get('checkedValue'));
3.3556 + } else if (allBindings['has']('value')) {
3.3557 + return ko.utils.unwrapObservable(allBindings.get('value'));
3.3558 + }
3.3559 +
3.3560 + return element.value;
3.3561 + });
3.3562 +
3.3563 + function updateModel() {
3.3564 + // This updates the model value from the view value.
3.3565 + // It runs in response to DOM events (click) and changes in checkedValue.
3.3566 + var isChecked = element.checked,
3.3567 + elemValue = useCheckedValue ? checkedValue() : isChecked;
3.3568 +
3.3569 + // When we're first setting up this computed, don't change any model state.
3.3570 + if (ko.computedContext.isInitial()) {
3.3571 + return;
3.3572 + }
3.3573 +
3.3574 + // We can ignore unchecked radio buttons, because some other radio
3.3575 + // button will be getting checked, and that one can take care of updating state.
3.3576 + if (isRadio && !isChecked) {
3.3577 + return;
3.3578 + }
3.3579 +
3.3580 + var modelValue = ko.dependencyDetection.ignore(valueAccessor);
3.3581 + if (isValueArray) {
3.3582 + if (oldElemValue !== elemValue) {
3.3583 + // When we're responding to the checkedValue changing, and the element is
3.3584 + // currently checked, replace the old elem value with the new elem value
3.3585 + // in the model array.
3.3586 + if (isChecked) {
3.3587 + ko.utils.addOrRemoveItem(modelValue, elemValue, true);
3.3588 + ko.utils.addOrRemoveItem(modelValue, oldElemValue, false);
3.3589 + }
3.3590 +
3.3591 + oldElemValue = elemValue;
3.3592 + } else {
3.3593 + // When we're responding to the user having checked/unchecked a checkbox,
3.3594 + // add/remove the element value to the model array.
3.3595 + ko.utils.addOrRemoveItem(modelValue, elemValue, isChecked);
3.3596 + }
3.3597 + } else {
3.3598 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'checked', elemValue, true);
3.3599 + }
3.3600 + };
3.3601 +
3.3602 + function updateView() {
3.3603 + // This updates the view value from the model value.
3.3604 + // It runs in response to changes in the bound (checked) value.
3.3605 + var modelValue = ko.utils.unwrapObservable(valueAccessor());
3.3606 +
3.3607 + if (isValueArray) {
3.3608 + // When a checkbox is bound to an array, being checked represents its value being present in that array
3.3609 + element.checked = ko.utils.arrayIndexOf(modelValue, checkedValue()) >= 0;
3.3610 + } else if (isCheckbox) {
3.3611 + // When a checkbox is bound to any other value (not an array), being checked represents the value being trueish
3.3612 + element.checked = modelValue;
3.3613 + } else {
3.3614 + // For radio buttons, being checked means that the radio button's value corresponds to the model value
3.3615 + element.checked = (checkedValue() === modelValue);
3.3616 + }
3.3617 + };
3.3618 +
3.3619 + var isCheckbox = element.type == "checkbox",
3.3620 + isRadio = element.type == "radio";
3.3621 +
3.3622 + // Only bind to check boxes and radio buttons
3.3623 + if (!isCheckbox && !isRadio) {
3.3624 + return;
3.3625 + }
3.3626 +
3.3627 + var isValueArray = isCheckbox && (ko.utils.unwrapObservable(valueAccessor()) instanceof Array),
3.3628 + oldElemValue = isValueArray ? checkedValue() : undefined,
3.3629 + useCheckedValue = isRadio || isValueArray;
3.3630 +
3.3631 + // IE 6 won't allow radio buttons to be selected unless they have a name
3.3632 + if (isRadio && !element.name)
3.3633 + ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
3.3634 +
3.3635 + // Set up two computeds to update the binding:
3.3636 +
3.3637 + // The first responds to changes in the checkedValue value and to element clicks
3.3638 + ko.computed(updateModel, null, { disposeWhenNodeIsRemoved: element });
3.3639 + ko.utils.registerEventHandler(element, "click", updateModel);
3.3640 +
3.3641 + // The second responds to changes in the model value (the one associated with the checked binding)
3.3642 + ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
3.3643 + }
3.3644 +};
3.3645 +ko.expressionRewriting.twoWayBindings['checked'] = true;
3.3646 +
3.3647 +ko.bindingHandlers['checkedValue'] = {
3.3648 + 'update': function (element, valueAccessor) {
3.3649 + element.value = ko.utils.unwrapObservable(valueAccessor());
3.3650 + }
3.3651 +};
3.3652 +
3.3653 +})();var classesWrittenByBindingKey = '__ko__cssValue';
3.3654 +ko.bindingHandlers['css'] = {
3.3655 + 'update': function (element, valueAccessor) {
3.3656 + var value = ko.utils.unwrapObservable(valueAccessor());
3.3657 + if (typeof value == "object") {
3.3658 + ko.utils.objectForEach(value, function(className, shouldHaveClass) {
3.3659 + shouldHaveClass = ko.utils.unwrapObservable(shouldHaveClass);
3.3660 + ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
3.3661 + });
3.3662 + } else {
3.3663 + value = String(value || ''); // Make sure we don't try to store or set a non-string value
3.3664 + ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
3.3665 + element[classesWrittenByBindingKey] = value;
3.3666 + ko.utils.toggleDomNodeCssClass(element, value, true);
3.3667 + }
3.3668 + }
3.3669 +};
3.3670 +ko.bindingHandlers['enable'] = {
3.3671 + 'update': function (element, valueAccessor) {
3.3672 + var value = ko.utils.unwrapObservable(valueAccessor());
3.3673 + if (value && element.disabled)
3.3674 + element.removeAttribute("disabled");
3.3675 + else if ((!value) && (!element.disabled))
3.3676 + element.disabled = true;
3.3677 + }
3.3678 +};
3.3679 +
3.3680 +ko.bindingHandlers['disable'] = {
3.3681 + 'update': function (element, valueAccessor) {
3.3682 + ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
3.3683 + }
3.3684 +};
3.3685 +// For certain common events (currently just 'click'), allow a simplified data-binding syntax
3.3686 +// e.g. click:handler instead of the usual full-length event:{click:handler}
3.3687 +function makeEventHandlerShortcut(eventName) {
3.3688 + ko.bindingHandlers[eventName] = {
3.3689 + 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
3.3690 + var newValueAccessor = function () {
3.3691 + var result = {};
3.3692 + result[eventName] = valueAccessor();
3.3693 + return result;
3.3694 + };
3.3695 + return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindings, viewModel, bindingContext);
3.3696 + }
3.3697 + }
3.3698 +}
3.3699 +
3.3700 +ko.bindingHandlers['event'] = {
3.3701 + 'init' : function (element, valueAccessor, allBindings, viewModel, bindingContext) {
3.3702 + var eventsToHandle = valueAccessor() || {};
3.3703 + ko.utils.objectForEach(eventsToHandle, function(eventName) {
3.3704 + if (typeof eventName == "string") {
3.3705 + ko.utils.registerEventHandler(element, eventName, function (event) {
3.3706 + var handlerReturnValue;
3.3707 + var handlerFunction = valueAccessor()[eventName];
3.3708 + if (!handlerFunction)
3.3709 + return;
3.3710 +
3.3711 + try {
3.3712 + // Take all the event args, and prefix with the viewmodel
3.3713 + var argsForHandler = ko.utils.makeArray(arguments);
3.3714 + viewModel = bindingContext['$data'];
3.3715 + argsForHandler.unshift(viewModel);
3.3716 + handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
3.3717 + } finally {
3.3718 + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
3.3719 + if (event.preventDefault)
3.3720 + event.preventDefault();
3.3721 + else
3.3722 + event.returnValue = false;
3.3723 + }
3.3724 + }
3.3725 +
3.3726 + var bubble = allBindings.get(eventName + 'Bubble') !== false;
3.3727 + if (!bubble) {
3.3728 + event.cancelBubble = true;
3.3729 + if (event.stopPropagation)
3.3730 + event.stopPropagation();
3.3731 + }
3.3732 + });
3.3733 + }
3.3734 + });
3.3735 + }
3.3736 +};
3.3737 +// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
3.3738 +// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
3.3739 +ko.bindingHandlers['foreach'] = {
3.3740 + makeTemplateValueAccessor: function(valueAccessor) {
3.3741 + return function() {
3.3742 + var modelValue = valueAccessor(),
3.3743 + unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
3.3744 +
3.3745 + // If unwrappedValue is the array, pass in the wrapped value on its own
3.3746 + // The value will be unwrapped and tracked within the template binding
3.3747 + // (See https://github.com/SteveSanderson/knockout/issues/523)
3.3748 + if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
3.3749 + return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
3.3750 +
3.3751 + // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
3.3752 + ko.utils.unwrapObservable(modelValue);
3.3753 + return {
3.3754 + 'foreach': unwrappedValue['data'],
3.3755 + 'as': unwrappedValue['as'],
3.3756 + 'includeDestroyed': unwrappedValue['includeDestroyed'],
3.3757 + 'afterAdd': unwrappedValue['afterAdd'],
3.3758 + 'beforeRemove': unwrappedValue['beforeRemove'],
3.3759 + 'afterRender': unwrappedValue['afterRender'],
3.3760 + 'beforeMove': unwrappedValue['beforeMove'],
3.3761 + 'afterMove': unwrappedValue['afterMove'],
3.3762 + 'templateEngine': ko.nativeTemplateEngine.instance
3.3763 + };
3.3764 + };
3.3765 + },
3.3766 + 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
3.3767 + return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
3.3768 + },
3.3769 + 'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
3.3770 + return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindings, viewModel, bindingContext);
3.3771 + }
3.3772 +};
3.3773 +ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
3.3774 +ko.virtualElements.allowedBindings['foreach'] = true;
3.3775 +var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
3.3776 +var hasfocusLastValue = '__ko_hasfocusLastValue';
3.3777 +ko.bindingHandlers['hasfocus'] = {
3.3778 + 'init': function(element, valueAccessor, allBindings) {
3.3779 + var handleElementFocusChange = function(isFocused) {
3.3780 + // Where possible, ignore which event was raised and determine focus state using activeElement,
3.3781 + // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
3.3782 + // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
3.3783 + // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
3.3784 + // from calling 'blur()' on the element when it loses focus.
3.3785 + // Discussion at https://github.com/SteveSanderson/knockout/pull/352
3.3786 + element[hasfocusUpdatingProperty] = true;
3.3787 + var ownerDoc = element.ownerDocument;
3.3788 + if ("activeElement" in ownerDoc) {
3.3789 + var active;
3.3790 + try {
3.3791 + active = ownerDoc.activeElement;
3.3792 + } catch(e) {
3.3793 + // IE9 throws if you access activeElement during page load (see issue #703)
3.3794 + active = ownerDoc.body;
3.3795 + }
3.3796 + isFocused = (active === element);
3.3797 + }
3.3798 + var modelValue = valueAccessor();
3.3799 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'hasfocus', isFocused, true);
3.3800 +
3.3801 + //cache the latest value, so we can avoid unnecessarily calling focus/blur in the update function
3.3802 + element[hasfocusLastValue] = isFocused;
3.3803 + element[hasfocusUpdatingProperty] = false;
3.3804 + };
3.3805 + var handleElementFocusIn = handleElementFocusChange.bind(null, true);
3.3806 + var handleElementFocusOut = handleElementFocusChange.bind(null, false);
3.3807 +
3.3808 + ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
3.3809 + ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
3.3810 + ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
3.3811 + ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
3.3812 + },
3.3813 + 'update': function(element, valueAccessor) {
3.3814 + var value = !!ko.utils.unwrapObservable(valueAccessor()); //force boolean to compare with last value
3.3815 + if (!element[hasfocusUpdatingProperty] && element[hasfocusLastValue] !== value) {
3.3816 + value ? element.focus() : element.blur();
3.3817 + ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
3.3818 + }
3.3819 + }
3.3820 +};
3.3821 +ko.expressionRewriting.twoWayBindings['hasfocus'] = true;
3.3822 +
3.3823 +ko.bindingHandlers['hasFocus'] = ko.bindingHandlers['hasfocus']; // Make "hasFocus" an alias
3.3824 +ko.expressionRewriting.twoWayBindings['hasFocus'] = true;
3.3825 +ko.bindingHandlers['html'] = {
3.3826 + 'init': function() {
3.3827 + // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
3.3828 + return { 'controlsDescendantBindings': true };
3.3829 + },
3.3830 + 'update': function (element, valueAccessor) {
3.3831 + // setHtml will unwrap the value if needed
3.3832 + ko.utils.setHtml(element, valueAccessor());
3.3833 + }
3.3834 +};
3.3835 +// Makes a binding like with or if
3.3836 +function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
3.3837 + ko.bindingHandlers[bindingKey] = {
3.3838 + 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
3.3839 + var didDisplayOnLastUpdate,
3.3840 + savedNodes;
3.3841 + ko.computed(function() {
3.3842 + var dataValue = ko.utils.unwrapObservable(valueAccessor()),
3.3843 + shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
3.3844 + isFirstRender = !savedNodes,
3.3845 + needsRefresh = isFirstRender || isWith || (shouldDisplay !== didDisplayOnLastUpdate);
3.3846 +
3.3847 + if (needsRefresh) {
3.3848 + // Save a copy of the inner nodes on the initial update, but only if we have dependencies.
3.3849 + if (isFirstRender && ko.computedContext.getDependenciesCount()) {
3.3850 + savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
3.3851 + }
3.3852 +
3.3853 + if (shouldDisplay) {
3.3854 + if (!isFirstRender) {
3.3855 + ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes));
3.3856 + }
3.3857 + ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
3.3858 + } else {
3.3859 + ko.virtualElements.emptyNode(element);
3.3860 + }
3.3861 +
3.3862 + didDisplayOnLastUpdate = shouldDisplay;
3.3863 + }
3.3864 + }, null, { disposeWhenNodeIsRemoved: element });
3.3865 + return { 'controlsDescendantBindings': true };
3.3866 + }
3.3867 + };
3.3868 + ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
3.3869 + ko.virtualElements.allowedBindings[bindingKey] = true;
3.3870 +}
3.3871 +
3.3872 +// Construct the actual binding handlers
3.3873 +makeWithIfBinding('if');
3.3874 +makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
3.3875 +makeWithIfBinding('with', true /* isWith */, false /* isNot */,
3.3876 + function(bindingContext, dataValue) {
3.3877 + return bindingContext['createChildContext'](dataValue);
3.3878 + }
3.3879 +);
3.3880 +var captionPlaceholder = {};
3.3881 +ko.bindingHandlers['options'] = {
3.3882 + 'init': function(element) {
3.3883 + if (ko.utils.tagNameLower(element) !== "select")
3.3884 + throw new Error("options binding applies only to SELECT elements");
3.3885 +
3.3886 + // Remove all existing <option>s.
3.3887 + while (element.length > 0) {
3.3888 + element.remove(0);
3.3889 + }
3.3890 +
3.3891 + // Ensures that the binding processor doesn't try to bind the options
3.3892 + return { 'controlsDescendantBindings': true };
3.3893 + },
3.3894 + 'update': function (element, valueAccessor, allBindings) {
3.3895 + function selectedOptions() {
3.3896 + return ko.utils.arrayFilter(element.options, function (node) { return node.selected; });
3.3897 + }
3.3898 +
3.3899 + var selectWasPreviouslyEmpty = element.length == 0;
3.3900 + var previousScrollTop = (!selectWasPreviouslyEmpty && element.multiple) ? element.scrollTop : null;
3.3901 + var unwrappedArray = ko.utils.unwrapObservable(valueAccessor());
3.3902 + var includeDestroyed = allBindings.get('optionsIncludeDestroyed');
3.3903 + var arrayToDomNodeChildrenOptions = {};
3.3904 + var captionValue;
3.3905 + var filteredArray;
3.3906 + var previousSelectedValues;
3.3907 +
3.3908 + if (element.multiple) {
3.3909 + previousSelectedValues = ko.utils.arrayMap(selectedOptions(), ko.selectExtensions.readValue);
3.3910 + } else {
3.3911 + previousSelectedValues = element.selectedIndex >= 0 ? [ ko.selectExtensions.readValue(element.options[element.selectedIndex]) ] : [];
3.3912 + }
3.3913 +
3.3914 + if (unwrappedArray) {
3.3915 + if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
3.3916 + unwrappedArray = [unwrappedArray];
3.3917 +
3.3918 + // Filter out any entries marked as destroyed
3.3919 + filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
3.3920 + return includeDestroyed || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
3.3921 + });
3.3922 +
3.3923 + // If caption is included, add it to the array
3.3924 + if (allBindings['has']('optionsCaption')) {
3.3925 + captionValue = ko.utils.unwrapObservable(allBindings.get('optionsCaption'));
3.3926 + // If caption value is null or undefined, don't show a caption
3.3927 + if (captionValue !== null && captionValue !== undefined) {
3.3928 + filteredArray.unshift(captionPlaceholder);
3.3929 + }
3.3930 + }
3.3931 + } else {
3.3932 + // If a falsy value is provided (e.g. null), we'll simply empty the select element
3.3933 + }
3.3934 +
3.3935 + function applyToObject(object, predicate, defaultValue) {
3.3936 + var predicateType = typeof predicate;
3.3937 + if (predicateType == "function") // Given a function; run it against the data value
3.3938 + return predicate(object);
3.3939 + else if (predicateType == "string") // Given a string; treat it as a property name on the data value
3.3940 + return object[predicate];
3.3941 + else // Given no optionsText arg; use the data value itself
3.3942 + return defaultValue;
3.3943 + }
3.3944 +
3.3945 + // The following functions can run at two different times:
3.3946 + // The first is when the whole array is being updated directly from this binding handler.
3.3947 + // The second is when an observable value for a specific array entry is updated.
3.3948 + // oldOptions will be empty in the first case, but will be filled with the previously generated option in the second.
3.3949 + var itemUpdate = false;
3.3950 + function optionForArrayItem(arrayEntry, index, oldOptions) {
3.3951 + if (oldOptions.length) {
3.3952 + previousSelectedValues = oldOptions[0].selected ? [ ko.selectExtensions.readValue(oldOptions[0]) ] : [];
3.3953 + itemUpdate = true;
3.3954 + }
3.3955 + var option = element.ownerDocument.createElement("option");
3.3956 + if (arrayEntry === captionPlaceholder) {
3.3957 + ko.utils.setTextContent(option, allBindings.get('optionsCaption'));
3.3958 + ko.selectExtensions.writeValue(option, undefined);
3.3959 + } else {
3.3960 + // Apply a value to the option element
3.3961 + var optionValue = applyToObject(arrayEntry, allBindings.get('optionsValue'), arrayEntry);
3.3962 + ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
3.3963 +
3.3964 + // Apply some text to the option element
3.3965 + var optionText = applyToObject(arrayEntry, allBindings.get('optionsText'), optionValue);
3.3966 + ko.utils.setTextContent(option, optionText);
3.3967 + }
3.3968 + return [option];
3.3969 + }
3.3970 +
3.3971 + // By using a beforeRemove callback, we delay the removal until after new items are added. This fixes a selection
3.3972 + // problem in IE<=8 and Firefox. See https://github.com/knockout/knockout/issues/1208
3.3973 + arrayToDomNodeChildrenOptions['beforeRemove'] =
3.3974 + function (option) {
3.3975 + element.removeChild(option);
3.3976 + };
3.3977 +
3.3978 + function setSelectionCallback(arrayEntry, newOptions) {
3.3979 + // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
3.3980 + // That's why we first added them without selection. Now it's time to set the selection.
3.3981 + if (previousSelectedValues.length) {
3.3982 + var isSelected = ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[0])) >= 0;
3.3983 + ko.utils.setOptionNodeSelectionState(newOptions[0], isSelected);
3.3984 +
3.3985 + // If this option was changed from being selected during a single-item update, notify the change
3.3986 + if (itemUpdate && !isSelected)
3.3987 + ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
3.3988 + }
3.3989 + }
3.3990 +
3.3991 + var callback = setSelectionCallback;
3.3992 + if (allBindings['has']('optionsAfterRender')) {
3.3993 + callback = function(arrayEntry, newOptions) {
3.3994 + setSelectionCallback(arrayEntry, newOptions);
3.3995 + ko.dependencyDetection.ignore(allBindings.get('optionsAfterRender'), null, [newOptions[0], arrayEntry !== captionPlaceholder ? arrayEntry : undefined]);
3.3996 + }
3.3997 + }
3.3998 +
3.3999 + ko.utils.setDomNodeChildrenFromArrayMapping(element, filteredArray, optionForArrayItem, arrayToDomNodeChildrenOptions, callback);
3.4000 +
3.4001 + ko.dependencyDetection.ignore(function () {
3.4002 + if (allBindings.get('valueAllowUnset') && allBindings['has']('value')) {
3.4003 + // The model value is authoritative, so make sure its value is the one selected
3.4004 + ko.selectExtensions.writeValue(element, ko.utils.unwrapObservable(allBindings.get('value')), true /* allowUnset */);
3.4005 + } else {
3.4006 + // Determine if the selection has changed as a result of updating the options list
3.4007 + var selectionChanged;
3.4008 + if (element.multiple) {
3.4009 + // For a multiple-select box, compare the new selection count to the previous one
3.4010 + // But if nothing was selected before, the selection can't have changed
3.4011 + selectionChanged = previousSelectedValues.length && selectedOptions().length < previousSelectedValues.length;
3.4012 + } else {
3.4013 + // For a single-select box, compare the current value to the previous value
3.4014 + // But if nothing was selected before or nothing is selected now, just look for a change in selection
3.4015 + selectionChanged = (previousSelectedValues.length && element.selectedIndex >= 0)
3.4016 + ? (ko.selectExtensions.readValue(element.options[element.selectedIndex]) !== previousSelectedValues[0])
3.4017 + : (previousSelectedValues.length || element.selectedIndex >= 0);
3.4018 + }
3.4019 +
3.4020 + // Ensure consistency between model value and selected option.
3.4021 + // If the dropdown was changed so that selection is no longer the same,
3.4022 + // notify the value or selectedOptions binding.
3.4023 + if (selectionChanged) {
3.4024 + ko.utils.triggerEvent(element, "change");
3.4025 + }
3.4026 + }
3.4027 + });
3.4028 +
3.4029 + // Workaround for IE bug
3.4030 + ko.utils.ensureSelectElementIsRenderedCorrectly(element);
3.4031 +
3.4032 + if (previousScrollTop && Math.abs(previousScrollTop - element.scrollTop) > 20)
3.4033 + element.scrollTop = previousScrollTop;
3.4034 + }
3.4035 +};
3.4036 +ko.bindingHandlers['options'].optionValueDomDataKey = ko.utils.domData.nextKey();
3.4037 +ko.bindingHandlers['selectedOptions'] = {
3.4038 + 'after': ['options', 'foreach'],
3.4039 + 'init': function (element, valueAccessor, allBindings) {
3.4040 + ko.utils.registerEventHandler(element, "change", function () {
3.4041 + var value = valueAccessor(), valueToWrite = [];
3.4042 + ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
3.4043 + if (node.selected)
3.4044 + valueToWrite.push(ko.selectExtensions.readValue(node));
3.4045 + });
3.4046 + ko.expressionRewriting.writeValueToProperty(value, allBindings, 'selectedOptions', valueToWrite);
3.4047 + });
3.4048 + },
3.4049 + 'update': function (element, valueAccessor) {
3.4050 + if (ko.utils.tagNameLower(element) != "select")
3.4051 + throw new Error("values binding applies only to SELECT elements");
3.4052 +
3.4053 + var newValue = ko.utils.unwrapObservable(valueAccessor());
3.4054 + if (newValue && typeof newValue.length == "number") {
3.4055 + ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
3.4056 + var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
3.4057 + ko.utils.setOptionNodeSelectionState(node, isSelected);
3.4058 + });
3.4059 + }
3.4060 + }
3.4061 +};
3.4062 +ko.expressionRewriting.twoWayBindings['selectedOptions'] = true;
3.4063 +ko.bindingHandlers['style'] = {
3.4064 + 'update': function (element, valueAccessor) {
3.4065 + var value = ko.utils.unwrapObservable(valueAccessor() || {});
3.4066 + ko.utils.objectForEach(value, function(styleName, styleValue) {
3.4067 + styleValue = ko.utils.unwrapObservable(styleValue);
3.4068 +
3.4069 + if (styleValue === null || styleValue === undefined || styleValue === false) {
3.4070 + // Empty string removes the value, whereas null/undefined have no effect
3.4071 + styleValue = "";
3.4072 + }
3.4073 +
3.4074 + element.style[styleName] = styleValue;
3.4075 + });
3.4076 + }
3.4077 +};
3.4078 +ko.bindingHandlers['submit'] = {
3.4079 + 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
3.4080 + if (typeof valueAccessor() != "function")
3.4081 + throw new Error("The value for a submit binding must be a function");
3.4082 + ko.utils.registerEventHandler(element, "submit", function (event) {
3.4083 + var handlerReturnValue;
3.4084 + var value = valueAccessor();
3.4085 + try { handlerReturnValue = value.call(bindingContext['$data'], element); }
3.4086 + finally {
3.4087 + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
3.4088 + if (event.preventDefault)
3.4089 + event.preventDefault();
3.4090 + else
3.4091 + event.returnValue = false;
3.4092 + }
3.4093 + }
3.4094 + });
3.4095 + }
3.4096 +};
3.4097 +ko.bindingHandlers['text'] = {
3.4098 + 'init': function() {
3.4099 + // Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications).
3.4100 + // It should also make things faster, as we no longer have to consider whether the text node might be bindable.
3.4101 + return { 'controlsDescendantBindings': true };
3.4102 + },
3.4103 + 'update': function (element, valueAccessor) {
3.4104 + ko.utils.setTextContent(element, valueAccessor());
3.4105 + }
3.4106 +};
3.4107 +ko.virtualElements.allowedBindings['text'] = true;
3.4108 +(function () {
3.4109 +
3.4110 +if (window && window.navigator) {
3.4111 + var parseVersion = function (matches) {
3.4112 + if (matches) {
3.4113 + return parseFloat(matches[1]);
3.4114 + }
3.4115 + };
3.4116 +
3.4117 + // Detect various browser versions because some old versions don't fully support the 'input' event
3.4118 + var operaVersion = window.opera && window.opera.version && parseInt(window.opera.version()),
3.4119 + userAgent = window.navigator.userAgent,
3.4120 + safariVersion = parseVersion(userAgent.match(/^(?:(?!chrome).)*version\/([^ ]*) safari/i)),
3.4121 + firefoxVersion = parseVersion(userAgent.match(/Firefox\/([^ ]*)/));
3.4122 +}
3.4123 +
3.4124 +// IE 8 and 9 have bugs that prevent the normal events from firing when the value changes.
3.4125 +// But it does fire the 'selectionchange' event on many of those, presumably because the
3.4126 +// cursor is moving and that counts as the selection changing. The 'selectionchange' event is
3.4127 +// fired at the document level only and doesn't directly indicate which element changed. We
3.4128 +// set up just one event handler for the document and use 'activeElement' to determine which
3.4129 +// element was changed.
3.4130 +if (ko.utils.ieVersion < 10) {
3.4131 + var selectionChangeRegisteredName = ko.utils.domData.nextKey(),
3.4132 + selectionChangeHandlerName = ko.utils.domData.nextKey();
3.4133 + var selectionChangeHandler = function(event) {
3.4134 + var target = this.activeElement,
3.4135 + handler = target && ko.utils.domData.get(target, selectionChangeHandlerName);
3.4136 + if (handler) {
3.4137 + handler(event);
3.4138 + }
3.4139 + };
3.4140 + var registerForSelectionChangeEvent = function (element, handler) {
3.4141 + var ownerDoc = element.ownerDocument;
3.4142 + if (!ko.utils.domData.get(ownerDoc, selectionChangeRegisteredName)) {
3.4143 + ko.utils.domData.set(ownerDoc, selectionChangeRegisteredName, true);
3.4144 + ko.utils.registerEventHandler(ownerDoc, 'selectionchange', selectionChangeHandler);
3.4145 + }
3.4146 + ko.utils.domData.set(element, selectionChangeHandlerName, handler);
3.4147 + };
3.4148 +}
3.4149 +
3.4150 +ko.bindingHandlers['textInput'] = {
3.4151 + 'init': function (element, valueAccessor, allBindings) {
3.4152 +
3.4153 + var previousElementValue = element.value,
3.4154 + timeoutHandle,
3.4155 + elementValueBeforeEvent;
3.4156 +
3.4157 + var updateModel = function (event) {
3.4158 + clearTimeout(timeoutHandle);
3.4159 + elementValueBeforeEvent = timeoutHandle = undefined;
3.4160 +
3.4161 + var elementValue = element.value;
3.4162 + if (previousElementValue !== elementValue) {
3.4163 + // Provide a way for tests to know exactly which event was processed
3.4164 + if (DEBUG && event) element['_ko_textInputProcessedEvent'] = event.type;
3.4165 + previousElementValue = elementValue;
3.4166 + ko.expressionRewriting.writeValueToProperty(valueAccessor(), allBindings, 'textInput', elementValue);
3.4167 + }
3.4168 + };
3.4169 +
3.4170 + var deferUpdateModel = function (event) {
3.4171 + if (!timeoutHandle) {
3.4172 + // The elementValueBeforeEvent variable is set *only* during the brief gap between an
3.4173 + // event firing and the updateModel function running. This allows us to ignore model
3.4174 + // updates that are from the previous state of the element, usually due to techniques
3.4175 + // such as rateLimit. Such updates, if not ignored, can cause keystrokes to be lost.
3.4176 + elementValueBeforeEvent = element.value;
3.4177 + var handler = DEBUG ? updateModel.bind(element, {type: event.type}) : updateModel;
3.4178 + timeoutHandle = setTimeout(handler, 4);
3.4179 + }
3.4180 + };
3.4181 +
3.4182 + var updateView = function () {
3.4183 + var modelValue = ko.utils.unwrapObservable(valueAccessor());
3.4184 +
3.4185 + if (modelValue === null || modelValue === undefined) {
3.4186 + modelValue = '';
3.4187 + }
3.4188 +
3.4189 + if (elementValueBeforeEvent !== undefined && modelValue === elementValueBeforeEvent) {
3.4190 + setTimeout(updateView, 4);
3.4191 + return;
3.4192 + }
3.4193 +
3.4194 + // Update the element only if the element and model are different. On some browsers, updating the value
3.4195 + // will move the cursor to the end of the input, which would be bad while the user is typing.
3.4196 + if (element.value !== modelValue) {
3.4197 + previousElementValue = modelValue; // Make sure we ignore events (propertychange) that result from updating the value
3.4198 + element.value = modelValue;
3.4199 + }
3.4200 + };
3.4201 +
3.4202 + var onEvent = function (event, handler) {
3.4203 + ko.utils.registerEventHandler(element, event, handler);
3.4204 + };
3.4205 +
3.4206 + if (DEBUG && ko.bindingHandlers['textInput']['_forceUpdateOn']) {
3.4207 + // Provide a way for tests to specify exactly which events are bound
3.4208 + ko.utils.arrayForEach(ko.bindingHandlers['textInput']['_forceUpdateOn'], function(eventName) {
3.4209 + if (eventName.slice(0,5) == 'after') {
3.4210 + onEvent(eventName.slice(5), deferUpdateModel);
3.4211 + } else {
3.4212 + onEvent(eventName, updateModel);
3.4213 + }
3.4214 + });
3.4215 + } else {
3.4216 + if (ko.utils.ieVersion < 10) {
3.4217 + // Internet Explorer <= 8 doesn't support the 'input' event, but does include 'propertychange' that fires whenever
3.4218 + // any property of an element changes. Unlike 'input', it also fires if a property is changed from JavaScript code,
3.4219 + // but that's an acceptable compromise for this binding. IE 9 does support 'input', but since it doesn't fire it
3.4220 + // when using autocomplete, we'll use 'propertychange' for it also.
3.4221 + onEvent('propertychange', function(event) {
3.4222 + if (event.propertyName === 'value') {
3.4223 + updateModel(event);
3.4224 + }
3.4225 + });
3.4226 +
3.4227 + if (ko.utils.ieVersion == 8) {
3.4228 + // IE 8 has a bug where it fails to fire 'propertychange' on the first update following a value change from
3.4229 + // JavaScript code. It also doesn't fire if you clear the entire value. To fix this, we bind to the following
3.4230 + // events too.
3.4231 + onEvent('keyup', updateModel); // A single keystoke
3.4232 + onEvent('keydown', updateModel); // The first character when a key is held down
3.4233 + }
3.4234 + if (ko.utils.ieVersion >= 8) {
3.4235 + // Internet Explorer 9 doesn't fire the 'input' event when deleting text, including using
3.4236 + // the backspace, delete, or ctrl-x keys, clicking the 'x' to clear the input, dragging text
3.4237 + // out of the field, and cutting or deleting text using the context menu. 'selectionchange'
3.4238 + // can detect all of those except dragging text out of the field, for which we use 'dragend'.
3.4239 + // These are also needed in IE8 because of the bug described above.
3.4240 + registerForSelectionChangeEvent(element, updateModel); // 'selectionchange' covers cut, paste, drop, delete, etc.
3.4241 + onEvent('dragend', deferUpdateModel);
3.4242 + }
3.4243 + } else {
3.4244 + // All other supported browsers support the 'input' event, which fires whenever the content of the element is changed
3.4245 + // through the user interface.
3.4246 + onEvent('input', updateModel);
3.4247 +
3.4248 + if (safariVersion < 5 && ko.utils.tagNameLower(element) === "textarea") {
3.4249 + // Safari <5 doesn't fire the 'input' event for <textarea> elements (it does fire 'textInput'
3.4250 + // but only when typing). So we'll just catch as much as we can with keydown, cut, and paste.
3.4251 + onEvent('keydown', deferUpdateModel);
3.4252 + onEvent('paste', deferUpdateModel);
3.4253 + onEvent('cut', deferUpdateModel);
3.4254 + } else if (operaVersion < 11) {
3.4255 + // Opera 10 doesn't always fire the 'input' event for cut, paste, undo & drop operations.
3.4256 + // We can try to catch some of those using 'keydown'.
3.4257 + onEvent('keydown', deferUpdateModel);
3.4258 + } else if (firefoxVersion < 4.0) {
3.4259 + // Firefox <= 3.6 doesn't fire the 'input' event when text is filled in through autocomplete
3.4260 + onEvent('DOMAutoComplete', updateModel);
3.4261 +
3.4262 + // Firefox <=3.5 doesn't fire the 'input' event when text is dropped into the input.
3.4263 + onEvent('dragdrop', updateModel); // <3.5
3.4264 + onEvent('drop', updateModel); // 3.5
3.4265 + }
3.4266 + }
3.4267 + }
3.4268 +
3.4269 + // Bind to the change event so that we can catch programmatic updates of the value that fire this event.
3.4270 + onEvent('change', updateModel);
3.4271 +
3.4272 + ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
3.4273 + }
3.4274 +};
3.4275 +ko.expressionRewriting.twoWayBindings['textInput'] = true;
3.4276 +
3.4277 +// textinput is an alias for textInput
3.4278 +ko.bindingHandlers['textinput'] = {
3.4279 + // preprocess is the only way to set up a full alias
3.4280 + 'preprocess': function (value, name, addBinding) {
3.4281 + addBinding('textInput', value);
3.4282 + }
3.4283 +};
3.4284 +
3.4285 +})();ko.bindingHandlers['uniqueName'] = {
3.4286 + 'init': function (element, valueAccessor) {
3.4287 + if (valueAccessor()) {
3.4288 + var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
3.4289 + ko.utils.setElementName(element, name);
3.4290 + }
3.4291 + }
3.4292 +};
3.4293 +ko.bindingHandlers['uniqueName'].currentIndex = 0;
3.4294 +ko.bindingHandlers['value'] = {
3.4295 + 'after': ['options', 'foreach'],
3.4296 + 'init': function (element, valueAccessor, allBindings) {
3.4297 + // If the value binding is placed on a radio/checkbox, then just pass through to checkedValue and quit
3.4298 + if (element.tagName.toLowerCase() == "input" && (element.type == "checkbox" || element.type == "radio")) {
3.4299 + ko.applyBindingAccessorsToNode(element, { 'checkedValue': valueAccessor });
3.4300 + return;
3.4301 + }
3.4302 +
3.4303 + // Always catch "change" event; possibly other events too if asked
3.4304 + var eventsToCatch = ["change"];
3.4305 + var requestedEventsToCatch = allBindings.get("valueUpdate");
3.4306 + var propertyChangedFired = false;
3.4307 + var elementValueBeforeEvent = null;
3.4308 +
3.4309 + if (requestedEventsToCatch) {
3.4310 + if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
3.4311 + requestedEventsToCatch = [requestedEventsToCatch];
3.4312 + ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
3.4313 + eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
3.4314 + }
3.4315 +
3.4316 + var valueUpdateHandler = function() {
3.4317 + elementValueBeforeEvent = null;
3.4318 + propertyChangedFired = false;
3.4319 + var modelValue = valueAccessor();
3.4320 + var elementValue = ko.selectExtensions.readValue(element);
3.4321 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'value', elementValue);
3.4322 + }
3.4323 +
3.4324 + // Workaround for https://github.com/SteveSanderson/knockout/issues/122
3.4325 + // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
3.4326 + var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
3.4327 + && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
3.4328 + if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
3.4329 + ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
3.4330 + ko.utils.registerEventHandler(element, "focus", function () { propertyChangedFired = false });
3.4331 + ko.utils.registerEventHandler(element, "blur", function() {
3.4332 + if (propertyChangedFired) {
3.4333 + valueUpdateHandler();
3.4334 + }
3.4335 + });
3.4336 + }
3.4337 +
3.4338 + ko.utils.arrayForEach(eventsToCatch, function(eventName) {
3.4339 + // The syntax "after<eventname>" means "run the handler asynchronously after the event"
3.4340 + // This is useful, for example, to catch "keydown" events after the browser has updated the control
3.4341 + // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
3.4342 + var handler = valueUpdateHandler;
3.4343 + if (ko.utils.stringStartsWith(eventName, "after")) {
3.4344 + handler = function() {
3.4345 + // The elementValueBeforeEvent variable is non-null *only* during the brief gap between
3.4346 + // a keyX event firing and the valueUpdateHandler running, which is scheduled to happen
3.4347 + // at the earliest asynchronous opportunity. We store this temporary information so that
3.4348 + // if, between keyX and valueUpdateHandler, the underlying model value changes separately,
3.4349 + // we can overwrite that model value change with the value the user just typed. Otherwise,
3.4350 + // techniques like rateLimit can trigger model changes at critical moments that will
3.4351 + // override the user's inputs, causing keystrokes to be lost.
3.4352 + elementValueBeforeEvent = ko.selectExtensions.readValue(element);
3.4353 + setTimeout(valueUpdateHandler, 0);
3.4354 + };
3.4355 + eventName = eventName.substring("after".length);
3.4356 + }
3.4357 + ko.utils.registerEventHandler(element, eventName, handler);
3.4358 + });
3.4359 +
3.4360 + var updateFromModel = function () {
3.4361 + var newValue = ko.utils.unwrapObservable(valueAccessor());
3.4362 + var elementValue = ko.selectExtensions.readValue(element);
3.4363 +
3.4364 + if (elementValueBeforeEvent !== null && newValue === elementValueBeforeEvent) {
3.4365 + setTimeout(updateFromModel, 0);
3.4366 + return;
3.4367 + }
3.4368 +
3.4369 + var valueHasChanged = (newValue !== elementValue);
3.4370 +
3.4371 + if (valueHasChanged) {
3.4372 + if (ko.utils.tagNameLower(element) === "select") {
3.4373 + var allowUnset = allBindings.get('valueAllowUnset');
3.4374 + var applyValueAction = function () {
3.4375 + ko.selectExtensions.writeValue(element, newValue, allowUnset);
3.4376 + };
3.4377 + applyValueAction();
3.4378 +
3.4379 + if (!allowUnset && newValue !== ko.selectExtensions.readValue(element)) {
3.4380 + // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
3.4381 + // because you're not allowed to have a model value that disagrees with a visible UI selection.
3.4382 + ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
3.4383 + } else {
3.4384 + // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
3.4385 + // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
3.4386 + // to apply the value as well.
3.4387 + setTimeout(applyValueAction, 0);
3.4388 + }
3.4389 + } else {
3.4390 + ko.selectExtensions.writeValue(element, newValue);
3.4391 + }
3.4392 + }
3.4393 + };
3.4394 +
3.4395 + ko.computed(updateFromModel, null, { disposeWhenNodeIsRemoved: element });
3.4396 + },
3.4397 + 'update': function() {} // Keep for backwards compatibility with code that may have wrapped value binding
3.4398 +};
3.4399 +ko.expressionRewriting.twoWayBindings['value'] = true;
3.4400 +ko.bindingHandlers['visible'] = {
3.4401 + 'update': function (element, valueAccessor) {
3.4402 + var value = ko.utils.unwrapObservable(valueAccessor());
3.4403 + var isCurrentlyVisible = !(element.style.display == "none");
3.4404 + if (value && !isCurrentlyVisible)
3.4405 + element.style.display = "";
3.4406 + else if ((!value) && isCurrentlyVisible)
3.4407 + element.style.display = "none";
3.4408 + }
3.4409 +};
3.4410 +// 'click' is just a shorthand for the usual full-length event:{click:handler}
3.4411 +makeEventHandlerShortcut('click');
3.4412 +// If you want to make a custom template engine,
3.4413 +//
3.4414 +// [1] Inherit from this class (like ko.nativeTemplateEngine does)
3.4415 +// [2] Override 'renderTemplateSource', supplying a function with this signature:
3.4416 +//
3.4417 +// function (templateSource, bindingContext, options) {
3.4418 +// // - templateSource.text() is the text of the template you should render
3.4419 +// // - bindingContext.$data is the data you should pass into the template
3.4420 +// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
3.4421 +// // and bindingContext.$root available in the template too
3.4422 +// // - options gives you access to any other properties set on "data-bind: { template: options }"
3.4423 +// //
3.4424 +// // Return value: an array of DOM nodes
3.4425 +// }
3.4426 +//
3.4427 +// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
3.4428 +//
3.4429 +// function (script) {
3.4430 +// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
3.4431 +// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
3.4432 +// }
3.4433 +//
3.4434 +// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
3.4435 +// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
3.4436 +// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
3.4437 +
3.4438 +ko.templateEngine = function () { };
3.4439 +
3.4440 +ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
3.4441 + throw new Error("Override renderTemplateSource");
3.4442 +};
3.4443 +
3.4444 +ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
3.4445 + throw new Error("Override createJavaScriptEvaluatorBlock");
3.4446 +};
3.4447 +
3.4448 +ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
3.4449 + // Named template
3.4450 + if (typeof template == "string") {
3.4451 + templateDocument = templateDocument || document;
3.4452 + var elem = templateDocument.getElementById(template);
3.4453 + if (!elem)
3.4454 + throw new Error("Cannot find template with ID " + template);
3.4455 + return new ko.templateSources.domElement(elem);
3.4456 + } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
3.4457 + // Anonymous template
3.4458 + return new ko.templateSources.anonymousTemplate(template);
3.4459 + } else
3.4460 + throw new Error("Unknown template type: " + template);
3.4461 +};
3.4462 +
3.4463 +ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
3.4464 + var templateSource = this['makeTemplateSource'](template, templateDocument);
3.4465 + return this['renderTemplateSource'](templateSource, bindingContext, options);
3.4466 +};
3.4467 +
3.4468 +ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
3.4469 + // Skip rewriting if requested
3.4470 + if (this['allowTemplateRewriting'] === false)
3.4471 + return true;
3.4472 + return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
3.4473 +};
3.4474 +
3.4475 +ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
3.4476 + var templateSource = this['makeTemplateSource'](template, templateDocument);
3.4477 + var rewritten = rewriterCallback(templateSource['text']());
3.4478 + templateSource['text'](rewritten);
3.4479 + templateSource['data']("isRewritten", true);
3.4480 +};
3.4481 +
3.4482 +ko.exportSymbol('templateEngine', ko.templateEngine);
3.4483 +
3.4484 +ko.templateRewriting = (function () {
3.4485 + var memoizeDataBindingAttributeSyntaxRegex = /(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi;
3.4486 + var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
3.4487 +
3.4488 + function validateDataBindValuesForRewriting(keyValueArray) {
3.4489 + var allValidators = ko.expressionRewriting.bindingRewriteValidators;
3.4490 + for (var i = 0; i < keyValueArray.length; i++) {
3.4491 + var key = keyValueArray[i]['key'];
3.4492 + if (allValidators.hasOwnProperty(key)) {
3.4493 + var validator = allValidators[key];
3.4494 +
3.4495 + if (typeof validator === "function") {
3.4496 + var possibleErrorMessage = validator(keyValueArray[i]['value']);
3.4497 + if (possibleErrorMessage)
3.4498 + throw new Error(possibleErrorMessage);
3.4499 + } else if (!validator) {
3.4500 + throw new Error("This template engine does not support the '" + key + "' binding within its templates");
3.4501 + }
3.4502 + }
3.4503 + }
3.4504 + }
3.4505 +
3.4506 + function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, nodeName, templateEngine) {
3.4507 + var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
3.4508 + validateDataBindValuesForRewriting(dataBindKeyValueArray);
3.4509 + var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray, {'valueAccessors':true});
3.4510 +
3.4511 + // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
3.4512 + // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
3.4513 + // extra indirection.
3.4514 + var applyBindingsToNextSiblingScript =
3.4515 + "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()},'" + nodeName.toLowerCase() + "')";
3.4516 + return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
3.4517 + }
3.4518 +
3.4519 + return {
3.4520 + ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
3.4521 + if (!templateEngine['isTemplateRewritten'](template, templateDocument))
3.4522 + templateEngine['rewriteTemplate'](template, function (htmlString) {
3.4523 + return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
3.4524 + }, templateDocument);
3.4525 + },
3.4526 +
3.4527 + memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
3.4528 + return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
3.4529 + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[4], /* tagToRetain: */ arguments[1], /* nodeName: */ arguments[2], templateEngine);
3.4530 + }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
3.4531 + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", /* nodeName: */ "#comment", templateEngine);
3.4532 + });
3.4533 + },
3.4534 +
3.4535 + applyMemoizedBindingsToNextSibling: function (bindings, nodeName) {
3.4536 + return ko.memoization.memoize(function (domNode, bindingContext) {
3.4537 + var nodeToBind = domNode.nextSibling;
3.4538 + if (nodeToBind && nodeToBind.nodeName.toLowerCase() === nodeName) {
3.4539 + ko.applyBindingAccessorsToNode(nodeToBind, bindings, bindingContext);
3.4540 + }
3.4541 + });
3.4542 + }
3.4543 + }
3.4544 +})();
3.4545 +
3.4546 +
3.4547 +// Exported only because it has to be referenced by string lookup from within rewritten template
3.4548 +ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
3.4549 +(function() {
3.4550 + // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
3.4551 + // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
3.4552 + //
3.4553 + // Two are provided by default:
3.4554 + // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
3.4555 + // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
3.4556 + // without reading/writing the actual element text content, since it will be overwritten
3.4557 + // with the rendered template output.
3.4558 + // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
3.4559 + // Template sources need to have the following functions:
3.4560 + // text() - returns the template text from your storage location
3.4561 + // text(value) - writes the supplied template text to your storage location
3.4562 + // data(key) - reads values stored using data(key, value) - see below
3.4563 + // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
3.4564 + //
3.4565 + // Optionally, template sources can also have the following functions:
3.4566 + // nodes() - returns a DOM element containing the nodes of this template, where available
3.4567 + // nodes(value) - writes the given DOM element to your storage location
3.4568 + // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
3.4569 + // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
3.4570 + //
3.4571 + // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
3.4572 + // using and overriding "makeTemplateSource" to return an instance of your custom template source.
3.4573 +
3.4574 + ko.templateSources = {};
3.4575 +
3.4576 + // ---- ko.templateSources.domElement -----
3.4577 +
3.4578 + ko.templateSources.domElement = function(element) {
3.4579 + this.domElement = element;
3.4580 + }
3.4581 +
3.4582 + ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
3.4583 + var tagNameLower = ko.utils.tagNameLower(this.domElement),
3.4584 + elemContentsProperty = tagNameLower === "script" ? "text"
3.4585 + : tagNameLower === "textarea" ? "value"
3.4586 + : "innerHTML";
3.4587 +
3.4588 + if (arguments.length == 0) {
3.4589 + return this.domElement[elemContentsProperty];
3.4590 + } else {
3.4591 + var valueToWrite = arguments[0];
3.4592 + if (elemContentsProperty === "innerHTML")
3.4593 + ko.utils.setHtml(this.domElement, valueToWrite);
3.4594 + else
3.4595 + this.domElement[elemContentsProperty] = valueToWrite;
3.4596 + }
3.4597 + };
3.4598 +
3.4599 + var dataDomDataPrefix = ko.utils.domData.nextKey() + "_";
3.4600 + ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
3.4601 + if (arguments.length === 1) {
3.4602 + return ko.utils.domData.get(this.domElement, dataDomDataPrefix + key);
3.4603 + } else {
3.4604 + ko.utils.domData.set(this.domElement, dataDomDataPrefix + key, arguments[1]);
3.4605 + }
3.4606 + };
3.4607 +
3.4608 + // ---- ko.templateSources.anonymousTemplate -----
3.4609 + // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
3.4610 + // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
3.4611 + // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
3.4612 +
3.4613 + var anonymousTemplatesDomDataKey = ko.utils.domData.nextKey();
3.4614 + ko.templateSources.anonymousTemplate = function(element) {
3.4615 + this.domElement = element;
3.4616 + }
3.4617 + ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
3.4618 + ko.templateSources.anonymousTemplate.prototype.constructor = ko.templateSources.anonymousTemplate;
3.4619 + ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
3.4620 + if (arguments.length == 0) {
3.4621 + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
3.4622 + if (templateData.textData === undefined && templateData.containerData)
3.4623 + templateData.textData = templateData.containerData.innerHTML;
3.4624 + return templateData.textData;
3.4625 + } else {
3.4626 + var valueToWrite = arguments[0];
3.4627 + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
3.4628 + }
3.4629 + };
3.4630 + ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
3.4631 + if (arguments.length == 0) {
3.4632 + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
3.4633 + return templateData.containerData;
3.4634 + } else {
3.4635 + var valueToWrite = arguments[0];
3.4636 + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
3.4637 + }
3.4638 + };
3.4639 +
3.4640 + ko.exportSymbol('templateSources', ko.templateSources);
3.4641 + ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
3.4642 + ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
3.4643 +})();
3.4644 +(function () {
3.4645 + var _templateEngine;
3.4646 + ko.setTemplateEngine = function (templateEngine) {
3.4647 + if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
3.4648 + throw new Error("templateEngine must inherit from ko.templateEngine");
3.4649 + _templateEngine = templateEngine;
3.4650 + }
3.4651 +
3.4652 + function invokeForEachNodeInContinuousRange(firstNode, lastNode, action) {
3.4653 + var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
3.4654 + while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
3.4655 + nextInQueue = ko.virtualElements.nextSibling(node);
3.4656 + action(node, nextInQueue);
3.4657 + }
3.4658 + }
3.4659 +
3.4660 + function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
3.4661 + // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
3.4662 + // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
3.4663 + // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
3.4664 + // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
3.4665 + // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
3.4666 +
3.4667 + if (continuousNodeArray.length) {
3.4668 + var firstNode = continuousNodeArray[0],
3.4669 + lastNode = continuousNodeArray[continuousNodeArray.length - 1],
3.4670 + parentNode = firstNode.parentNode,
3.4671 + provider = ko.bindingProvider['instance'],
3.4672 + preprocessNode = provider['preprocessNode'];
3.4673 +
3.4674 + if (preprocessNode) {
3.4675 + invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node, nextNodeInRange) {
3.4676 + var nodePreviousSibling = node.previousSibling;
3.4677 + var newNodes = preprocessNode.call(provider, node);
3.4678 + if (newNodes) {
3.4679 + if (node === firstNode)
3.4680 + firstNode = newNodes[0] || nextNodeInRange;
3.4681 + if (node === lastNode)
3.4682 + lastNode = newNodes[newNodes.length - 1] || nodePreviousSibling;
3.4683 + }
3.4684 + });
3.4685 +
3.4686 + // Because preprocessNode can change the nodes, including the first and last nodes, update continuousNodeArray to match.
3.4687 + // We need the full set, including inner nodes, because the unmemoize step might remove the first node (and so the real
3.4688 + // first node needs to be in the array).
3.4689 + continuousNodeArray.length = 0;
3.4690 + if (!firstNode) { // preprocessNode might have removed all the nodes, in which case there's nothing left to do
3.4691 + return;
3.4692 + }
3.4693 + if (firstNode === lastNode) {
3.4694 + continuousNodeArray.push(firstNode);
3.4695 + } else {
3.4696 + continuousNodeArray.push(firstNode, lastNode);
3.4697 + ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
3.4698 + }
3.4699 + }
3.4700 +
3.4701 + // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
3.4702 + // whereas a regular applyBindings won't introduce new memoized nodes
3.4703 + invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
3.4704 + if (node.nodeType === 1 || node.nodeType === 8)
3.4705 + ko.applyBindings(bindingContext, node);
3.4706 + });
3.4707 + invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
3.4708 + if (node.nodeType === 1 || node.nodeType === 8)
3.4709 + ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
3.4710 + });
3.4711 +
3.4712 + // Make sure any changes done by applyBindings or unmemoize are reflected in the array
3.4713 + ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
3.4714 + }
3.4715 + }
3.4716 +
3.4717 + function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
3.4718 + return nodeOrNodeArray.nodeType ? nodeOrNodeArray
3.4719 + : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
3.4720 + : null;
3.4721 + }
3.4722 +
3.4723 + function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
3.4724 + options = options || {};
3.4725 + var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
3.4726 + var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
3.4727 + var templateEngineToUse = (options['templateEngine'] || _templateEngine);
3.4728 + ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
3.4729 + var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
3.4730 +
3.4731 + // Loosely check result is an array of DOM nodes
3.4732 + if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
3.4733 + throw new Error("Template engine must return an array of DOM nodes");
3.4734 +
3.4735 + var haveAddedNodesToParent = false;
3.4736 + switch (renderMode) {
3.4737 + case "replaceChildren":
3.4738 + ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
3.4739 + haveAddedNodesToParent = true;
3.4740 + break;
3.4741 + case "replaceNode":
3.4742 + ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
3.4743 + haveAddedNodesToParent = true;
3.4744 + break;
3.4745 + case "ignoreTargetNode": break;
3.4746 + default:
3.4747 + throw new Error("Unknown renderMode: " + renderMode);
3.4748 + }
3.4749 +
3.4750 + if (haveAddedNodesToParent) {
3.4751 + activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
3.4752 + if (options['afterRender'])
3.4753 + ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
3.4754 + }
3.4755 +
3.4756 + return renderedNodesArray;
3.4757 + }
3.4758 +
3.4759 + function resolveTemplateName(template, data, context) {
3.4760 + // The template can be specified as:
3.4761 + if (ko.isObservable(template)) {
3.4762 + // 1. An observable, with string value
3.4763 + return template();
3.4764 + } else if (typeof template === 'function') {
3.4765 + // 2. A function of (data, context) returning a string
3.4766 + return template(data, context);
3.4767 + } else {
3.4768 + // 3. A string
3.4769 + return template;
3.4770 + }
3.4771 + }
3.4772 +
3.4773 + ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
3.4774 + options = options || {};
3.4775 + if ((options['templateEngine'] || _templateEngine) == undefined)
3.4776 + throw new Error("Set a template engine before calling renderTemplate");
3.4777 + renderMode = renderMode || "replaceChildren";
3.4778 +
3.4779 + if (targetNodeOrNodeArray) {
3.4780 + var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
3.4781 +
3.4782 + var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
3.4783 + var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
3.4784 +
3.4785 + return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
3.4786 + function () {
3.4787 + // Ensure we've got a proper binding context to work with
3.4788 + var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
3.4789 + ? dataOrBindingContext
3.4790 + : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
3.4791 +
3.4792 + var templateName = resolveTemplateName(template, bindingContext['$data'], bindingContext),
3.4793 + renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
3.4794 +
3.4795 + if (renderMode == "replaceNode") {
3.4796 + targetNodeOrNodeArray = renderedNodesArray;
3.4797 + firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
3.4798 + }
3.4799 + },
3.4800 + null,
3.4801 + { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
3.4802 + );
3.4803 + } else {
3.4804 + // 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
3.4805 + return ko.memoization.memoize(function (domNode) {
3.4806 + ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
3.4807 + });
3.4808 + }
3.4809 + };
3.4810 +
3.4811 + ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
3.4812 + // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
3.4813 + // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
3.4814 + var arrayItemContext;
3.4815 +
3.4816 + // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
3.4817 + var executeTemplateForArrayItem = function (arrayValue, index) {
3.4818 + // Support selecting template as a function of the data being rendered
3.4819 + arrayItemContext = parentBindingContext['createChildContext'](arrayValue, options['as'], function(context) {
3.4820 + context['$index'] = index;
3.4821 + });
3.4822 +
3.4823 + var templateName = resolveTemplateName(template, arrayValue, arrayItemContext);
3.4824 + return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
3.4825 + }
3.4826 +
3.4827 + // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
3.4828 + var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
3.4829 + activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
3.4830 + if (options['afterRender'])
3.4831 + options['afterRender'](addedNodesArray, arrayValue);
3.4832 + };
3.4833 +
3.4834 + return ko.dependentObservable(function () {
3.4835 + var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
3.4836 + if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
3.4837 + unwrappedArray = [unwrappedArray];
3.4838 +
3.4839 + // Filter out any entries marked as destroyed
3.4840 + var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
3.4841 + return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
3.4842 + });
3.4843 +
3.4844 + // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
3.4845 + // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
3.4846 + ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
3.4847 +
3.4848 + }, null, { disposeWhenNodeIsRemoved: targetNode });
3.4849 + };
3.4850 +
3.4851 + var templateComputedDomDataKey = ko.utils.domData.nextKey();
3.4852 + function disposeOldComputedAndStoreNewOne(element, newComputed) {
3.4853 + var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
3.4854 + if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
3.4855 + oldComputed.dispose();
3.4856 + ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
3.4857 + }
3.4858 +
3.4859 + ko.bindingHandlers['template'] = {
3.4860 + 'init': function(element, valueAccessor) {
3.4861 + // Support anonymous templates
3.4862 + var bindingValue = ko.utils.unwrapObservable(valueAccessor());
3.4863 + if (typeof bindingValue == "string" || bindingValue['name']) {
3.4864 + // It's a named template - clear the element
3.4865 + ko.virtualElements.emptyNode(element);
3.4866 + } else {
3.4867 + // It's an anonymous template - store the element contents, then clear the element
3.4868 + var templateNodes = ko.virtualElements.childNodes(element),
3.4869 + container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
3.4870 + new ko.templateSources.anonymousTemplate(element)['nodes'](container);
3.4871 + }
3.4872 + return { 'controlsDescendantBindings': true };
3.4873 + },
3.4874 + 'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
3.4875 + var value = valueAccessor(),
3.4876 + dataValue,
3.4877 + options = ko.utils.unwrapObservable(value),
3.4878 + shouldDisplay = true,
3.4879 + templateComputed = null,
3.4880 + templateName;
3.4881 +
3.4882 + if (typeof options == "string") {
3.4883 + templateName = value;
3.4884 + options = {};
3.4885 + } else {
3.4886 + templateName = options['name'];
3.4887 +
3.4888 + // Support "if"/"ifnot" conditions
3.4889 + if ('if' in options)
3.4890 + shouldDisplay = ko.utils.unwrapObservable(options['if']);
3.4891 + if (shouldDisplay && 'ifnot' in options)
3.4892 + shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
3.4893 +
3.4894 + dataValue = ko.utils.unwrapObservable(options['data']);
3.4895 + }
3.4896 +
3.4897 + if ('foreach' in options) {
3.4898 + // Render once for each data point (treating data set as empty if shouldDisplay==false)
3.4899 + var dataArray = (shouldDisplay && options['foreach']) || [];
3.4900 + templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
3.4901 + } else if (!shouldDisplay) {
3.4902 + ko.virtualElements.emptyNode(element);
3.4903 + } else {
3.4904 + // Render once for this single data point (or use the viewModel if no data was provided)
3.4905 + var innerBindingContext = ('data' in options) ?
3.4906 + bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
3.4907 + bindingContext; // Given no explicit 'data' value, we retain the same binding context
3.4908 + templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
3.4909 + }
3.4910 +
3.4911 + // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
3.4912 + disposeOldComputedAndStoreNewOne(element, templateComputed);
3.4913 + }
3.4914 + };
3.4915 +
3.4916 + // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
3.4917 + ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
3.4918 + var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
3.4919 +
3.4920 + if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
3.4921 + return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
3.4922 +
3.4923 + if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
3.4924 + return null; // Named templates can be rewritten, so return "no error"
3.4925 + return "This template engine does not support anonymous templates nested within its templates";
3.4926 + };
3.4927 +
3.4928 + ko.virtualElements.allowedBindings['template'] = true;
3.4929 +})();
3.4930 +
3.4931 +ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
3.4932 +ko.exportSymbol('renderTemplate', ko.renderTemplate);
3.4933 +// Go through the items that have been added and deleted and try to find matches between them.
3.4934 +ko.utils.findMovesInArrayComparison = function (left, right, limitFailedCompares) {
3.4935 + if (left.length && right.length) {
3.4936 + var failedCompares, l, r, leftItem, rightItem;
3.4937 + for (failedCompares = l = 0; (!limitFailedCompares || failedCompares < limitFailedCompares) && (leftItem = left[l]); ++l) {
3.4938 + for (r = 0; rightItem = right[r]; ++r) {
3.4939 + if (leftItem['value'] === rightItem['value']) {
3.4940 + leftItem['moved'] = rightItem['index'];
3.4941 + rightItem['moved'] = leftItem['index'];
3.4942 + right.splice(r, 1); // This item is marked as moved; so remove it from right list
3.4943 + failedCompares = r = 0; // Reset failed compares count because we're checking for consecutive failures
3.4944 + break;
3.4945 + }
3.4946 + }
3.4947 + failedCompares += r;
3.4948 + }
3.4949 + }
3.4950 +};
3.4951 +
3.4952 +ko.utils.compareArrays = (function () {
3.4953 + var statusNotInOld = 'added', statusNotInNew = 'deleted';
3.4954 +
3.4955 + // Simple calculation based on Levenshtein distance.
3.4956 + function compareArrays(oldArray, newArray, options) {
3.4957 + // For backward compatibility, if the third arg is actually a bool, interpret
3.4958 + // it as the old parameter 'dontLimitMoves'. Newer code should use { dontLimitMoves: true }.
3.4959 + options = (typeof options === 'boolean') ? { 'dontLimitMoves': options } : (options || {});
3.4960 + oldArray = oldArray || [];
3.4961 + newArray = newArray || [];
3.4962 +
3.4963 + if (oldArray.length <= newArray.length)
3.4964 + return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, options);
3.4965 + else
3.4966 + return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, options);
3.4967 + }
3.4968 +
3.4969 + function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, options) {
3.4970 + var myMin = Math.min,
3.4971 + myMax = Math.max,
3.4972 + editDistanceMatrix = [],
3.4973 + smlIndex, smlIndexMax = smlArray.length,
3.4974 + bigIndex, bigIndexMax = bigArray.length,
3.4975 + compareRange = (bigIndexMax - smlIndexMax) || 1,
3.4976 + maxDistance = smlIndexMax + bigIndexMax + 1,
3.4977 + thisRow, lastRow,
3.4978 + bigIndexMaxForRow, bigIndexMinForRow;
3.4979 +
3.4980 + for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
3.4981 + lastRow = thisRow;
3.4982 + editDistanceMatrix.push(thisRow = []);
3.4983 + bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
3.4984 + bigIndexMinForRow = myMax(0, smlIndex - 1);
3.4985 + for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
3.4986 + if (!bigIndex)
3.4987 + thisRow[bigIndex] = smlIndex + 1;
3.4988 + else if (!smlIndex) // Top row - transform empty array into new array via additions
3.4989 + thisRow[bigIndex] = bigIndex + 1;
3.4990 + else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
3.4991 + thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
3.4992 + else {
3.4993 + var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
3.4994 + var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
3.4995 + thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
3.4996 + }
3.4997 + }
3.4998 + }
3.4999 +
3.5000 + var editScript = [], meMinusOne, notInSml = [], notInBig = [];
3.5001 + for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
3.5002 + meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
3.5003 + if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
3.5004 + notInSml.push(editScript[editScript.length] = { // added
3.5005 + 'status': statusNotInSml,
3.5006 + 'value': bigArray[--bigIndex],
3.5007 + 'index': bigIndex });
3.5008 + } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
3.5009 + notInBig.push(editScript[editScript.length] = { // deleted
3.5010 + 'status': statusNotInBig,
3.5011 + 'value': smlArray[--smlIndex],
3.5012 + 'index': smlIndex });
3.5013 + } else {
3.5014 + --bigIndex;
3.5015 + --smlIndex;
3.5016 + if (!options['sparse']) {
3.5017 + editScript.push({
3.5018 + 'status': "retained",
3.5019 + 'value': bigArray[bigIndex] });
3.5020 + }
3.5021 + }
3.5022 + }
3.5023 +
3.5024 + // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
3.5025 + // smlIndexMax keeps the time complexity of this algorithm linear.
3.5026 + ko.utils.findMovesInArrayComparison(notInSml, notInBig, smlIndexMax * 10);
3.5027 +
3.5028 + return editScript.reverse();
3.5029 + }
3.5030 +
3.5031 + return compareArrays;
3.5032 +})();
3.5033 +
3.5034 +ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
3.5035 +(function () {
3.5036 + // Objective:
3.5037 + // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
3.5038 + // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
3.5039 + // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
3.5040 + // 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
3.5041 + // previously mapped - retain those nodes, and just insert/delete other ones
3.5042 +
3.5043 + // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
3.5044 + // You can use this, for example, to activate bindings on those nodes.
3.5045 +
3.5046 + function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
3.5047 + // Map this array value inside a dependentObservable so we re-map when any dependency changes
3.5048 + var mappedNodes = [];
3.5049 + var dependentObservable = ko.dependentObservable(function() {
3.5050 + var newMappedNodes = mapping(valueToMap, index, ko.utils.fixUpContinuousNodeArray(mappedNodes, containerNode)) || [];
3.5051 +
3.5052 + // On subsequent evaluations, just replace the previously-inserted DOM nodes
3.5053 + if (mappedNodes.length > 0) {
3.5054 + ko.utils.replaceDomNodes(mappedNodes, newMappedNodes);
3.5055 + if (callbackAfterAddingNodes)
3.5056 + ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
3.5057 + }
3.5058 +
3.5059 + // Replace the contents of the mappedNodes array, thereby updating the record
3.5060 + // of which nodes would be deleted if valueToMap was itself later removed
3.5061 + mappedNodes.length = 0;
3.5062 + ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
3.5063 + }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return !ko.utils.anyDomNodeIsAttachedToDocument(mappedNodes); } });
3.5064 + return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
3.5065 + }
3.5066 +
3.5067 + var lastMappingResultDomDataKey = ko.utils.domData.nextKey();
3.5068 +
3.5069 + ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
3.5070 + // Compare the provided array against the previous one
3.5071 + array = array || [];
3.5072 + options = options || {};
3.5073 + var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
3.5074 + var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
3.5075 + var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
3.5076 + var editScript = ko.utils.compareArrays(lastArray, array, options['dontLimitMoves']);
3.5077 +
3.5078 + // Build the new mapping result
3.5079 + var newMappingResult = [];
3.5080 + var lastMappingResultIndex = 0;
3.5081 + var newMappingResultIndex = 0;
3.5082 +
3.5083 + var nodesToDelete = [];
3.5084 + var itemsToProcess = [];
3.5085 + var itemsForBeforeRemoveCallbacks = [];
3.5086 + var itemsForMoveCallbacks = [];
3.5087 + var itemsForAfterAddCallbacks = [];
3.5088 + var mapData;
3.5089 +
3.5090 + function itemMovedOrRetained(editScriptIndex, oldPosition) {
3.5091 + mapData = lastMappingResult[oldPosition];
3.5092 + if (newMappingResultIndex !== oldPosition)
3.5093 + itemsForMoveCallbacks[editScriptIndex] = mapData;
3.5094 + // Since updating the index might change the nodes, do so before calling fixUpContinuousNodeArray
3.5095 + mapData.indexObservable(newMappingResultIndex++);
3.5096 + ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode);
3.5097 + newMappingResult.push(mapData);
3.5098 + itemsToProcess.push(mapData);
3.5099 + }
3.5100 +
3.5101 + function callCallback(callback, items) {
3.5102 + if (callback) {
3.5103 + for (var i = 0, n = items.length; i < n; i++) {
3.5104 + if (items[i]) {
3.5105 + ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
3.5106 + callback(node, i, items[i].arrayEntry);
3.5107 + });
3.5108 + }
3.5109 + }
3.5110 + }
3.5111 + }
3.5112 +
3.5113 + for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
3.5114 + movedIndex = editScriptItem['moved'];
3.5115 + switch (editScriptItem['status']) {
3.5116 + case "deleted":
3.5117 + if (movedIndex === undefined) {
3.5118 + mapData = lastMappingResult[lastMappingResultIndex];
3.5119 +
3.5120 + // Stop tracking changes to the mapping for these nodes
3.5121 + if (mapData.dependentObservable)
3.5122 + mapData.dependentObservable.dispose();
3.5123 +
3.5124 + // Queue these nodes for later removal
3.5125 + nodesToDelete.push.apply(nodesToDelete, ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode));
3.5126 + if (options['beforeRemove']) {
3.5127 + itemsForBeforeRemoveCallbacks[i] = mapData;
3.5128 + itemsToProcess.push(mapData);
3.5129 + }
3.5130 + }
3.5131 + lastMappingResultIndex++;
3.5132 + break;
3.5133 +
3.5134 + case "retained":
3.5135 + itemMovedOrRetained(i, lastMappingResultIndex++);
3.5136 + break;
3.5137 +
3.5138 + case "added":
3.5139 + if (movedIndex !== undefined) {
3.5140 + itemMovedOrRetained(i, movedIndex);
3.5141 + } else {
3.5142 + mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
3.5143 + newMappingResult.push(mapData);
3.5144 + itemsToProcess.push(mapData);
3.5145 + if (!isFirstExecution)
3.5146 + itemsForAfterAddCallbacks[i] = mapData;
3.5147 + }
3.5148 + break;
3.5149 + }
3.5150 + }
3.5151 +
3.5152 + // Call beforeMove first before any changes have been made to the DOM
3.5153 + callCallback(options['beforeMove'], itemsForMoveCallbacks);
3.5154 +
3.5155 + // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
3.5156 + ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
3.5157 +
3.5158 + // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
3.5159 + for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
3.5160 + // Get nodes for newly added items
3.5161 + if (!mapData.mappedNodes)
3.5162 + ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
3.5163 +
3.5164 + // Put nodes in the right place if they aren't there already
3.5165 + for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
3.5166 + if (node !== nextNode)
3.5167 + ko.virtualElements.insertAfter(domNode, node, lastNode);
3.5168 + }
3.5169 +
3.5170 + // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
3.5171 + if (!mapData.initialized && callbackAfterAddingNodes) {
3.5172 + callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
3.5173 + mapData.initialized = true;
3.5174 + }
3.5175 + }
3.5176 +
3.5177 + // If there's a beforeRemove callback, call it after reordering.
3.5178 + // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
3.5179 + // some sort of animation, which is why we first reorder the nodes that will be removed. If the
3.5180 + // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
3.5181 + // Perhaps we'll make that change in the future if this scenario becomes more common.
3.5182 + callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
3.5183 +
3.5184 + // Finally call afterMove and afterAdd callbacks
3.5185 + callCallback(options['afterMove'], itemsForMoveCallbacks);
3.5186 + callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
3.5187 +
3.5188 + // Store a copy of the array items we just considered so we can difference it next time
3.5189 + ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
3.5190 + }
3.5191 +})();
3.5192 +
3.5193 +ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
3.5194 +ko.nativeTemplateEngine = function () {
3.5195 + this['allowTemplateRewriting'] = false;
3.5196 +}
3.5197 +
3.5198 +ko.nativeTemplateEngine.prototype = new ko.templateEngine();
3.5199 +ko.nativeTemplateEngine.prototype.constructor = ko.nativeTemplateEngine;
3.5200 +ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
3.5201 + var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
3.5202 + templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
3.5203 + templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
3.5204 +
3.5205 + if (templateNodes) {
3.5206 + return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
3.5207 + } else {
3.5208 + var templateText = templateSource['text']();
3.5209 + return ko.utils.parseHtmlFragment(templateText);
3.5210 + }
3.5211 +};
3.5212 +
3.5213 +ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
3.5214 +ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
3.5215 +
3.5216 +ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
3.5217 +(function() {
3.5218 + ko.jqueryTmplTemplateEngine = function () {
3.5219 + // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
3.5220 + // doesn't expose a version number, so we have to infer it.
3.5221 + // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
3.5222 + // which KO internally refers to as version "2", so older versions are no longer detected.
3.5223 + var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
3.5224 + if (!jQueryInstance || !(jQueryInstance['tmpl']))
3.5225 + return 0;
3.5226 + // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
3.5227 + try {
3.5228 + if (jQueryInstance['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
3.5229 + // Since 1.0.0pre, custom tags should append markup to an array called "__"
3.5230 + return 2; // Final version of jquery.tmpl
3.5231 + }
3.5232 + } catch(ex) { /* Apparently not the version we were looking for */ }
3.5233 +
3.5234 + return 1; // Any older version that we don't support
3.5235 + })();
3.5236 +
3.5237 + function ensureHasReferencedJQueryTemplates() {
3.5238 + if (jQueryTmplVersion < 2)
3.5239 + throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
3.5240 + }
3.5241 +
3.5242 + function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
3.5243 + return jQueryInstance['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
3.5244 + }
3.5245 +
3.5246 + this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
3.5247 + options = options || {};
3.5248 + ensureHasReferencedJQueryTemplates();
3.5249 +
3.5250 + // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
3.5251 + var precompiled = templateSource['data']('precompiled');
3.5252 + if (!precompiled) {
3.5253 + var templateText = templateSource['text']() || "";
3.5254 + // Wrap in "with($whatever.koBindingContext) { ... }"
3.5255 + templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
3.5256 +
3.5257 + precompiled = jQueryInstance['template'](null, templateText);
3.5258 + templateSource['data']('precompiled', precompiled);
3.5259 + }
3.5260 +
3.5261 + var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
3.5262 + var jQueryTemplateOptions = jQueryInstance['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
3.5263 +
3.5264 + var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
3.5265 + resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
3.5266 +
3.5267 + jQueryInstance['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
3.5268 + return resultNodes;
3.5269 + };
3.5270 +
3.5271 + this['createJavaScriptEvaluatorBlock'] = function(script) {
3.5272 + return "{{ko_code ((function() { return " + script + " })()) }}";
3.5273 + };
3.5274 +
3.5275 + this['addTemplate'] = function(templateName, templateMarkup) {
3.5276 + document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "<" + "/script>");
3.5277 + };
3.5278 +
3.5279 + if (jQueryTmplVersion > 0) {
3.5280 + jQueryInstance['tmpl']['tag']['ko_code'] = {
3.5281 + open: "__.push($1 || '');"
3.5282 + };
3.5283 + jQueryInstance['tmpl']['tag']['ko_with'] = {
3.5284 + open: "with($1) {",
3.5285 + close: "} "
3.5286 + };
3.5287 + }
3.5288 + };
3.5289 +
3.5290 + ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
3.5291 + ko.jqueryTmplTemplateEngine.prototype.constructor = ko.jqueryTmplTemplateEngine;
3.5292 +
3.5293 + // Use this one by default *only if jquery.tmpl is referenced*
3.5294 + var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
3.5295 + if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
3.5296 + ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
3.5297 +
3.5298 + ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
3.5299 +})();
3.5300 +}));
3.5301 +}());
3.5302 +})();