1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/Resources/Web/js/knockout-2.1.0.js Sun May 27 20:15:32 2012 +0000
1.3 @@ -0,0 +1,3443 @@
1.4 +// Knockout JavaScript library v2.1.0
1.5 +// (c) Steven Sanderson - http://knockoutjs.com/
1.6 +// License: MIT (http://www.opensource.org/licenses/mit-license.php)
1.7 +
1.8 +(function(window,document,navigator,undefined){
1.9 +var DEBUG=true;
1.10 +!function(factory) {
1.11 + // Support three module loading scenarios
1.12 + if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
1.13 + // [1] CommonJS/Node.js
1.14 + var target = module['exports'] || exports; // module.exports is for Node.js
1.15 + factory(target);
1.16 + } else if (typeof define === 'function' && define['amd']) {
1.17 + // [2] AMD anonymous module
1.18 + define(['exports'], factory);
1.19 + } else {
1.20 + // [3] No module loader (plain <script> tag) - put directly in global namespace
1.21 + factory(window['ko'] = {});
1.22 + }
1.23 +}(function(koExports){
1.24 +// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
1.25 +// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
1.26 +var ko = typeof koExports !== 'undefined' ? koExports : {};
1.27 +// Google Closure Compiler helpers (used only to make the minified file smaller)
1.28 +ko.exportSymbol = function(koPath, object) {
1.29 + var tokens = koPath.split(".");
1.30 +
1.31 + // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
1.32 + // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
1.33 + var target = ko;
1.34 +
1.35 + for (var i = 0; i < tokens.length - 1; i++)
1.36 + target = target[tokens[i]];
1.37 + target[tokens[tokens.length - 1]] = object;
1.38 +};
1.39 +ko.exportProperty = function(owner, publicName, object) {
1.40 + owner[publicName] = object;
1.41 +};
1.42 +ko.version = "2.1.0";
1.43 +
1.44 +ko.exportSymbol('version', ko.version);
1.45 +ko.utils = new (function () {
1.46 + var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
1.47 +
1.48 + // Represent the known event types in a compact way, then at runtime transform it into a hash with event name as key (for fast lookup)
1.49 + var knownEvents = {}, knownEventTypesByEventName = {};
1.50 + var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';
1.51 + knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
1.52 + knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
1.53 + for (var eventType in knownEvents) {
1.54 + var knownEventsForType = knownEvents[eventType];
1.55 + if (knownEventsForType.length) {
1.56 + for (var i = 0, j = knownEventsForType.length; i < j; i++)
1.57 + knownEventTypesByEventName[knownEventsForType[i]] = eventType;
1.58 + }
1.59 + }
1.60 + var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
1.61 +
1.62 + // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
1.63 + var ieVersion = (function() {
1.64 + var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
1.65 +
1.66 + // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
1.67 + while (
1.68 + div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
1.69 + iElems[0]
1.70 + );
1.71 + return version > 4 ? version : undefined;
1.72 + }());
1.73 + var isIe6 = ieVersion === 6,
1.74 + isIe7 = ieVersion === 7;
1.75 +
1.76 + function isClickOnCheckableElement(element, eventType) {
1.77 + if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
1.78 + if (eventType.toLowerCase() != "click") return false;
1.79 + var inputType = element.type;
1.80 + return (inputType == "checkbox") || (inputType == "radio");
1.81 + }
1.82 +
1.83 + return {
1.84 + fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
1.85 +
1.86 + arrayForEach: function (array, action) {
1.87 + for (var i = 0, j = array.length; i < j; i++)
1.88 + action(array[i]);
1.89 + },
1.90 +
1.91 + arrayIndexOf: function (array, item) {
1.92 + if (typeof Array.prototype.indexOf == "function")
1.93 + return Array.prototype.indexOf.call(array, item);
1.94 + for (var i = 0, j = array.length; i < j; i++)
1.95 + if (array[i] === item)
1.96 + return i;
1.97 + return -1;
1.98 + },
1.99 +
1.100 + arrayFirst: function (array, predicate, predicateOwner) {
1.101 + for (var i = 0, j = array.length; i < j; i++)
1.102 + if (predicate.call(predicateOwner, array[i]))
1.103 + return array[i];
1.104 + return null;
1.105 + },
1.106 +
1.107 + arrayRemoveItem: function (array, itemToRemove) {
1.108 + var index = ko.utils.arrayIndexOf(array, itemToRemove);
1.109 + if (index >= 0)
1.110 + array.splice(index, 1);
1.111 + },
1.112 +
1.113 + arrayGetDistinctValues: function (array) {
1.114 + array = array || [];
1.115 + var result = [];
1.116 + for (var i = 0, j = array.length; i < j; i++) {
1.117 + if (ko.utils.arrayIndexOf(result, array[i]) < 0)
1.118 + result.push(array[i]);
1.119 + }
1.120 + return result;
1.121 + },
1.122 +
1.123 + arrayMap: function (array, mapping) {
1.124 + array = array || [];
1.125 + var result = [];
1.126 + for (var i = 0, j = array.length; i < j; i++)
1.127 + result.push(mapping(array[i]));
1.128 + return result;
1.129 + },
1.130 +
1.131 + arrayFilter: function (array, predicate) {
1.132 + array = array || [];
1.133 + var result = [];
1.134 + for (var i = 0, j = array.length; i < j; i++)
1.135 + if (predicate(array[i]))
1.136 + result.push(array[i]);
1.137 + return result;
1.138 + },
1.139 +
1.140 + arrayPushAll: function (array, valuesToPush) {
1.141 + if (valuesToPush instanceof Array)
1.142 + array.push.apply(array, valuesToPush);
1.143 + else
1.144 + for (var i = 0, j = valuesToPush.length; i < j; i++)
1.145 + array.push(valuesToPush[i]);
1.146 + return array;
1.147 + },
1.148 +
1.149 + extend: function (target, source) {
1.150 + if (source) {
1.151 + for(var prop in source) {
1.152 + if(source.hasOwnProperty(prop)) {
1.153 + target[prop] = source[prop];
1.154 + }
1.155 + }
1.156 + }
1.157 + return target;
1.158 + },
1.159 +
1.160 + emptyDomNode: function (domNode) {
1.161 + while (domNode.firstChild) {
1.162 + ko.removeNode(domNode.firstChild);
1.163 + }
1.164 + },
1.165 +
1.166 + moveCleanedNodesToContainerElement: function(nodes) {
1.167 + // Ensure it's a real array, as we're about to reparent the nodes and
1.168 + // we don't want the underlying collection to change while we're doing that.
1.169 + var nodesArray = ko.utils.makeArray(nodes);
1.170 +
1.171 + var container = document.createElement('div');
1.172 + for (var i = 0, j = nodesArray.length; i < j; i++) {
1.173 + ko.cleanNode(nodesArray[i]);
1.174 + container.appendChild(nodesArray[i]);
1.175 + }
1.176 + return container;
1.177 + },
1.178 +
1.179 + setDomNodeChildren: function (domNode, childNodes) {
1.180 + ko.utils.emptyDomNode(domNode);
1.181 + if (childNodes) {
1.182 + for (var i = 0, j = childNodes.length; i < j; i++)
1.183 + domNode.appendChild(childNodes[i]);
1.184 + }
1.185 + },
1.186 +
1.187 + replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
1.188 + var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
1.189 + if (nodesToReplaceArray.length > 0) {
1.190 + var insertionPoint = nodesToReplaceArray[0];
1.191 + var parent = insertionPoint.parentNode;
1.192 + for (var i = 0, j = newNodesArray.length; i < j; i++)
1.193 + parent.insertBefore(newNodesArray[i], insertionPoint);
1.194 + for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
1.195 + ko.removeNode(nodesToReplaceArray[i]);
1.196 + }
1.197 + }
1.198 + },
1.199 +
1.200 + setOptionNodeSelectionState: function (optionNode, isSelected) {
1.201 + // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
1.202 + if (navigator.userAgent.indexOf("MSIE 6") >= 0)
1.203 + optionNode.setAttribute("selected", isSelected);
1.204 + else
1.205 + optionNode.selected = isSelected;
1.206 + },
1.207 +
1.208 + stringTrim: function (string) {
1.209 + return (string || "").replace(stringTrimRegex, "");
1.210 + },
1.211 +
1.212 + stringTokenize: function (string, delimiter) {
1.213 + var result = [];
1.214 + var tokens = (string || "").split(delimiter);
1.215 + for (var i = 0, j = tokens.length; i < j; i++) {
1.216 + var trimmed = ko.utils.stringTrim(tokens[i]);
1.217 + if (trimmed !== "")
1.218 + result.push(trimmed);
1.219 + }
1.220 + return result;
1.221 + },
1.222 +
1.223 + stringStartsWith: function (string, startsWith) {
1.224 + string = string || "";
1.225 + if (startsWith.length > string.length)
1.226 + return false;
1.227 + return string.substring(0, startsWith.length) === startsWith;
1.228 + },
1.229 +
1.230 + buildEvalWithinScopeFunction: function (expression, scopeLevels) {
1.231 + // Build the source for a function that evaluates "expression"
1.232 + // For each scope variable, add an extra level of "with" nesting
1.233 + // Example result: with(sc[1]) { with(sc[0]) { return (expression) } }
1.234 + var functionBody = "return (" + expression + ")";
1.235 + for (var i = 0; i < scopeLevels; i++) {
1.236 + functionBody = "with(sc[" + i + "]) { " + functionBody + " } ";
1.237 + }
1.238 + return new Function("sc", functionBody);
1.239 + },
1.240 +
1.241 + domNodeIsContainedBy: function (node, containedByNode) {
1.242 + if (containedByNode.compareDocumentPosition)
1.243 + return (containedByNode.compareDocumentPosition(node) & 16) == 16;
1.244 + while (node != null) {
1.245 + if (node == containedByNode)
1.246 + return true;
1.247 + node = node.parentNode;
1.248 + }
1.249 + return false;
1.250 + },
1.251 +
1.252 + domNodeIsAttachedToDocument: function (node) {
1.253 + return ko.utils.domNodeIsContainedBy(node, node.ownerDocument);
1.254 + },
1.255 +
1.256 + tagNameLower: function(element) {
1.257 + // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
1.258 + // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
1.259 + // we don't need to do the .toLowerCase() as it will always be lower case anyway.
1.260 + return element && element.tagName && element.tagName.toLowerCase();
1.261 + },
1.262 +
1.263 + registerEventHandler: function (element, eventType, handler) {
1.264 + var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
1.265 + if (!mustUseAttachEvent && typeof jQuery != "undefined") {
1.266 + if (isClickOnCheckableElement(element, eventType)) {
1.267 + // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
1.268 + // it toggles the element checked state *after* the click event handlers run, whereas native
1.269 + // click events toggle the checked state *before* the event handler.
1.270 + // Fix this by intecepting the handler and applying the correct checkedness before it runs.
1.271 + var originalHandler = handler;
1.272 + handler = function(event, eventData) {
1.273 + var jQuerySuppliedCheckedState = this.checked;
1.274 + if (eventData)
1.275 + this.checked = eventData.checkedStateBeforeEvent !== true;
1.276 + originalHandler.call(this, event);
1.277 + this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
1.278 + };
1.279 + }
1.280 + jQuery(element)['bind'](eventType, handler);
1.281 + } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
1.282 + element.addEventListener(eventType, handler, false);
1.283 + else if (typeof element.attachEvent != "undefined")
1.284 + element.attachEvent("on" + eventType, function (event) {
1.285 + handler.call(element, event);
1.286 + });
1.287 + else
1.288 + throw new Error("Browser doesn't support addEventListener or attachEvent");
1.289 + },
1.290 +
1.291 + triggerEvent: function (element, eventType) {
1.292 + if (!(element && element.nodeType))
1.293 + throw new Error("element must be a DOM node when calling triggerEvent");
1.294 +
1.295 + if (typeof jQuery != "undefined") {
1.296 + var eventData = [];
1.297 + if (isClickOnCheckableElement(element, eventType)) {
1.298 + // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
1.299 + eventData.push({ checkedStateBeforeEvent: element.checked });
1.300 + }
1.301 + jQuery(element)['trigger'](eventType, eventData);
1.302 + } else if (typeof document.createEvent == "function") {
1.303 + if (typeof element.dispatchEvent == "function") {
1.304 + var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
1.305 + var event = document.createEvent(eventCategory);
1.306 + event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
1.307 + element.dispatchEvent(event);
1.308 + }
1.309 + else
1.310 + throw new Error("The supplied element doesn't support dispatchEvent");
1.311 + } else if (typeof element.fireEvent != "undefined") {
1.312 + // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
1.313 + // so to make it consistent, we'll do it manually here
1.314 + if (isClickOnCheckableElement(element, eventType))
1.315 + element.checked = element.checked !== true;
1.316 + element.fireEvent("on" + eventType);
1.317 + }
1.318 + else
1.319 + throw new Error("Browser doesn't support triggering events");
1.320 + },
1.321 +
1.322 + unwrapObservable: function (value) {
1.323 + return ko.isObservable(value) ? value() : value;
1.324 + },
1.325 +
1.326 + toggleDomNodeCssClass: function (node, className, shouldHaveClass) {
1.327 + var currentClassNames = (node.className || "").split(/\s+/);
1.328 + var hasClass = ko.utils.arrayIndexOf(currentClassNames, className) >= 0;
1.329 +
1.330 + if (shouldHaveClass && !hasClass) {
1.331 + node.className += (currentClassNames[0] ? " " : "") + className;
1.332 + } else if (hasClass && !shouldHaveClass) {
1.333 + var newClassName = "";
1.334 + for (var i = 0; i < currentClassNames.length; i++)
1.335 + if (currentClassNames[i] != className)
1.336 + newClassName += currentClassNames[i] + " ";
1.337 + node.className = ko.utils.stringTrim(newClassName);
1.338 + }
1.339 + },
1.340 +
1.341 + setTextContent: function(element, textContent) {
1.342 + var value = ko.utils.unwrapObservable(textContent);
1.343 + if ((value === null) || (value === undefined))
1.344 + value = "";
1.345 +
1.346 + 'innerText' in element ? element.innerText = value
1.347 + : element.textContent = value;
1.348 +
1.349 + if (ieVersion >= 9) {
1.350 + // Believe it or not, this actually fixes an IE9 rendering bug
1.351 + // (See https://github.com/SteveSanderson/knockout/issues/209)
1.352 + element.style.display = element.style.display;
1.353 + }
1.354 + },
1.355 +
1.356 + ensureSelectElementIsRenderedCorrectly: function(selectElement) {
1.357 + // Workaround for IE9 rendering bug - it doesn't reliably display all the text in dynamically-added select boxes unless you force it to re-render by updating the width.
1.358 + // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
1.359 + if (ieVersion >= 9) {
1.360 + var originalWidth = selectElement.style.width;
1.361 + selectElement.style.width = 0;
1.362 + selectElement.style.width = originalWidth;
1.363 + }
1.364 + },
1.365 +
1.366 + range: function (min, max) {
1.367 + min = ko.utils.unwrapObservable(min);
1.368 + max = ko.utils.unwrapObservable(max);
1.369 + var result = [];
1.370 + for (var i = min; i <= max; i++)
1.371 + result.push(i);
1.372 + return result;
1.373 + },
1.374 +
1.375 + makeArray: function(arrayLikeObject) {
1.376 + var result = [];
1.377 + for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
1.378 + result.push(arrayLikeObject[i]);
1.379 + };
1.380 + return result;
1.381 + },
1.382 +
1.383 + isIe6 : isIe6,
1.384 + isIe7 : isIe7,
1.385 + ieVersion : ieVersion,
1.386 +
1.387 + getFormFields: function(form, fieldName) {
1.388 + var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
1.389 + var isMatchingField = (typeof fieldName == 'string')
1.390 + ? function(field) { return field.name === fieldName }
1.391 + : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
1.392 + var matches = [];
1.393 + for (var i = fields.length - 1; i >= 0; i--) {
1.394 + if (isMatchingField(fields[i]))
1.395 + matches.push(fields[i]);
1.396 + };
1.397 + return matches;
1.398 + },
1.399 +
1.400 + parseJson: function (jsonString) {
1.401 + if (typeof jsonString == "string") {
1.402 + jsonString = ko.utils.stringTrim(jsonString);
1.403 + if (jsonString) {
1.404 + if (window.JSON && window.JSON.parse) // Use native parsing where available
1.405 + return window.JSON.parse(jsonString);
1.406 + return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
1.407 + }
1.408 + }
1.409 + return null;
1.410 + },
1.411 +
1.412 + stringifyJson: function (data, replacer, space) { // replacer and space are optional
1.413 + if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
1.414 + throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");
1.415 + return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
1.416 + },
1.417 +
1.418 + postJson: function (urlOrForm, data, options) {
1.419 + options = options || {};
1.420 + var params = options['params'] || {};
1.421 + var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
1.422 + var url = urlOrForm;
1.423 +
1.424 + // If we were given a form, use its 'action' URL and pick out any requested field values
1.425 + if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
1.426 + var originalForm = urlOrForm;
1.427 + url = originalForm.action;
1.428 + for (var i = includeFields.length - 1; i >= 0; i--) {
1.429 + var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
1.430 + for (var j = fields.length - 1; j >= 0; j--)
1.431 + params[fields[j].name] = fields[j].value;
1.432 + }
1.433 + }
1.434 +
1.435 + data = ko.utils.unwrapObservable(data);
1.436 + var form = document.createElement("form");
1.437 + form.style.display = "none";
1.438 + form.action = url;
1.439 + form.method = "post";
1.440 + for (var key in data) {
1.441 + var input = document.createElement("input");
1.442 + input.name = key;
1.443 + input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
1.444 + form.appendChild(input);
1.445 + }
1.446 + for (var key in params) {
1.447 + var input = document.createElement("input");
1.448 + input.name = key;
1.449 + input.value = params[key];
1.450 + form.appendChild(input);
1.451 + }
1.452 + document.body.appendChild(form);
1.453 + options['submitter'] ? options['submitter'](form) : form.submit();
1.454 + setTimeout(function () { form.parentNode.removeChild(form); }, 0);
1.455 + }
1.456 + }
1.457 +})();
1.458 +
1.459 +ko.exportSymbol('utils', ko.utils);
1.460 +ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
1.461 +ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
1.462 +ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
1.463 +ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
1.464 +ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
1.465 +ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
1.466 +ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
1.467 +ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
1.468 +ko.exportSymbol('utils.extend', ko.utils.extend);
1.469 +ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
1.470 +ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
1.471 +ko.exportSymbol('utils.postJson', ko.utils.postJson);
1.472 +ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
1.473 +ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
1.474 +ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
1.475 +ko.exportSymbol('utils.range', ko.utils.range);
1.476 +ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
1.477 +ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
1.478 +ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
1.479 +
1.480 +if (!Function.prototype['bind']) {
1.481 + // Function.prototype.bind is a standard part of ECMAScript 5th Edition (December 2009, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf)
1.482 + // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
1.483 + Function.prototype['bind'] = function (object) {
1.484 + var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
1.485 + return function () {
1.486 + return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
1.487 + };
1.488 + };
1.489 +}
1.490 +
1.491 +ko.utils.domData = new (function () {
1.492 + var uniqueId = 0;
1.493 + var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
1.494 + var dataStore = {};
1.495 + return {
1.496 + get: function (node, key) {
1.497 + var allDataForNode = ko.utils.domData.getAll(node, false);
1.498 + return allDataForNode === undefined ? undefined : allDataForNode[key];
1.499 + },
1.500 + set: function (node, key, value) {
1.501 + if (value === undefined) {
1.502 + // Make sure we don't actually create a new domData key if we are actually deleting a value
1.503 + if (ko.utils.domData.getAll(node, false) === undefined)
1.504 + return;
1.505 + }
1.506 + var allDataForNode = ko.utils.domData.getAll(node, true);
1.507 + allDataForNode[key] = value;
1.508 + },
1.509 + getAll: function (node, createIfNotFound) {
1.510 + var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
1.511 + var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null");
1.512 + if (!hasExistingDataStore) {
1.513 + if (!createIfNotFound)
1.514 + return undefined;
1.515 + dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
1.516 + dataStore[dataStoreKey] = {};
1.517 + }
1.518 + return dataStore[dataStoreKey];
1.519 + },
1.520 + clear: function (node) {
1.521 + var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
1.522 + if (dataStoreKey) {
1.523 + delete dataStore[dataStoreKey];
1.524 + node[dataStoreKeyExpandoPropertyName] = null;
1.525 + }
1.526 + }
1.527 + }
1.528 +})();
1.529 +
1.530 +ko.exportSymbol('utils.domData', ko.utils.domData);
1.531 +ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
1.532 +
1.533 +ko.utils.domNodeDisposal = new (function () {
1.534 + var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();
1.535 + var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
1.536 + var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
1.537 +
1.538 + function getDisposeCallbacksCollection(node, createIfNotFound) {
1.539 + var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
1.540 + if ((allDisposeCallbacks === undefined) && createIfNotFound) {
1.541 + allDisposeCallbacks = [];
1.542 + ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
1.543 + }
1.544 + return allDisposeCallbacks;
1.545 + }
1.546 + function destroyCallbacksCollection(node) {
1.547 + ko.utils.domData.set(node, domDataKey, undefined);
1.548 + }
1.549 +
1.550 + function cleanSingleNode(node) {
1.551 + // Run all the dispose callbacks
1.552 + var callbacks = getDisposeCallbacksCollection(node, false);
1.553 + if (callbacks) {
1.554 + callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
1.555 + for (var i = 0; i < callbacks.length; i++)
1.556 + callbacks[i](node);
1.557 + }
1.558 +
1.559 + // Also erase the DOM data
1.560 + ko.utils.domData.clear(node);
1.561 +
1.562 + // Special support for jQuery here because it's so commonly used.
1.563 + // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
1.564 + // so notify it to tear down any resources associated with the node & descendants here.
1.565 + if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
1.566 + jQuery['cleanData']([node]);
1.567 +
1.568 + // Also clear any immediate-child comment nodes, as these wouldn't have been found by
1.569 + // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
1.570 + if (cleanableNodeTypesWithDescendants[node.nodeType])
1.571 + cleanImmediateCommentTypeChildren(node);
1.572 + }
1.573 +
1.574 + function cleanImmediateCommentTypeChildren(nodeWithChildren) {
1.575 + var child, nextChild = nodeWithChildren.firstChild;
1.576 + while (child = nextChild) {
1.577 + nextChild = child.nextSibling;
1.578 + if (child.nodeType === 8)
1.579 + cleanSingleNode(child);
1.580 + }
1.581 + }
1.582 +
1.583 + return {
1.584 + addDisposeCallback : function(node, callback) {
1.585 + if (typeof callback != "function")
1.586 + throw new Error("Callback must be a function");
1.587 + getDisposeCallbacksCollection(node, true).push(callback);
1.588 + },
1.589 +
1.590 + removeDisposeCallback : function(node, callback) {
1.591 + var callbacksCollection = getDisposeCallbacksCollection(node, false);
1.592 + if (callbacksCollection) {
1.593 + ko.utils.arrayRemoveItem(callbacksCollection, callback);
1.594 + if (callbacksCollection.length == 0)
1.595 + destroyCallbacksCollection(node);
1.596 + }
1.597 + },
1.598 +
1.599 + cleanNode : function(node) {
1.600 + // First clean this node, where applicable
1.601 + if (cleanableNodeTypes[node.nodeType]) {
1.602 + cleanSingleNode(node);
1.603 +
1.604 + // ... then its descendants, where applicable
1.605 + if (cleanableNodeTypesWithDescendants[node.nodeType]) {
1.606 + // Clone the descendants list in case it changes during iteration
1.607 + var descendants = [];
1.608 + ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
1.609 + for (var i = 0, j = descendants.length; i < j; i++)
1.610 + cleanSingleNode(descendants[i]);
1.611 + }
1.612 + }
1.613 + },
1.614 +
1.615 + removeNode : function(node) {
1.616 + ko.cleanNode(node);
1.617 + if (node.parentNode)
1.618 + node.parentNode.removeChild(node);
1.619 + }
1.620 + }
1.621 +})();
1.622 +ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
1.623 +ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
1.624 +ko.exportSymbol('cleanNode', ko.cleanNode);
1.625 +ko.exportSymbol('removeNode', ko.removeNode);
1.626 +ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
1.627 +ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
1.628 +ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
1.629 +(function () {
1.630 + var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
1.631 +
1.632 + function simpleHtmlParse(html) {
1.633 + // Based on jQuery's "clean" function, but only accounting for table-related elements.
1.634 + // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
1.635 +
1.636 + // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
1.637 + // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
1.638 + // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
1.639 + // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
1.640 +
1.641 + // Trim whitespace, otherwise indexOf won't work as expected
1.642 + var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
1.643 +
1.644 + // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
1.645 + var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
1.646 + !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
1.647 + (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
1.648 + /* anything else */ [0, "", ""];
1.649 +
1.650 + // Go to html and back, then peel off extra wrappers
1.651 + // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
1.652 + var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
1.653 + if (typeof window['innerShiv'] == "function") {
1.654 + div.appendChild(window['innerShiv'](markup));
1.655 + } else {
1.656 + div.innerHTML = markup;
1.657 + }
1.658 +
1.659 + // Move to the right depth
1.660 + while (wrap[0]--)
1.661 + div = div.lastChild;
1.662 +
1.663 + return ko.utils.makeArray(div.lastChild.childNodes);
1.664 + }
1.665 +
1.666 + function jQueryHtmlParse(html) {
1.667 + var elems = jQuery['clean']([html]);
1.668 +
1.669 + // As of jQuery 1.7.1, jQuery parses the HTML by appending it to some dummy parent nodes held in an in-memory document fragment.
1.670 + // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
1.671 + // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
1.672 + if (elems && elems[0]) {
1.673 + // Find the top-most parent element that's a direct child of a document fragment
1.674 + var elem = elems[0];
1.675 + while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
1.676 + elem = elem.parentNode;
1.677 + // ... then detach it
1.678 + if (elem.parentNode)
1.679 + elem.parentNode.removeChild(elem);
1.680 + }
1.681 +
1.682 + return elems;
1.683 + }
1.684 +
1.685 + ko.utils.parseHtmlFragment = function(html) {
1.686 + return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
1.687 + : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
1.688 + };
1.689 +
1.690 + ko.utils.setHtml = function(node, html) {
1.691 + ko.utils.emptyDomNode(node);
1.692 +
1.693 + if ((html !== null) && (html !== undefined)) {
1.694 + if (typeof html != 'string')
1.695 + html = html.toString();
1.696 +
1.697 + // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
1.698 + // for example <tr> elements which are not normally allowed to exist on their own.
1.699 + // If you've referenced jQuery we'll use that rather than duplicating its code.
1.700 + if (typeof jQuery != 'undefined') {
1.701 + jQuery(node)['html'](html);
1.702 + } else {
1.703 + // ... otherwise, use KO's own parsing logic.
1.704 + var parsedNodes = ko.utils.parseHtmlFragment(html);
1.705 + for (var i = 0; i < parsedNodes.length; i++)
1.706 + node.appendChild(parsedNodes[i]);
1.707 + }
1.708 + }
1.709 + };
1.710 +})();
1.711 +
1.712 +ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
1.713 +ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
1.714 +
1.715 +ko.memoization = (function () {
1.716 + var memos = {};
1.717 +
1.718 + function randomMax8HexChars() {
1.719 + return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
1.720 + }
1.721 + function generateRandomId() {
1.722 + return randomMax8HexChars() + randomMax8HexChars();
1.723 + }
1.724 + function findMemoNodes(rootNode, appendToArray) {
1.725 + if (!rootNode)
1.726 + return;
1.727 + if (rootNode.nodeType == 8) {
1.728 + var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
1.729 + if (memoId != null)
1.730 + appendToArray.push({ domNode: rootNode, memoId: memoId });
1.731 + } else if (rootNode.nodeType == 1) {
1.732 + for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
1.733 + findMemoNodes(childNodes[i], appendToArray);
1.734 + }
1.735 + }
1.736 +
1.737 + return {
1.738 + memoize: function (callback) {
1.739 + if (typeof callback != "function")
1.740 + throw new Error("You can only pass a function to ko.memoization.memoize()");
1.741 + var memoId = generateRandomId();
1.742 + memos[memoId] = callback;
1.743 + return "<!--[ko_memo:" + memoId + "]-->";
1.744 + },
1.745 +
1.746 + unmemoize: function (memoId, callbackParams) {
1.747 + var callback = memos[memoId];
1.748 + if (callback === undefined)
1.749 + throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
1.750 + try {
1.751 + callback.apply(null, callbackParams || []);
1.752 + return true;
1.753 + }
1.754 + finally { delete memos[memoId]; }
1.755 + },
1.756 +
1.757 + unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
1.758 + var memos = [];
1.759 + findMemoNodes(domNode, memos);
1.760 + for (var i = 0, j = memos.length; i < j; i++) {
1.761 + var node = memos[i].domNode;
1.762 + var combinedParams = [node];
1.763 + if (extraCallbackParamsArray)
1.764 + ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
1.765 + ko.memoization.unmemoize(memos[i].memoId, combinedParams);
1.766 + node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
1.767 + if (node.parentNode)
1.768 + node.parentNode.removeChild(node); // If possible, erase it totally (not always possible - someone else might just hold a reference to it then call unmemoizeDomNodeAndDescendants again)
1.769 + }
1.770 + },
1.771 +
1.772 + parseMemoText: function (memoText) {
1.773 + var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
1.774 + return match ? match[1] : null;
1.775 + }
1.776 + };
1.777 +})();
1.778 +
1.779 +ko.exportSymbol('memoization', ko.memoization);
1.780 +ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
1.781 +ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
1.782 +ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
1.783 +ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
1.784 +ko.extenders = {
1.785 + 'throttle': function(target, timeout) {
1.786 + // Throttling means two things:
1.787 +
1.788 + // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
1.789 + // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
1.790 + target['throttleEvaluation'] = timeout;
1.791 +
1.792 + // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
1.793 + // so the target cannot change value synchronously or faster than a certain rate
1.794 + var writeTimeoutInstance = null;
1.795 + return ko.dependentObservable({
1.796 + 'read': target,
1.797 + 'write': function(value) {
1.798 + clearTimeout(writeTimeoutInstance);
1.799 + writeTimeoutInstance = setTimeout(function() {
1.800 + target(value);
1.801 + }, timeout);
1.802 + }
1.803 + });
1.804 + },
1.805 +
1.806 + 'notify': function(target, notifyWhen) {
1.807 + target["equalityComparer"] = notifyWhen == "always"
1.808 + ? function() { return false } // Treat all values as not equal
1.809 + : ko.observable["fn"]["equalityComparer"];
1.810 + return target;
1.811 + }
1.812 +};
1.813 +
1.814 +function applyExtenders(requestedExtenders) {
1.815 + var target = this;
1.816 + if (requestedExtenders) {
1.817 + for (var key in requestedExtenders) {
1.818 + var extenderHandler = ko.extenders[key];
1.819 + if (typeof extenderHandler == 'function') {
1.820 + target = extenderHandler(target, requestedExtenders[key]);
1.821 + }
1.822 + }
1.823 + }
1.824 + return target;
1.825 +}
1.826 +
1.827 +ko.exportSymbol('extenders', ko.extenders);
1.828 +
1.829 +ko.subscription = function (target, callback, disposeCallback) {
1.830 + this.target = target;
1.831 + this.callback = callback;
1.832 + this.disposeCallback = disposeCallback;
1.833 + ko.exportProperty(this, 'dispose', this.dispose);
1.834 +};
1.835 +ko.subscription.prototype.dispose = function () {
1.836 + this.isDisposed = true;
1.837 + this.disposeCallback();
1.838 +};
1.839 +
1.840 +ko.subscribable = function () {
1.841 + this._subscriptions = {};
1.842 +
1.843 + ko.utils.extend(this, ko.subscribable['fn']);
1.844 + ko.exportProperty(this, 'subscribe', this.subscribe);
1.845 + ko.exportProperty(this, 'extend', this.extend);
1.846 + ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
1.847 +}
1.848 +
1.849 +var defaultEvent = "change";
1.850 +
1.851 +ko.subscribable['fn'] = {
1.852 + subscribe: function (callback, callbackTarget, event) {
1.853 + event = event || defaultEvent;
1.854 + var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
1.855 +
1.856 + var subscription = new ko.subscription(this, boundCallback, function () {
1.857 + ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
1.858 + }.bind(this));
1.859 +
1.860 + if (!this._subscriptions[event])
1.861 + this._subscriptions[event] = [];
1.862 + this._subscriptions[event].push(subscription);
1.863 + return subscription;
1.864 + },
1.865 +
1.866 + "notifySubscribers": function (valueToNotify, event) {
1.867 + event = event || defaultEvent;
1.868 + if (this._subscriptions[event]) {
1.869 + ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
1.870 + // In case a subscription was disposed during the arrayForEach cycle, check
1.871 + // for isDisposed on each subscription before invoking its callback
1.872 + if (subscription && (subscription.isDisposed !== true))
1.873 + subscription.callback(valueToNotify);
1.874 + });
1.875 + }
1.876 + },
1.877 +
1.878 + getSubscriptionsCount: function () {
1.879 + var total = 0;
1.880 + for (var eventName in this._subscriptions) {
1.881 + if (this._subscriptions.hasOwnProperty(eventName))
1.882 + total += this._subscriptions[eventName].length;
1.883 + }
1.884 + return total;
1.885 + },
1.886 +
1.887 + extend: applyExtenders
1.888 +};
1.889 +
1.890 +
1.891 +ko.isSubscribable = function (instance) {
1.892 + return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
1.893 +};
1.894 +
1.895 +ko.exportSymbol('subscribable', ko.subscribable);
1.896 +ko.exportSymbol('isSubscribable', ko.isSubscribable);
1.897 +
1.898 +ko.dependencyDetection = (function () {
1.899 + var _frames = [];
1.900 +
1.901 + return {
1.902 + begin: function (callback) {
1.903 + _frames.push({ callback: callback, distinctDependencies:[] });
1.904 + },
1.905 +
1.906 + end: function () {
1.907 + _frames.pop();
1.908 + },
1.909 +
1.910 + registerDependency: function (subscribable) {
1.911 + if (!ko.isSubscribable(subscribable))
1.912 + throw new Error("Only subscribable things can act as dependencies");
1.913 + if (_frames.length > 0) {
1.914 + var topFrame = _frames[_frames.length - 1];
1.915 + if (ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
1.916 + return;
1.917 + topFrame.distinctDependencies.push(subscribable);
1.918 + topFrame.callback(subscribable);
1.919 + }
1.920 + }
1.921 + };
1.922 +})();
1.923 +var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };
1.924 +
1.925 +ko.observable = function (initialValue) {
1.926 + var _latestValue = initialValue;
1.927 +
1.928 + function observable() {
1.929 + if (arguments.length > 0) {
1.930 + // Write
1.931 +
1.932 + // Ignore writes if the value hasn't changed
1.933 + if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
1.934 + observable.valueWillMutate();
1.935 + _latestValue = arguments[0];
1.936 + if (DEBUG) observable._latestValue = _latestValue;
1.937 + observable.valueHasMutated();
1.938 + }
1.939 + return this; // Permits chained assignments
1.940 + }
1.941 + else {
1.942 + // Read
1.943 + ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
1.944 + return _latestValue;
1.945 + }
1.946 + }
1.947 + if (DEBUG) observable._latestValue = _latestValue;
1.948 + ko.subscribable.call(observable);
1.949 + observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
1.950 + observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
1.951 + ko.utils.extend(observable, ko.observable['fn']);
1.952 +
1.953 + ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
1.954 + ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
1.955 +
1.956 + return observable;
1.957 +}
1.958 +
1.959 +ko.observable['fn'] = {
1.960 + "equalityComparer": function valuesArePrimitiveAndEqual(a, b) {
1.961 + var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
1.962 + return oldValueIsPrimitive ? (a === b) : false;
1.963 + }
1.964 +};
1.965 +
1.966 +var protoProperty = ko.observable.protoProperty = "__ko_proto__";
1.967 +ko.observable['fn'][protoProperty] = ko.observable;
1.968 +
1.969 +ko.hasPrototype = function(instance, prototype) {
1.970 + if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
1.971 + if (instance[protoProperty] === prototype) return true;
1.972 + return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
1.973 +};
1.974 +
1.975 +ko.isObservable = function (instance) {
1.976 + return ko.hasPrototype(instance, ko.observable);
1.977 +}
1.978 +ko.isWriteableObservable = function (instance) {
1.979 + // Observable
1.980 + if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
1.981 + return true;
1.982 + // Writeable dependent observable
1.983 + if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
1.984 + return true;
1.985 + // Anything else
1.986 + return false;
1.987 +}
1.988 +
1.989 +
1.990 +ko.exportSymbol('observable', ko.observable);
1.991 +ko.exportSymbol('isObservable', ko.isObservable);
1.992 +ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
1.993 +ko.observableArray = function (initialValues) {
1.994 + if (arguments.length == 0) {
1.995 + // Zero-parameter constructor initializes to empty array
1.996 + initialValues = [];
1.997 + }
1.998 + if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
1.999 + throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
1.1000 +
1.1001 + var result = ko.observable(initialValues);
1.1002 + ko.utils.extend(result, ko.observableArray['fn']);
1.1003 + return result;
1.1004 +}
1.1005 +
1.1006 +ko.observableArray['fn'] = {
1.1007 + 'remove': function (valueOrPredicate) {
1.1008 + var underlyingArray = this();
1.1009 + var removedValues = [];
1.1010 + var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
1.1011 + for (var i = 0; i < underlyingArray.length; i++) {
1.1012 + var value = underlyingArray[i];
1.1013 + if (predicate(value)) {
1.1014 + if (removedValues.length === 0) {
1.1015 + this.valueWillMutate();
1.1016 + }
1.1017 + removedValues.push(value);
1.1018 + underlyingArray.splice(i, 1);
1.1019 + i--;
1.1020 + }
1.1021 + }
1.1022 + if (removedValues.length) {
1.1023 + this.valueHasMutated();
1.1024 + }
1.1025 + return removedValues;
1.1026 + },
1.1027 +
1.1028 + 'removeAll': function (arrayOfValues) {
1.1029 + // If you passed zero args, we remove everything
1.1030 + if (arrayOfValues === undefined) {
1.1031 + var underlyingArray = this();
1.1032 + var allValues = underlyingArray.slice(0);
1.1033 + this.valueWillMutate();
1.1034 + underlyingArray.splice(0, underlyingArray.length);
1.1035 + this.valueHasMutated();
1.1036 + return allValues;
1.1037 + }
1.1038 + // If you passed an arg, we interpret it as an array of entries to remove
1.1039 + if (!arrayOfValues)
1.1040 + return [];
1.1041 + return this['remove'](function (value) {
1.1042 + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
1.1043 + });
1.1044 + },
1.1045 +
1.1046 + 'destroy': function (valueOrPredicate) {
1.1047 + var underlyingArray = this();
1.1048 + var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
1.1049 + this.valueWillMutate();
1.1050 + for (var i = underlyingArray.length - 1; i >= 0; i--) {
1.1051 + var value = underlyingArray[i];
1.1052 + if (predicate(value))
1.1053 + underlyingArray[i]["_destroy"] = true;
1.1054 + }
1.1055 + this.valueHasMutated();
1.1056 + },
1.1057 +
1.1058 + 'destroyAll': function (arrayOfValues) {
1.1059 + // If you passed zero args, we destroy everything
1.1060 + if (arrayOfValues === undefined)
1.1061 + return this['destroy'](function() { return true });
1.1062 +
1.1063 + // If you passed an arg, we interpret it as an array of entries to destroy
1.1064 + if (!arrayOfValues)
1.1065 + return [];
1.1066 + return this['destroy'](function (value) {
1.1067 + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
1.1068 + });
1.1069 + },
1.1070 +
1.1071 + 'indexOf': function (item) {
1.1072 + var underlyingArray = this();
1.1073 + return ko.utils.arrayIndexOf(underlyingArray, item);
1.1074 + },
1.1075 +
1.1076 + 'replace': function(oldItem, newItem) {
1.1077 + var index = this['indexOf'](oldItem);
1.1078 + if (index >= 0) {
1.1079 + this.valueWillMutate();
1.1080 + this()[index] = newItem;
1.1081 + this.valueHasMutated();
1.1082 + }
1.1083 + }
1.1084 +}
1.1085 +
1.1086 +// Populate ko.observableArray.fn with read/write functions from native arrays
1.1087 +ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
1.1088 + ko.observableArray['fn'][methodName] = function () {
1.1089 + var underlyingArray = this();
1.1090 + this.valueWillMutate();
1.1091 + var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
1.1092 + this.valueHasMutated();
1.1093 + return methodCallResult;
1.1094 + };
1.1095 +});
1.1096 +
1.1097 +// Populate ko.observableArray.fn with read-only functions from native arrays
1.1098 +ko.utils.arrayForEach(["slice"], function (methodName) {
1.1099 + ko.observableArray['fn'][methodName] = function () {
1.1100 + var underlyingArray = this();
1.1101 + return underlyingArray[methodName].apply(underlyingArray, arguments);
1.1102 + };
1.1103 +});
1.1104 +
1.1105 +ko.exportSymbol('observableArray', ko.observableArray);
1.1106 +ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
1.1107 + var _latestValue,
1.1108 + _hasBeenEvaluated = false,
1.1109 + _isBeingEvaluated = false,
1.1110 + readFunction = evaluatorFunctionOrOptions;
1.1111 +
1.1112 + if (readFunction && typeof readFunction == "object") {
1.1113 + // Single-parameter syntax - everything is on this "options" param
1.1114 + options = readFunction;
1.1115 + readFunction = options["read"];
1.1116 + } else {
1.1117 + // Multi-parameter syntax - construct the options according to the params passed
1.1118 + options = options || {};
1.1119 + if (!readFunction)
1.1120 + readFunction = options["read"];
1.1121 + }
1.1122 + // By here, "options" is always non-null
1.1123 + if (typeof readFunction != "function")
1.1124 + throw new Error("Pass a function that returns the value of the ko.computed");
1.1125 +
1.1126 + var writeFunction = options["write"];
1.1127 + if (!evaluatorFunctionTarget)
1.1128 + evaluatorFunctionTarget = options["owner"];
1.1129 +
1.1130 + var _subscriptionsToDependencies = [];
1.1131 + function disposeAllSubscriptionsToDependencies() {
1.1132 + ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
1.1133 + subscription.dispose();
1.1134 + });
1.1135 + _subscriptionsToDependencies = [];
1.1136 + }
1.1137 + var dispose = disposeAllSubscriptionsToDependencies;
1.1138 +
1.1139 + // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values
1.1140 + // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
1.1141 + // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
1.1142 + var disposeWhenNodeIsRemoved = (typeof options["disposeWhenNodeIsRemoved"] == "object") ? options["disposeWhenNodeIsRemoved"] : null;
1.1143 + var disposeWhen = options["disposeWhen"] || function() { return false; };
1.1144 + if (disposeWhenNodeIsRemoved) {
1.1145 + dispose = function() {
1.1146 + ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
1.1147 + disposeAllSubscriptionsToDependencies();
1.1148 + };
1.1149 + ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
1.1150 + var existingDisposeWhenFunction = disposeWhen;
1.1151 + disposeWhen = function () {
1.1152 + return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
1.1153 + }
1.1154 + }
1.1155 +
1.1156 + var evaluationTimeoutInstance = null;
1.1157 + function evaluatePossiblyAsync() {
1.1158 + var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
1.1159 + if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
1.1160 + clearTimeout(evaluationTimeoutInstance);
1.1161 + evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
1.1162 + } else
1.1163 + evaluateImmediate();
1.1164 + }
1.1165 +
1.1166 + function evaluateImmediate() {
1.1167 + if (_isBeingEvaluated) {
1.1168 + // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
1.1169 + // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
1.1170 + // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
1.1171 + // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
1.1172 + return;
1.1173 + }
1.1174 +
1.1175 + // Don't dispose on first evaluation, because the "disposeWhen" callback might
1.1176 + // e.g., dispose when the associated DOM element isn't in the doc, and it's not
1.1177 + // going to be in the doc until *after* the first evaluation
1.1178 + if (_hasBeenEvaluated && disposeWhen()) {
1.1179 + dispose();
1.1180 + return;
1.1181 + }
1.1182 +
1.1183 + _isBeingEvaluated = true;
1.1184 + try {
1.1185 + // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
1.1186 + // Then, during evaluation, we cross off any that are in fact still being used.
1.1187 + var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
1.1188 +
1.1189 + ko.dependencyDetection.begin(function(subscribable) {
1.1190 + var inOld;
1.1191 + if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
1.1192 + disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
1.1193 + else
1.1194 + _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync)); // Brand new subscription - add it
1.1195 + });
1.1196 +
1.1197 + var newValue = readFunction.call(evaluatorFunctionTarget);
1.1198 +
1.1199 + // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
1.1200 + for (var i = disposalCandidates.length - 1; i >= 0; i--) {
1.1201 + if (disposalCandidates[i])
1.1202 + _subscriptionsToDependencies.splice(i, 1)[0].dispose();
1.1203 + }
1.1204 + _hasBeenEvaluated = true;
1.1205 +
1.1206 + dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
1.1207 + _latestValue = newValue;
1.1208 + if (DEBUG) dependentObservable._latestValue = _latestValue;
1.1209 + } finally {
1.1210 + ko.dependencyDetection.end();
1.1211 + }
1.1212 +
1.1213 + dependentObservable["notifySubscribers"](_latestValue);
1.1214 + _isBeingEvaluated = false;
1.1215 +
1.1216 + }
1.1217 +
1.1218 + function dependentObservable() {
1.1219 + if (arguments.length > 0) {
1.1220 + set.apply(dependentObservable, arguments);
1.1221 + } else {
1.1222 + return get();
1.1223 + }
1.1224 + }
1.1225 +
1.1226 + function set() {
1.1227 + if (typeof writeFunction === "function") {
1.1228 + // Writing a value
1.1229 + writeFunction.apply(evaluatorFunctionTarget, arguments);
1.1230 + } else {
1.1231 + throw new Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");
1.1232 + }
1.1233 + }
1.1234 +
1.1235 + function get() {
1.1236 + // Reading the value
1.1237 + if (!_hasBeenEvaluated)
1.1238 + evaluateImmediate();
1.1239 + ko.dependencyDetection.registerDependency(dependentObservable);
1.1240 + return _latestValue;
1.1241 + }
1.1242 +
1.1243 + dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
1.1244 + dependentObservable.hasWriteFunction = typeof options["write"] === "function";
1.1245 + dependentObservable.dispose = function () { dispose(); };
1.1246 +
1.1247 + ko.subscribable.call(dependentObservable);
1.1248 + ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
1.1249 +
1.1250 + if (options['deferEvaluation'] !== true)
1.1251 + evaluateImmediate();
1.1252 +
1.1253 + ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
1.1254 + ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
1.1255 +
1.1256 + return dependentObservable;
1.1257 +};
1.1258 +
1.1259 +ko.isComputed = function(instance) {
1.1260 + return ko.hasPrototype(instance, ko.dependentObservable);
1.1261 +};
1.1262 +
1.1263 +var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
1.1264 +ko.dependentObservable[protoProp] = ko.observable;
1.1265 +
1.1266 +ko.dependentObservable['fn'] = {};
1.1267 +ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
1.1268 +
1.1269 +ko.exportSymbol('dependentObservable', ko.dependentObservable);
1.1270 +ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
1.1271 +ko.exportSymbol('isComputed', ko.isComputed);
1.1272 +
1.1273 +(function() {
1.1274 + var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
1.1275 +
1.1276 + ko.toJS = function(rootObject) {
1.1277 + if (arguments.length == 0)
1.1278 + throw new Error("When calling ko.toJS, pass the object you want to convert.");
1.1279 +
1.1280 + // We just unwrap everything at every level in the object graph
1.1281 + return mapJsObjectGraph(rootObject, function(valueToMap) {
1.1282 + // Loop because an observable's value might in turn be another observable wrapper
1.1283 + for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
1.1284 + valueToMap = valueToMap();
1.1285 + return valueToMap;
1.1286 + });
1.1287 + };
1.1288 +
1.1289 + ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
1.1290 + var plainJavaScriptObject = ko.toJS(rootObject);
1.1291 + return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
1.1292 + };
1.1293 +
1.1294 + function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
1.1295 + visitedObjects = visitedObjects || new objectLookup();
1.1296 +
1.1297 + rootObject = mapInputCallback(rootObject);
1.1298 + var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
1.1299 + if (!canHaveProperties)
1.1300 + return rootObject;
1.1301 +
1.1302 + var outputProperties = rootObject instanceof Array ? [] : {};
1.1303 + visitedObjects.save(rootObject, outputProperties);
1.1304 +
1.1305 + visitPropertiesOrArrayEntries(rootObject, function(indexer) {
1.1306 + var propertyValue = mapInputCallback(rootObject[indexer]);
1.1307 +
1.1308 + switch (typeof propertyValue) {
1.1309 + case "boolean":
1.1310 + case "number":
1.1311 + case "string":
1.1312 + case "function":
1.1313 + outputProperties[indexer] = propertyValue;
1.1314 + break;
1.1315 + case "object":
1.1316 + case "undefined":
1.1317 + var previouslyMappedValue = visitedObjects.get(propertyValue);
1.1318 + outputProperties[indexer] = (previouslyMappedValue !== undefined)
1.1319 + ? previouslyMappedValue
1.1320 + : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
1.1321 + break;
1.1322 + }
1.1323 + });
1.1324 +
1.1325 + return outputProperties;
1.1326 + }
1.1327 +
1.1328 + function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
1.1329 + if (rootObject instanceof Array) {
1.1330 + for (var i = 0; i < rootObject.length; i++)
1.1331 + visitorCallback(i);
1.1332 +
1.1333 + // For arrays, also respect toJSON property for custom mappings (fixes #278)
1.1334 + if (typeof rootObject['toJSON'] == 'function')
1.1335 + visitorCallback('toJSON');
1.1336 + } else {
1.1337 + for (var propertyName in rootObject)
1.1338 + visitorCallback(propertyName);
1.1339 + }
1.1340 + };
1.1341 +
1.1342 + function objectLookup() {
1.1343 + var keys = [];
1.1344 + var values = [];
1.1345 + this.save = function(key, value) {
1.1346 + var existingIndex = ko.utils.arrayIndexOf(keys, key);
1.1347 + if (existingIndex >= 0)
1.1348 + values[existingIndex] = value;
1.1349 + else {
1.1350 + keys.push(key);
1.1351 + values.push(value);
1.1352 + }
1.1353 + };
1.1354 + this.get = function(key) {
1.1355 + var existingIndex = ko.utils.arrayIndexOf(keys, key);
1.1356 + return (existingIndex >= 0) ? values[existingIndex] : undefined;
1.1357 + };
1.1358 + };
1.1359 +})();
1.1360 +
1.1361 +ko.exportSymbol('toJS', ko.toJS);
1.1362 +ko.exportSymbol('toJSON', ko.toJSON);
1.1363 +(function () {
1.1364 + var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
1.1365 +
1.1366 + // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
1.1367 + // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
1.1368 + // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
1.1369 + ko.selectExtensions = {
1.1370 + readValue : function(element) {
1.1371 + switch (ko.utils.tagNameLower(element)) {
1.1372 + case 'option':
1.1373 + if (element[hasDomDataExpandoProperty] === true)
1.1374 + return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
1.1375 + return element.getAttribute("value");
1.1376 + case 'select':
1.1377 + return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
1.1378 + default:
1.1379 + return element.value;
1.1380 + }
1.1381 + },
1.1382 +
1.1383 + writeValue: function(element, value) {
1.1384 + switch (ko.utils.tagNameLower(element)) {
1.1385 + case 'option':
1.1386 + switch(typeof value) {
1.1387 + case "string":
1.1388 + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
1.1389 + if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
1.1390 + delete element[hasDomDataExpandoProperty];
1.1391 + }
1.1392 + element.value = value;
1.1393 + break;
1.1394 + default:
1.1395 + // Store arbitrary object using DomData
1.1396 + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
1.1397 + element[hasDomDataExpandoProperty] = true;
1.1398 +
1.1399 + // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
1.1400 + element.value = typeof value === "number" ? value : "";
1.1401 + break;
1.1402 + }
1.1403 + break;
1.1404 + case 'select':
1.1405 + for (var i = element.options.length - 1; i >= 0; i--) {
1.1406 + if (ko.selectExtensions.readValue(element.options[i]) == value) {
1.1407 + element.selectedIndex = i;
1.1408 + break;
1.1409 + }
1.1410 + }
1.1411 + break;
1.1412 + default:
1.1413 + if ((value === null) || (value === undefined))
1.1414 + value = "";
1.1415 + element.value = value;
1.1416 + break;
1.1417 + }
1.1418 + }
1.1419 + };
1.1420 +})();
1.1421 +
1.1422 +ko.exportSymbol('selectExtensions', ko.selectExtensions);
1.1423 +ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
1.1424 +ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
1.1425 +
1.1426 +ko.jsonExpressionRewriting = (function () {
1.1427 + var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
1.1428 + var javaScriptAssignmentTarget = /^[\_$a-z][\_$a-z0-9]*(\[.*?\])*(\.[\_$a-z][\_$a-z0-9]*(\[.*?\])*)*$/i;
1.1429 + var javaScriptReservedWords = ["true", "false"];
1.1430 +
1.1431 + function restoreTokens(string, tokens) {
1.1432 + var prevValue = null;
1.1433 + while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
1.1434 + prevValue = string;
1.1435 + string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
1.1436 + return tokens[tokenIndex];
1.1437 + });
1.1438 + }
1.1439 + return string;
1.1440 + }
1.1441 +
1.1442 + function isWriteableValue(expression) {
1.1443 + if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
1.1444 + return false;
1.1445 + return expression.match(javaScriptAssignmentTarget) !== null;
1.1446 + }
1.1447 +
1.1448 + function ensureQuoted(key) {
1.1449 + var trimmedKey = ko.utils.stringTrim(key);
1.1450 + switch (trimmedKey.length && trimmedKey.charAt(0)) {
1.1451 + case "'":
1.1452 + case '"':
1.1453 + return key;
1.1454 + default:
1.1455 + return "'" + trimmedKey + "'";
1.1456 + }
1.1457 + }
1.1458 +
1.1459 + return {
1.1460 + bindingRewriteValidators: [],
1.1461 +
1.1462 + parseObjectLiteral: function(objectLiteralString) {
1.1463 + // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
1.1464 + // that is sufficient just to split an object literal string into a set of top-level key-value pairs
1.1465 +
1.1466 + var str = ko.utils.stringTrim(objectLiteralString);
1.1467 + if (str.length < 3)
1.1468 + return [];
1.1469 + if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
1.1470 + str = str.substring(1, str.length - 1);
1.1471 +
1.1472 + // Pull out any string literals and regex literals
1.1473 + var tokens = [];
1.1474 + var tokenStart = null, tokenEndChar;
1.1475 + for (var position = 0; position < str.length; position++) {
1.1476 + var c = str.charAt(position);
1.1477 + if (tokenStart === null) {
1.1478 + switch (c) {
1.1479 + case '"':
1.1480 + case "'":
1.1481 + case "/":
1.1482 + tokenStart = position;
1.1483 + tokenEndChar = c;
1.1484 + break;
1.1485 + }
1.1486 + } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
1.1487 + var token = str.substring(tokenStart, position + 1);
1.1488 + tokens.push(token);
1.1489 + var replacement = "@ko_token_" + (tokens.length - 1) + "@";
1.1490 + str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
1.1491 + position -= (token.length - replacement.length);
1.1492 + tokenStart = null;
1.1493 + }
1.1494 + }
1.1495 +
1.1496 + // Next pull out balanced paren, brace, and bracket blocks
1.1497 + tokenStart = null;
1.1498 + tokenEndChar = null;
1.1499 + var tokenDepth = 0, tokenStartChar = null;
1.1500 + for (var position = 0; position < str.length; position++) {
1.1501 + var c = str.charAt(position);
1.1502 + if (tokenStart === null) {
1.1503 + switch (c) {
1.1504 + case "{": tokenStart = position; tokenStartChar = c;
1.1505 + tokenEndChar = "}";
1.1506 + break;
1.1507 + case "(": tokenStart = position; tokenStartChar = c;
1.1508 + tokenEndChar = ")";
1.1509 + break;
1.1510 + case "[": tokenStart = position; tokenStartChar = c;
1.1511 + tokenEndChar = "]";
1.1512 + break;
1.1513 + }
1.1514 + }
1.1515 +
1.1516 + if (c === tokenStartChar)
1.1517 + tokenDepth++;
1.1518 + else if (c === tokenEndChar) {
1.1519 + tokenDepth--;
1.1520 + if (tokenDepth === 0) {
1.1521 + var token = str.substring(tokenStart, position + 1);
1.1522 + tokens.push(token);
1.1523 + var replacement = "@ko_token_" + (tokens.length - 1) + "@";
1.1524 + str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
1.1525 + position -= (token.length - replacement.length);
1.1526 + tokenStart = null;
1.1527 + }
1.1528 + }
1.1529 + }
1.1530 +
1.1531 + // Now we can safely split on commas to get the key/value pairs
1.1532 + var result = [];
1.1533 + var keyValuePairs = str.split(",");
1.1534 + for (var i = 0, j = keyValuePairs.length; i < j; i++) {
1.1535 + var pair = keyValuePairs[i];
1.1536 + var colonPos = pair.indexOf(":");
1.1537 + if ((colonPos > 0) && (colonPos < pair.length - 1)) {
1.1538 + var key = pair.substring(0, colonPos);
1.1539 + var value = pair.substring(colonPos + 1);
1.1540 + result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
1.1541 + } else {
1.1542 + result.push({ 'unknown': restoreTokens(pair, tokens) });
1.1543 + }
1.1544 + }
1.1545 + return result;
1.1546 + },
1.1547 +
1.1548 + insertPropertyAccessorsIntoJson: function (objectLiteralStringOrKeyValueArray) {
1.1549 + var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
1.1550 + ? ko.jsonExpressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
1.1551 + : objectLiteralStringOrKeyValueArray;
1.1552 + var resultStrings = [], propertyAccessorResultStrings = [];
1.1553 +
1.1554 + var keyValueEntry;
1.1555 + for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
1.1556 + if (resultStrings.length > 0)
1.1557 + resultStrings.push(",");
1.1558 +
1.1559 + if (keyValueEntry['key']) {
1.1560 + var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
1.1561 + resultStrings.push(quotedKey);
1.1562 + resultStrings.push(":");
1.1563 + resultStrings.push(val);
1.1564 +
1.1565 + if (isWriteableValue(ko.utils.stringTrim(val))) {
1.1566 + if (propertyAccessorResultStrings.length > 0)
1.1567 + propertyAccessorResultStrings.push(", ");
1.1568 + propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
1.1569 + }
1.1570 + } else if (keyValueEntry['unknown']) {
1.1571 + resultStrings.push(keyValueEntry['unknown']);
1.1572 + }
1.1573 + }
1.1574 +
1.1575 + var combinedResult = resultStrings.join("");
1.1576 + if (propertyAccessorResultStrings.length > 0) {
1.1577 + var allPropertyAccessors = propertyAccessorResultStrings.join("");
1.1578 + combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
1.1579 + }
1.1580 +
1.1581 + return combinedResult;
1.1582 + },
1.1583 +
1.1584 + keyValueArrayContainsKey: function(keyValueArray, key) {
1.1585 + for (var i = 0; i < keyValueArray.length; i++)
1.1586 + if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
1.1587 + return true;
1.1588 + return false;
1.1589 + },
1.1590 +
1.1591 + // Internal, private KO utility for updating model properties from within bindings
1.1592 + // property: If the property being updated is (or might be) an observable, pass it here
1.1593 + // If it turns out to be a writable observable, it will be written to directly
1.1594 + // allBindingsAccessor: All bindings in the current execution context.
1.1595 + // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
1.1596 + // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
1.1597 + // value: The value to be written
1.1598 + // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
1.1599 + // it is !== existing value on that writable observable
1.1600 + writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
1.1601 + if (!property || !ko.isWriteableObservable(property)) {
1.1602 + var propWriters = allBindingsAccessor()['_ko_property_writers'];
1.1603 + if (propWriters && propWriters[key])
1.1604 + propWriters[key](value);
1.1605 + } else if (!checkIfDifferent || property() !== value) {
1.1606 + property(value);
1.1607 + }
1.1608 + }
1.1609 + };
1.1610 +})();
1.1611 +
1.1612 +ko.exportSymbol('jsonExpressionRewriting', ko.jsonExpressionRewriting);
1.1613 +ko.exportSymbol('jsonExpressionRewriting.bindingRewriteValidators', ko.jsonExpressionRewriting.bindingRewriteValidators);
1.1614 +ko.exportSymbol('jsonExpressionRewriting.parseObjectLiteral', ko.jsonExpressionRewriting.parseObjectLiteral);
1.1615 +ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson);
1.1616 +(function() {
1.1617 + // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
1.1618 + // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
1.1619 + // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
1.1620 + // of that virtual hierarchy
1.1621 + //
1.1622 + // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
1.1623 + // without having to scatter special cases all over the binding and templating code.
1.1624 +
1.1625 + // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
1.1626 + // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
1.1627 + // So, use node.text where available, and node.nodeValue elsewhere
1.1628 + var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
1.1629 +
1.1630 + var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko\s+(.*\:.*)\s*-->$/ : /^\s*ko\s+(.*\:.*)\s*$/;
1.1631 + var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
1.1632 + var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
1.1633 +
1.1634 + function isStartComment(node) {
1.1635 + return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
1.1636 + }
1.1637 +
1.1638 + function isEndComment(node) {
1.1639 + return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
1.1640 + }
1.1641 +
1.1642 + function getVirtualChildren(startComment, allowUnbalanced) {
1.1643 + var currentNode = startComment;
1.1644 + var depth = 1;
1.1645 + var children = [];
1.1646 + while (currentNode = currentNode.nextSibling) {
1.1647 + if (isEndComment(currentNode)) {
1.1648 + depth--;
1.1649 + if (depth === 0)
1.1650 + return children;
1.1651 + }
1.1652 +
1.1653 + children.push(currentNode);
1.1654 +
1.1655 + if (isStartComment(currentNode))
1.1656 + depth++;
1.1657 + }
1.1658 + if (!allowUnbalanced)
1.1659 + throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
1.1660 + return null;
1.1661 + }
1.1662 +
1.1663 + function getMatchingEndComment(startComment, allowUnbalanced) {
1.1664 + var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
1.1665 + if (allVirtualChildren) {
1.1666 + if (allVirtualChildren.length > 0)
1.1667 + return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
1.1668 + return startComment.nextSibling;
1.1669 + } else
1.1670 + return null; // Must have no matching end comment, and allowUnbalanced is true
1.1671 + }
1.1672 +
1.1673 + function getUnbalancedChildTags(node) {
1.1674 + // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
1.1675 + // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
1.1676 + var childNode = node.firstChild, captureRemaining = null;
1.1677 + if (childNode) {
1.1678 + do {
1.1679 + if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
1.1680 + captureRemaining.push(childNode);
1.1681 + else if (isStartComment(childNode)) {
1.1682 + var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
1.1683 + if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
1.1684 + childNode = matchingEndComment;
1.1685 + else
1.1686 + captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
1.1687 + } else if (isEndComment(childNode)) {
1.1688 + captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
1.1689 + }
1.1690 + } while (childNode = childNode.nextSibling);
1.1691 + }
1.1692 + return captureRemaining;
1.1693 + }
1.1694 +
1.1695 + ko.virtualElements = {
1.1696 + allowedBindings: {},
1.1697 +
1.1698 + childNodes: function(node) {
1.1699 + return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
1.1700 + },
1.1701 +
1.1702 + emptyNode: function(node) {
1.1703 + if (!isStartComment(node))
1.1704 + ko.utils.emptyDomNode(node);
1.1705 + else {
1.1706 + var virtualChildren = ko.virtualElements.childNodes(node);
1.1707 + for (var i = 0, j = virtualChildren.length; i < j; i++)
1.1708 + ko.removeNode(virtualChildren[i]);
1.1709 + }
1.1710 + },
1.1711 +
1.1712 + setDomNodeChildren: function(node, childNodes) {
1.1713 + if (!isStartComment(node))
1.1714 + ko.utils.setDomNodeChildren(node, childNodes);
1.1715 + else {
1.1716 + ko.virtualElements.emptyNode(node);
1.1717 + var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
1.1718 + for (var i = 0, j = childNodes.length; i < j; i++)
1.1719 + endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
1.1720 + }
1.1721 + },
1.1722 +
1.1723 + prepend: function(containerNode, nodeToPrepend) {
1.1724 + if (!isStartComment(containerNode)) {
1.1725 + if (containerNode.firstChild)
1.1726 + containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
1.1727 + else
1.1728 + containerNode.appendChild(nodeToPrepend);
1.1729 + } else {
1.1730 + // Start comments must always have a parent and at least one following sibling (the end comment)
1.1731 + containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
1.1732 + }
1.1733 + },
1.1734 +
1.1735 + insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
1.1736 + if (!isStartComment(containerNode)) {
1.1737 + // Insert after insertion point
1.1738 + if (insertAfterNode.nextSibling)
1.1739 + containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
1.1740 + else
1.1741 + containerNode.appendChild(nodeToInsert);
1.1742 + } else {
1.1743 + // Children of start comments must always have a parent and at least one following sibling (the end comment)
1.1744 + containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
1.1745 + }
1.1746 + },
1.1747 +
1.1748 + firstChild: function(node) {
1.1749 + if (!isStartComment(node))
1.1750 + return node.firstChild;
1.1751 + if (!node.nextSibling || isEndComment(node.nextSibling))
1.1752 + return null;
1.1753 + return node.nextSibling;
1.1754 + },
1.1755 +
1.1756 + nextSibling: function(node) {
1.1757 + if (isStartComment(node))
1.1758 + node = getMatchingEndComment(node);
1.1759 + if (node.nextSibling && isEndComment(node.nextSibling))
1.1760 + return null;
1.1761 + return node.nextSibling;
1.1762 + },
1.1763 +
1.1764 + virtualNodeBindingValue: function(node) {
1.1765 + var regexMatch = isStartComment(node);
1.1766 + return regexMatch ? regexMatch[1] : null;
1.1767 + },
1.1768 +
1.1769 + normaliseVirtualElementDomStructure: function(elementVerified) {
1.1770 + // Workaround for https://github.com/SteveSanderson/knockout/issues/155
1.1771 + // (IE <= 8 or IE 9 quirks mode parses your HTML weirdly, treating closing </li> tags as if they don't exist, thereby moving comment nodes
1.1772 + // that are direct descendants of <ul> into the preceding <li>)
1.1773 + if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
1.1774 + return;
1.1775 +
1.1776 + // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
1.1777 + // must be intended to appear *after* that child, so move them there.
1.1778 + var childNode = elementVerified.firstChild;
1.1779 + if (childNode) {
1.1780 + do {
1.1781 + if (childNode.nodeType === 1) {
1.1782 + var unbalancedTags = getUnbalancedChildTags(childNode);
1.1783 + if (unbalancedTags) {
1.1784 + // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
1.1785 + var nodeToInsertBefore = childNode.nextSibling;
1.1786 + for (var i = 0; i < unbalancedTags.length; i++) {
1.1787 + if (nodeToInsertBefore)
1.1788 + elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
1.1789 + else
1.1790 + elementVerified.appendChild(unbalancedTags[i]);
1.1791 + }
1.1792 + }
1.1793 + }
1.1794 + } while (childNode = childNode.nextSibling);
1.1795 + }
1.1796 + }
1.1797 + };
1.1798 +})();
1.1799 +ko.exportSymbol('virtualElements', ko.virtualElements);
1.1800 +ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
1.1801 +ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
1.1802 +//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
1.1803 +ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
1.1804 +//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
1.1805 +ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
1.1806 +ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
1.1807 +(function() {
1.1808 + var defaultBindingAttributeName = "data-bind";
1.1809 +
1.1810 + ko.bindingProvider = function() {
1.1811 + this.bindingCache = {};
1.1812 + };
1.1813 +
1.1814 + ko.utils.extend(ko.bindingProvider.prototype, {
1.1815 + 'nodeHasBindings': function(node) {
1.1816 + switch (node.nodeType) {
1.1817 + case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
1.1818 + case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
1.1819 + default: return false;
1.1820 + }
1.1821 + },
1.1822 +
1.1823 + 'getBindings': function(node, bindingContext) {
1.1824 + var bindingsString = this['getBindingsString'](node, bindingContext);
1.1825 + return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext) : null;
1.1826 + },
1.1827 +
1.1828 + // The following function is only used internally by this default provider.
1.1829 + // It's not part of the interface definition for a general binding provider.
1.1830 + 'getBindingsString': function(node, bindingContext) {
1.1831 + switch (node.nodeType) {
1.1832 + case 1: return node.getAttribute(defaultBindingAttributeName); // Element
1.1833 + case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
1.1834 + default: return null;
1.1835 + }
1.1836 + },
1.1837 +
1.1838 + // The following function is only used internally by this default provider.
1.1839 + // It's not part of the interface definition for a general binding provider.
1.1840 + 'parseBindingsString': function(bindingsString, bindingContext) {
1.1841 + try {
1.1842 + var viewModel = bindingContext['$data'],
1.1843 + scopes = (typeof viewModel == 'object' && viewModel != null) ? [viewModel, bindingContext] : [bindingContext],
1.1844 + bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, scopes.length, this.bindingCache);
1.1845 + return bindingFunction(scopes);
1.1846 + } catch (ex) {
1.1847 + throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
1.1848 + }
1.1849 + }
1.1850 + });
1.1851 +
1.1852 + ko.bindingProvider['instance'] = new ko.bindingProvider();
1.1853 +
1.1854 + function createBindingsStringEvaluatorViaCache(bindingsString, scopesCount, cache) {
1.1855 + var cacheKey = scopesCount + '_' + bindingsString;
1.1856 + return cache[cacheKey]
1.1857 + || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, scopesCount));
1.1858 + }
1.1859 +
1.1860 + function createBindingsStringEvaluator(bindingsString, scopesCount) {
1.1861 + var rewrittenBindings = " { " + ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson(bindingsString) + " } ";
1.1862 + return ko.utils.buildEvalWithinScopeFunction(rewrittenBindings, scopesCount);
1.1863 + }
1.1864 +})();
1.1865 +
1.1866 +ko.exportSymbol('bindingProvider', ko.bindingProvider);
1.1867 +(function () {
1.1868 + ko.bindingHandlers = {};
1.1869 +
1.1870 + ko.bindingContext = function(dataItem, parentBindingContext) {
1.1871 + if (parentBindingContext) {
1.1872 + ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
1.1873 + this['$parentContext'] = parentBindingContext;
1.1874 + this['$parent'] = parentBindingContext['$data'];
1.1875 + this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
1.1876 + this['$parents'].unshift(this['$parent']);
1.1877 + } else {
1.1878 + this['$parents'] = [];
1.1879 + this['$root'] = dataItem;
1.1880 + }
1.1881 + this['$data'] = dataItem;
1.1882 + }
1.1883 + ko.bindingContext.prototype['createChildContext'] = function (dataItem) {
1.1884 + return new ko.bindingContext(dataItem, this);
1.1885 + };
1.1886 + ko.bindingContext.prototype['extend'] = function(properties) {
1.1887 + var clone = ko.utils.extend(new ko.bindingContext(), this);
1.1888 + return ko.utils.extend(clone, properties);
1.1889 + };
1.1890 +
1.1891 + function validateThatBindingIsAllowedForVirtualElements(bindingName) {
1.1892 + var validator = ko.virtualElements.allowedBindings[bindingName];
1.1893 + if (!validator)
1.1894 + throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
1.1895 + }
1.1896 +
1.1897 + function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
1.1898 + var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
1.1899 + while (currentChild = nextInQueue) {
1.1900 + // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
1.1901 + nextInQueue = ko.virtualElements.nextSibling(currentChild);
1.1902 + applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
1.1903 + }
1.1904 + }
1.1905 +
1.1906 + function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
1.1907 + var shouldBindDescendants = true;
1.1908 +
1.1909 + // Perf optimisation: Apply bindings only if...
1.1910 + // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
1.1911 + // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
1.1912 + // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
1.1913 + var isElement = (nodeVerified.nodeType === 1);
1.1914 + if (isElement) // Workaround IE <= 8 HTML parsing weirdness
1.1915 + ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
1.1916 +
1.1917 + var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
1.1918 + || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
1.1919 + if (shouldApplyBindings)
1.1920 + shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
1.1921 +
1.1922 + if (shouldBindDescendants) {
1.1923 + // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
1.1924 + // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
1.1925 + // hence bindingContextsMayDifferFromDomParentElement is false
1.1926 + // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
1.1927 + // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
1.1928 + // hence bindingContextsMayDifferFromDomParentElement is true
1.1929 + applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
1.1930 + }
1.1931 + }
1.1932 +
1.1933 + function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
1.1934 + // Need to be sure that inits are only run once, and updates never run until all the inits have been run
1.1935 + var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
1.1936 +
1.1937 + // Each time the dependentObservable is evaluated (after data changes),
1.1938 + // the binding attribute is reparsed so that it can pick out the correct
1.1939 + // model properties in the context of the changed data.
1.1940 + // DOM event callbacks need to be able to access this changed data,
1.1941 + // so we need a single parsedBindings variable (shared by all callbacks
1.1942 + // associated with this node's bindings) that all the closures can access.
1.1943 + var parsedBindings;
1.1944 + function makeValueAccessor(bindingKey) {
1.1945 + return function () { return parsedBindings[bindingKey] }
1.1946 + }
1.1947 + function parsedBindingsAccessor() {
1.1948 + return parsedBindings;
1.1949 + }
1.1950 +
1.1951 + var bindingHandlerThatControlsDescendantBindings;
1.1952 + ko.dependentObservable(
1.1953 + function () {
1.1954 + // Ensure we have a nonnull binding context to work with
1.1955 + var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
1.1956 + ? viewModelOrBindingContext
1.1957 + : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
1.1958 + var viewModel = bindingContextInstance['$data'];
1.1959 +
1.1960 + // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
1.1961 + // we can easily recover it just by scanning up the node's ancestors in the DOM
1.1962 + // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
1.1963 + if (bindingContextMayDifferFromDomParentElement)
1.1964 + ko.storedBindingContextForNode(node, bindingContextInstance);
1.1965 +
1.1966 + // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
1.1967 + var evaluatedBindings = (typeof bindings == "function") ? bindings() : bindings;
1.1968 + parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
1.1969 +
1.1970 + if (parsedBindings) {
1.1971 + // First run all the inits, so bindings can register for notification on changes
1.1972 + if (initPhase === 0) {
1.1973 + initPhase = 1;
1.1974 + for (var bindingKey in parsedBindings) {
1.1975 + var binding = ko.bindingHandlers[bindingKey];
1.1976 + if (binding && node.nodeType === 8)
1.1977 + validateThatBindingIsAllowedForVirtualElements(bindingKey);
1.1978 +
1.1979 + if (binding && typeof binding["init"] == "function") {
1.1980 + var handlerInitFn = binding["init"];
1.1981 + var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
1.1982 +
1.1983 + // If this binding handler claims to control descendant bindings, make a note of this
1.1984 + if (initResult && initResult['controlsDescendantBindings']) {
1.1985 + if (bindingHandlerThatControlsDescendantBindings !== undefined)
1.1986 + throw new Error("Multiple bindings (" + bindingHandlerThatControlsDescendantBindings + " and " + bindingKey + ") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");
1.1987 + bindingHandlerThatControlsDescendantBindings = bindingKey;
1.1988 + }
1.1989 + }
1.1990 + }
1.1991 + initPhase = 2;
1.1992 + }
1.1993 +
1.1994 + // ... then run all the updates, which might trigger changes even on the first evaluation
1.1995 + if (initPhase === 2) {
1.1996 + for (var bindingKey in parsedBindings) {
1.1997 + var binding = ko.bindingHandlers[bindingKey];
1.1998 + if (binding && typeof binding["update"] == "function") {
1.1999 + var handlerUpdateFn = binding["update"];
1.2000 + handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
1.2001 + }
1.2002 + }
1.2003 + }
1.2004 + }
1.2005 + },
1.2006 + null,
1.2007 + { 'disposeWhenNodeIsRemoved' : node }
1.2008 + );
1.2009 +
1.2010 + return {
1.2011 + shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
1.2012 + };
1.2013 + };
1.2014 +
1.2015 + var storedBindingContextDomDataKey = "__ko_bindingContext__";
1.2016 + ko.storedBindingContextForNode = function (node, bindingContext) {
1.2017 + if (arguments.length == 2)
1.2018 + ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
1.2019 + else
1.2020 + return ko.utils.domData.get(node, storedBindingContextDomDataKey);
1.2021 + }
1.2022 +
1.2023 + ko.applyBindingsToNode = function (node, bindings, viewModel) {
1.2024 + if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
1.2025 + ko.virtualElements.normaliseVirtualElementDomStructure(node);
1.2026 + return applyBindingsToNodeInternal(node, bindings, viewModel, true);
1.2027 + };
1.2028 +
1.2029 + ko.applyBindingsToDescendants = function(viewModel, rootNode) {
1.2030 + if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
1.2031 + applyBindingsToDescendantsInternal(viewModel, rootNode, true);
1.2032 + };
1.2033 +
1.2034 + ko.applyBindings = function (viewModel, rootNode) {
1.2035 + if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
1.2036 + throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
1.2037 + rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
1.2038 +
1.2039 + applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
1.2040 + };
1.2041 +
1.2042 + // Retrieving binding context from arbitrary nodes
1.2043 + ko.contextFor = function(node) {
1.2044 + // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
1.2045 + switch (node.nodeType) {
1.2046 + case 1:
1.2047 + case 8:
1.2048 + var context = ko.storedBindingContextForNode(node);
1.2049 + if (context) return context;
1.2050 + if (node.parentNode) return ko.contextFor(node.parentNode);
1.2051 + break;
1.2052 + }
1.2053 + return undefined;
1.2054 + };
1.2055 + ko.dataFor = function(node) {
1.2056 + var context = ko.contextFor(node);
1.2057 + return context ? context['$data'] : undefined;
1.2058 + };
1.2059 +
1.2060 + ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
1.2061 + ko.exportSymbol('applyBindings', ko.applyBindings);
1.2062 + ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
1.2063 + ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
1.2064 + ko.exportSymbol('contextFor', ko.contextFor);
1.2065 + ko.exportSymbol('dataFor', ko.dataFor);
1.2066 +})();
1.2067 +// For certain common events (currently just 'click'), allow a simplified data-binding syntax
1.2068 +// e.g. click:handler instead of the usual full-length event:{click:handler}
1.2069 +var eventHandlersWithShortcuts = ['click'];
1.2070 +ko.utils.arrayForEach(eventHandlersWithShortcuts, function(eventName) {
1.2071 + ko.bindingHandlers[eventName] = {
1.2072 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
1.2073 + var newValueAccessor = function () {
1.2074 + var result = {};
1.2075 + result[eventName] = valueAccessor();
1.2076 + return result;
1.2077 + };
1.2078 + return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
1.2079 + }
1.2080 + }
1.2081 +});
1.2082 +
1.2083 +
1.2084 +ko.bindingHandlers['event'] = {
1.2085 + 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
1.2086 + var eventsToHandle = valueAccessor() || {};
1.2087 + for(var eventNameOutsideClosure in eventsToHandle) {
1.2088 + (function() {
1.2089 + var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
1.2090 + if (typeof eventName == "string") {
1.2091 + ko.utils.registerEventHandler(element, eventName, function (event) {
1.2092 + var handlerReturnValue;
1.2093 + var handlerFunction = valueAccessor()[eventName];
1.2094 + if (!handlerFunction)
1.2095 + return;
1.2096 + var allBindings = allBindingsAccessor();
1.2097 +
1.2098 + try {
1.2099 + // Take all the event args, and prefix with the viewmodel
1.2100 + var argsForHandler = ko.utils.makeArray(arguments);
1.2101 + argsForHandler.unshift(viewModel);
1.2102 + handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
1.2103 + } finally {
1.2104 + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
1.2105 + if (event.preventDefault)
1.2106 + event.preventDefault();
1.2107 + else
1.2108 + event.returnValue = false;
1.2109 + }
1.2110 + }
1.2111 +
1.2112 + var bubble = allBindings[eventName + 'Bubble'] !== false;
1.2113 + if (!bubble) {
1.2114 + event.cancelBubble = true;
1.2115 + if (event.stopPropagation)
1.2116 + event.stopPropagation();
1.2117 + }
1.2118 + });
1.2119 + }
1.2120 + })();
1.2121 + }
1.2122 + }
1.2123 +};
1.2124 +
1.2125 +ko.bindingHandlers['submit'] = {
1.2126 + 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
1.2127 + if (typeof valueAccessor() != "function")
1.2128 + throw new Error("The value for a submit binding must be a function");
1.2129 + ko.utils.registerEventHandler(element, "submit", function (event) {
1.2130 + var handlerReturnValue;
1.2131 + var value = valueAccessor();
1.2132 + try { handlerReturnValue = value.call(viewModel, element); }
1.2133 + finally {
1.2134 + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
1.2135 + if (event.preventDefault)
1.2136 + event.preventDefault();
1.2137 + else
1.2138 + event.returnValue = false;
1.2139 + }
1.2140 + }
1.2141 + });
1.2142 + }
1.2143 +};
1.2144 +
1.2145 +ko.bindingHandlers['visible'] = {
1.2146 + 'update': function (element, valueAccessor) {
1.2147 + var value = ko.utils.unwrapObservable(valueAccessor());
1.2148 + var isCurrentlyVisible = !(element.style.display == "none");
1.2149 + if (value && !isCurrentlyVisible)
1.2150 + element.style.display = "";
1.2151 + else if ((!value) && isCurrentlyVisible)
1.2152 + element.style.display = "none";
1.2153 + }
1.2154 +}
1.2155 +
1.2156 +ko.bindingHandlers['enable'] = {
1.2157 + 'update': function (element, valueAccessor) {
1.2158 + var value = ko.utils.unwrapObservable(valueAccessor());
1.2159 + if (value && element.disabled)
1.2160 + element.removeAttribute("disabled");
1.2161 + else if ((!value) && (!element.disabled))
1.2162 + element.disabled = true;
1.2163 + }
1.2164 +};
1.2165 +
1.2166 +ko.bindingHandlers['disable'] = {
1.2167 + 'update': function (element, valueAccessor) {
1.2168 + ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
1.2169 + }
1.2170 +};
1.2171 +
1.2172 +function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
1.2173 + if (preferModelValue) {
1.2174 + if (modelValue !== ko.selectExtensions.readValue(element))
1.2175 + ko.selectExtensions.writeValue(element, modelValue);
1.2176 + }
1.2177 +
1.2178 + // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
1.2179 + // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
1.2180 + // change the model value to match the dropdown.
1.2181 + if (modelValue !== ko.selectExtensions.readValue(element))
1.2182 + ko.utils.triggerEvent(element, "change");
1.2183 +};
1.2184 +
1.2185 +ko.bindingHandlers['value'] = {
1.2186 + 'init': function (element, valueAccessor, allBindingsAccessor) {
1.2187 + // Always catch "change" event; possibly other events too if asked
1.2188 + var eventsToCatch = ["change"];
1.2189 + var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
1.2190 + if (requestedEventsToCatch) {
1.2191 + if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
1.2192 + requestedEventsToCatch = [requestedEventsToCatch];
1.2193 + ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
1.2194 + eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
1.2195 + }
1.2196 +
1.2197 + var valueUpdateHandler = function() {
1.2198 + var modelValue = valueAccessor();
1.2199 + var elementValue = ko.selectExtensions.readValue(element);
1.2200 + ko.jsonExpressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue, /* checkIfDifferent: */ true);
1.2201 + }
1.2202 +
1.2203 + // Workaround for https://github.com/SteveSanderson/knockout/issues/122
1.2204 + // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
1.2205 + var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
1.2206 + && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
1.2207 + if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
1.2208 + var propertyChangedFired = false;
1.2209 + ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
1.2210 + ko.utils.registerEventHandler(element, "blur", function() {
1.2211 + if (propertyChangedFired) {
1.2212 + propertyChangedFired = false;
1.2213 + valueUpdateHandler();
1.2214 + }
1.2215 + });
1.2216 + }
1.2217 +
1.2218 + ko.utils.arrayForEach(eventsToCatch, function(eventName) {
1.2219 + // The syntax "after<eventname>" means "run the handler asynchronously after the event"
1.2220 + // This is useful, for example, to catch "keydown" events after the browser has updated the control
1.2221 + // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
1.2222 + var handler = valueUpdateHandler;
1.2223 + if (ko.utils.stringStartsWith(eventName, "after")) {
1.2224 + handler = function() { setTimeout(valueUpdateHandler, 0) };
1.2225 + eventName = eventName.substring("after".length);
1.2226 + }
1.2227 + ko.utils.registerEventHandler(element, eventName, handler);
1.2228 + });
1.2229 + },
1.2230 + 'update': function (element, valueAccessor) {
1.2231 + var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
1.2232 + var newValue = ko.utils.unwrapObservable(valueAccessor());
1.2233 + var elementValue = ko.selectExtensions.readValue(element);
1.2234 + var valueHasChanged = (newValue != elementValue);
1.2235 +
1.2236 + // JavaScript's 0 == "" behavious is unfortunate here as it prevents writing 0 to an empty text box (loose equality suggests the values are the same).
1.2237 + // We don't want to do a strict equality comparison as that is more confusing for developers in certain cases, so we specifically special case 0 != "" here.
1.2238 + if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
1.2239 + valueHasChanged = true;
1.2240 +
1.2241 + if (valueHasChanged) {
1.2242 + var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
1.2243 + applyValueAction();
1.2244 +
1.2245 + // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
1.2246 + // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
1.2247 + // to apply the value as well.
1.2248 + var alsoApplyAsynchronously = valueIsSelectOption;
1.2249 + if (alsoApplyAsynchronously)
1.2250 + setTimeout(applyValueAction, 0);
1.2251 + }
1.2252 +
1.2253 + // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
1.2254 + // because you're not allowed to have a model value that disagrees with a visible UI selection.
1.2255 + if (valueIsSelectOption && (element.length > 0))
1.2256 + ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
1.2257 + }
1.2258 +};
1.2259 +
1.2260 +ko.bindingHandlers['options'] = {
1.2261 + 'update': function (element, valueAccessor, allBindingsAccessor) {
1.2262 + if (ko.utils.tagNameLower(element) !== "select")
1.2263 + throw new Error("options binding applies only to SELECT elements");
1.2264 +
1.2265 + var selectWasPreviouslyEmpty = element.length == 0;
1.2266 + var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
1.2267 + return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
1.2268 + }), function (node) {
1.2269 + return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
1.2270 + });
1.2271 + var previousScrollTop = element.scrollTop;
1.2272 +
1.2273 + var value = ko.utils.unwrapObservable(valueAccessor());
1.2274 + var selectedValue = element.value;
1.2275 +
1.2276 + // Remove all existing <option>s.
1.2277 + // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
1.2278 + while (element.length > 0) {
1.2279 + ko.cleanNode(element.options[0]);
1.2280 + element.remove(0);
1.2281 + }
1.2282 +
1.2283 + if (value) {
1.2284 + var allBindings = allBindingsAccessor();
1.2285 + if (typeof value.length != "number")
1.2286 + value = [value];
1.2287 + if (allBindings['optionsCaption']) {
1.2288 + var option = document.createElement("option");
1.2289 + ko.utils.setHtml(option, allBindings['optionsCaption']);
1.2290 + ko.selectExtensions.writeValue(option, undefined);
1.2291 + element.appendChild(option);
1.2292 + }
1.2293 + for (var i = 0, j = value.length; i < j; i++) {
1.2294 + var option = document.createElement("option");
1.2295 +
1.2296 + // Apply a value to the option element
1.2297 + var optionValue = typeof allBindings['optionsValue'] == "string" ? value[i][allBindings['optionsValue']] : value[i];
1.2298 + optionValue = ko.utils.unwrapObservable(optionValue);
1.2299 + ko.selectExtensions.writeValue(option, optionValue);
1.2300 +
1.2301 + // Apply some text to the option element
1.2302 + var optionsTextValue = allBindings['optionsText'];
1.2303 + var optionText;
1.2304 + if (typeof optionsTextValue == "function")
1.2305 + optionText = optionsTextValue(value[i]); // Given a function; run it against the data value
1.2306 + else if (typeof optionsTextValue == "string")
1.2307 + optionText = value[i][optionsTextValue]; // Given a string; treat it as a property name on the data value
1.2308 + else
1.2309 + optionText = optionValue; // Given no optionsText arg; use the data value itself
1.2310 + if ((optionText === null) || (optionText === undefined))
1.2311 + optionText = "";
1.2312 +
1.2313 + ko.utils.setTextContent(option, optionText);
1.2314 +
1.2315 + element.appendChild(option);
1.2316 + }
1.2317 +
1.2318 + // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
1.2319 + // That's why we first added them without selection. Now it's time to set the selection.
1.2320 + var newOptions = element.getElementsByTagName("option");
1.2321 + var countSelectionsRetained = 0;
1.2322 + for (var i = 0, j = newOptions.length; i < j; i++) {
1.2323 + if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
1.2324 + ko.utils.setOptionNodeSelectionState(newOptions[i], true);
1.2325 + countSelectionsRetained++;
1.2326 + }
1.2327 + }
1.2328 +
1.2329 + element.scrollTop = previousScrollTop;
1.2330 +
1.2331 + if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
1.2332 + // Ensure consistency between model value and selected option.
1.2333 + // If the dropdown is being populated for the first time here (or was otherwise previously empty),
1.2334 + // the dropdown selection state is meaningless, so we preserve the model value.
1.2335 + ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.unwrapObservable(allBindings['value']), /* preferModelValue */ true);
1.2336 + }
1.2337 +
1.2338 + // Workaround for IE9 bug
1.2339 + ko.utils.ensureSelectElementIsRenderedCorrectly(element);
1.2340 + }
1.2341 + }
1.2342 +};
1.2343 +ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
1.2344 +
1.2345 +ko.bindingHandlers['selectedOptions'] = {
1.2346 + getSelectedValuesFromSelectNode: function (selectNode) {
1.2347 + var result = [];
1.2348 + var nodes = selectNode.childNodes;
1.2349 + for (var i = 0, j = nodes.length; i < j; i++) {
1.2350 + var node = nodes[i], tagName = ko.utils.tagNameLower(node);
1.2351 + if (tagName == "option" && node.selected)
1.2352 + result.push(ko.selectExtensions.readValue(node));
1.2353 + else if (tagName == "optgroup") {
1.2354 + var selectedValuesFromOptGroup = ko.bindingHandlers['selectedOptions'].getSelectedValuesFromSelectNode(node);
1.2355 + Array.prototype.splice.apply(result, [result.length, 0].concat(selectedValuesFromOptGroup)); // Add new entries to existing 'result' instance
1.2356 + }
1.2357 + }
1.2358 + return result;
1.2359 + },
1.2360 + 'init': function (element, valueAccessor, allBindingsAccessor) {
1.2361 + ko.utils.registerEventHandler(element, "change", function () {
1.2362 + var value = valueAccessor();
1.2363 + var valueToWrite = ko.bindingHandlers['selectedOptions'].getSelectedValuesFromSelectNode(this);
1.2364 + ko.jsonExpressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
1.2365 + });
1.2366 + },
1.2367 + 'update': function (element, valueAccessor) {
1.2368 + if (ko.utils.tagNameLower(element) != "select")
1.2369 + throw new Error("values binding applies only to SELECT elements");
1.2370 +
1.2371 + var newValue = ko.utils.unwrapObservable(valueAccessor());
1.2372 + if (newValue && typeof newValue.length == "number") {
1.2373 + var nodes = element.childNodes;
1.2374 + for (var i = 0, j = nodes.length; i < j; i++) {
1.2375 + var node = nodes[i];
1.2376 + if (ko.utils.tagNameLower(node) === "option")
1.2377 + ko.utils.setOptionNodeSelectionState(node, ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0);
1.2378 + }
1.2379 + }
1.2380 + }
1.2381 +};
1.2382 +
1.2383 +ko.bindingHandlers['text'] = {
1.2384 + 'update': function (element, valueAccessor) {
1.2385 + ko.utils.setTextContent(element, valueAccessor());
1.2386 + }
1.2387 +};
1.2388 +
1.2389 +ko.bindingHandlers['html'] = {
1.2390 + 'init': function() {
1.2391 + // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
1.2392 + return { 'controlsDescendantBindings': true };
1.2393 + },
1.2394 + 'update': function (element, valueAccessor) {
1.2395 + var value = ko.utils.unwrapObservable(valueAccessor());
1.2396 + ko.utils.setHtml(element, value);
1.2397 + }
1.2398 +};
1.2399 +
1.2400 +ko.bindingHandlers['css'] = {
1.2401 + 'update': function (element, valueAccessor) {
1.2402 + var value = ko.utils.unwrapObservable(valueAccessor() || {});
1.2403 + for (var className in value) {
1.2404 + if (typeof className == "string") {
1.2405 + var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
1.2406 + ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
1.2407 + }
1.2408 + }
1.2409 + }
1.2410 +};
1.2411 +
1.2412 +ko.bindingHandlers['style'] = {
1.2413 + 'update': function (element, valueAccessor) {
1.2414 + var value = ko.utils.unwrapObservable(valueAccessor() || {});
1.2415 + for (var styleName in value) {
1.2416 + if (typeof styleName == "string") {
1.2417 + var styleValue = ko.utils.unwrapObservable(value[styleName]);
1.2418 + element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
1.2419 + }
1.2420 + }
1.2421 + }
1.2422 +};
1.2423 +
1.2424 +ko.bindingHandlers['uniqueName'] = {
1.2425 + 'init': function (element, valueAccessor) {
1.2426 + if (valueAccessor()) {
1.2427 + element.name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
1.2428 +
1.2429 + // Workaround IE 6/7 issue
1.2430 + // - https://github.com/SteveSanderson/knockout/issues/197
1.2431 + // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
1.2432 + if (ko.utils.isIe6 || ko.utils.isIe7)
1.2433 + element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
1.2434 + }
1.2435 + }
1.2436 +};
1.2437 +ko.bindingHandlers['uniqueName'].currentIndex = 0;
1.2438 +
1.2439 +ko.bindingHandlers['checked'] = {
1.2440 + 'init': function (element, valueAccessor, allBindingsAccessor) {
1.2441 + var updateHandler = function() {
1.2442 + var valueToWrite;
1.2443 + if (element.type == "checkbox") {
1.2444 + valueToWrite = element.checked;
1.2445 + } else if ((element.type == "radio") && (element.checked)) {
1.2446 + valueToWrite = element.value;
1.2447 + } else {
1.2448 + return; // "checked" binding only responds to checkboxes and selected radio buttons
1.2449 + }
1.2450 +
1.2451 + var modelValue = valueAccessor();
1.2452 + if ((element.type == "checkbox") && (ko.utils.unwrapObservable(modelValue) instanceof Array)) {
1.2453 + // For checkboxes bound to an array, we add/remove the checkbox value to that array
1.2454 + // This works for both observable and non-observable arrays
1.2455 + var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.unwrapObservable(modelValue), element.value);
1.2456 + if (element.checked && (existingEntryIndex < 0))
1.2457 + modelValue.push(element.value);
1.2458 + else if ((!element.checked) && (existingEntryIndex >= 0))
1.2459 + modelValue.splice(existingEntryIndex, 1);
1.2460 + } else {
1.2461 + ko.jsonExpressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
1.2462 + }
1.2463 + };
1.2464 + ko.utils.registerEventHandler(element, "click", updateHandler);
1.2465 +
1.2466 + // IE 6 won't allow radio buttons to be selected unless they have a name
1.2467 + if ((element.type == "radio") && !element.name)
1.2468 + ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
1.2469 + },
1.2470 + 'update': function (element, valueAccessor) {
1.2471 + var value = ko.utils.unwrapObservable(valueAccessor());
1.2472 +
1.2473 + if (element.type == "checkbox") {
1.2474 + if (value instanceof Array) {
1.2475 + // When bound to an array, the checkbox being checked represents its value being present in that array
1.2476 + element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
1.2477 + } else {
1.2478 + // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
1.2479 + element.checked = value;
1.2480 + }
1.2481 + } else if (element.type == "radio") {
1.2482 + element.checked = (element.value == value);
1.2483 + }
1.2484 + }
1.2485 +};
1.2486 +
1.2487 +var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
1.2488 +ko.bindingHandlers['attr'] = {
1.2489 + 'update': function(element, valueAccessor, allBindingsAccessor) {
1.2490 + var value = ko.utils.unwrapObservable(valueAccessor()) || {};
1.2491 + for (var attrName in value) {
1.2492 + if (typeof attrName == "string") {
1.2493 + var attrValue = ko.utils.unwrapObservable(value[attrName]);
1.2494 +
1.2495 + // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
1.2496 + // when someProp is a "no value"-like value (strictly null, false, or undefined)
1.2497 + // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
1.2498 + var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
1.2499 + if (toRemove)
1.2500 + element.removeAttribute(attrName);
1.2501 +
1.2502 + // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
1.2503 + // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
1.2504 + // but instead of figuring out the mode, we'll just set the attribute through the Javascript
1.2505 + // property for IE <= 8.
1.2506 + if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
1.2507 + attrName = attrHtmlToJavascriptMap[attrName];
1.2508 + if (toRemove)
1.2509 + element.removeAttribute(attrName);
1.2510 + else
1.2511 + element[attrName] = attrValue;
1.2512 + } else if (!toRemove) {
1.2513 + element.setAttribute(attrName, attrValue.toString());
1.2514 + }
1.2515 + }
1.2516 + }
1.2517 + }
1.2518 +};
1.2519 +
1.2520 +ko.bindingHandlers['hasfocus'] = {
1.2521 + 'init': function(element, valueAccessor, allBindingsAccessor) {
1.2522 + var writeValue = function(valueToWrite) {
1.2523 + var modelValue = valueAccessor();
1.2524 + ko.jsonExpressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', valueToWrite, true);
1.2525 + };
1.2526 + ko.utils.registerEventHandler(element, "focus", function() { writeValue(true) });
1.2527 + ko.utils.registerEventHandler(element, "focusin", function() { writeValue(true) }); // For IE
1.2528 + ko.utils.registerEventHandler(element, "blur", function() { writeValue(false) });
1.2529 + ko.utils.registerEventHandler(element, "focusout", function() { writeValue(false) }); // For IE
1.2530 + },
1.2531 + 'update': function(element, valueAccessor) {
1.2532 + var value = ko.utils.unwrapObservable(valueAccessor());
1.2533 + value ? element.focus() : element.blur();
1.2534 + ko.utils.triggerEvent(element, value ? "focusin" : "focusout"); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
1.2535 + }
1.2536 +};
1.2537 +
1.2538 +// "with: someExpression" is equivalent to "template: { if: someExpression, data: someExpression }"
1.2539 +ko.bindingHandlers['with'] = {
1.2540 + makeTemplateValueAccessor: function(valueAccessor) {
1.2541 + return function() { var value = valueAccessor(); return { 'if': value, 'data': value, 'templateEngine': ko.nativeTemplateEngine.instance } };
1.2542 + },
1.2543 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
1.2544 + return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['with'].makeTemplateValueAccessor(valueAccessor));
1.2545 + },
1.2546 + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
1.2547 + return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['with'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
1.2548 + }
1.2549 +};
1.2550 +ko.jsonExpressionRewriting.bindingRewriteValidators['with'] = false; // Can't rewrite control flow bindings
1.2551 +ko.virtualElements.allowedBindings['with'] = true;
1.2552 +
1.2553 +// "if: someExpression" is equivalent to "template: { if: someExpression }"
1.2554 +ko.bindingHandlers['if'] = {
1.2555 + makeTemplateValueAccessor: function(valueAccessor) {
1.2556 + return function() { return { 'if': valueAccessor(), 'templateEngine': ko.nativeTemplateEngine.instance } };
1.2557 + },
1.2558 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
1.2559 + return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['if'].makeTemplateValueAccessor(valueAccessor));
1.2560 + },
1.2561 + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
1.2562 + return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['if'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
1.2563 + }
1.2564 +};
1.2565 +ko.jsonExpressionRewriting.bindingRewriteValidators['if'] = false; // Can't rewrite control flow bindings
1.2566 +ko.virtualElements.allowedBindings['if'] = true;
1.2567 +
1.2568 +// "ifnot: someExpression" is equivalent to "template: { ifnot: someExpression }"
1.2569 +ko.bindingHandlers['ifnot'] = {
1.2570 + makeTemplateValueAccessor: function(valueAccessor) {
1.2571 + return function() { return { 'ifnot': valueAccessor(), 'templateEngine': ko.nativeTemplateEngine.instance } };
1.2572 + },
1.2573 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
1.2574 + return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['ifnot'].makeTemplateValueAccessor(valueAccessor));
1.2575 + },
1.2576 + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
1.2577 + return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['ifnot'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
1.2578 + }
1.2579 +};
1.2580 +ko.jsonExpressionRewriting.bindingRewriteValidators['ifnot'] = false; // Can't rewrite control flow bindings
1.2581 +ko.virtualElements.allowedBindings['ifnot'] = true;
1.2582 +
1.2583 +// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
1.2584 +// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
1.2585 +ko.bindingHandlers['foreach'] = {
1.2586 + makeTemplateValueAccessor: function(valueAccessor) {
1.2587 + return function() {
1.2588 + var bindingValue = ko.utils.unwrapObservable(valueAccessor());
1.2589 +
1.2590 + // If bindingValue is the array, just pass it on its own
1.2591 + if ((!bindingValue) || typeof bindingValue.length == "number")
1.2592 + return { 'foreach': bindingValue, 'templateEngine': ko.nativeTemplateEngine.instance };
1.2593 +
1.2594 + // If bindingValue.data is the array, preserve all relevant options
1.2595 + return {
1.2596 + 'foreach': bindingValue['data'],
1.2597 + 'includeDestroyed': bindingValue['includeDestroyed'],
1.2598 + 'afterAdd': bindingValue['afterAdd'],
1.2599 + 'beforeRemove': bindingValue['beforeRemove'],
1.2600 + 'afterRender': bindingValue['afterRender'],
1.2601 + 'templateEngine': ko.nativeTemplateEngine.instance
1.2602 + };
1.2603 + };
1.2604 + },
1.2605 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
1.2606 + return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
1.2607 + },
1.2608 + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
1.2609 + return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
1.2610 + }
1.2611 +};
1.2612 +ko.jsonExpressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
1.2613 +ko.virtualElements.allowedBindings['foreach'] = true;
1.2614 +// If you want to make a custom template engine,
1.2615 +//
1.2616 +// [1] Inherit from this class (like ko.nativeTemplateEngine does)
1.2617 +// [2] Override 'renderTemplateSource', supplying a function with this signature:
1.2618 +//
1.2619 +// function (templateSource, bindingContext, options) {
1.2620 +// // - templateSource.text() is the text of the template you should render
1.2621 +// // - bindingContext.$data is the data you should pass into the template
1.2622 +// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
1.2623 +// // and bindingContext.$root available in the template too
1.2624 +// // - options gives you access to any other properties set on "data-bind: { template: options }"
1.2625 +// //
1.2626 +// // Return value: an array of DOM nodes
1.2627 +// }
1.2628 +//
1.2629 +// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
1.2630 +//
1.2631 +// function (script) {
1.2632 +// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
1.2633 +// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
1.2634 +// }
1.2635 +//
1.2636 +// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
1.2637 +// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
1.2638 +// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
1.2639 +
1.2640 +ko.templateEngine = function () { };
1.2641 +
1.2642 +ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
1.2643 + throw new Error("Override renderTemplateSource");
1.2644 +};
1.2645 +
1.2646 +ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
1.2647 + throw new Error("Override createJavaScriptEvaluatorBlock");
1.2648 +};
1.2649 +
1.2650 +ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
1.2651 + // Named template
1.2652 + if (typeof template == "string") {
1.2653 + templateDocument = templateDocument || document;
1.2654 + var elem = templateDocument.getElementById(template);
1.2655 + if (!elem)
1.2656 + throw new Error("Cannot find template with ID " + template);
1.2657 + return new ko.templateSources.domElement(elem);
1.2658 + } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
1.2659 + // Anonymous template
1.2660 + return new ko.templateSources.anonymousTemplate(template);
1.2661 + } else
1.2662 + throw new Error("Unknown template type: " + template);
1.2663 +};
1.2664 +
1.2665 +ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
1.2666 + var templateSource = this['makeTemplateSource'](template, templateDocument);
1.2667 + return this['renderTemplateSource'](templateSource, bindingContext, options);
1.2668 +};
1.2669 +
1.2670 +ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
1.2671 + // Skip rewriting if requested
1.2672 + if (this['allowTemplateRewriting'] === false)
1.2673 + return true;
1.2674 +
1.2675 + // Perf optimisation - see below
1.2676 + var templateIsInExternalDocument = templateDocument && templateDocument != document;
1.2677 + if (!templateIsInExternalDocument && this.knownRewrittenTemplates && this.knownRewrittenTemplates[template])
1.2678 + return true;
1.2679 +
1.2680 + return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
1.2681 +};
1.2682 +
1.2683 +ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
1.2684 + var templateSource = this['makeTemplateSource'](template, templateDocument);
1.2685 + var rewritten = rewriterCallback(templateSource['text']());
1.2686 + templateSource['text'](rewritten);
1.2687 + templateSource['data']("isRewritten", true);
1.2688 +
1.2689 + // Perf optimisation - for named templates, track which ones have been rewritten so we can
1.2690 + // answer 'isTemplateRewritten' *without* having to use getElementById (which is slow on IE < 8)
1.2691 + //
1.2692 + // Note that we only cache the status for templates in the main document, because caching on a per-doc
1.2693 + // basis complicates the implementation excessively. In a future version of KO, we will likely remove
1.2694 + // this 'isRewritten' cache entirely anyway, because the benefit is extremely minor and only applies
1.2695 + // to rewritable templates, which are pretty much deprecated since KO 2.0.
1.2696 + var templateIsInExternalDocument = templateDocument && templateDocument != document;
1.2697 + if (!templateIsInExternalDocument && typeof template == "string") {
1.2698 + this.knownRewrittenTemplates = this.knownRewrittenTemplates || {};
1.2699 + this.knownRewrittenTemplates[template] = true;
1.2700 + }
1.2701 +};
1.2702 +
1.2703 +ko.exportSymbol('templateEngine', ko.templateEngine);
1.2704 +
1.2705 +ko.templateRewriting = (function () {
1.2706 + var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
1.2707 + var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
1.2708 +
1.2709 + function validateDataBindValuesForRewriting(keyValueArray) {
1.2710 + var allValidators = ko.jsonExpressionRewriting.bindingRewriteValidators;
1.2711 + for (var i = 0; i < keyValueArray.length; i++) {
1.2712 + var key = keyValueArray[i]['key'];
1.2713 + if (allValidators.hasOwnProperty(key)) {
1.2714 + var validator = allValidators[key];
1.2715 +
1.2716 + if (typeof validator === "function") {
1.2717 + var possibleErrorMessage = validator(keyValueArray[i]['value']);
1.2718 + if (possibleErrorMessage)
1.2719 + throw new Error(possibleErrorMessage);
1.2720 + } else if (!validator) {
1.2721 + throw new Error("This template engine does not support the '" + key + "' binding within its templates");
1.2722 + }
1.2723 + }
1.2724 + }
1.2725 + }
1.2726 +
1.2727 + function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
1.2728 + var dataBindKeyValueArray = ko.jsonExpressionRewriting.parseObjectLiteral(dataBindAttributeValue);
1.2729 + validateDataBindValuesForRewriting(dataBindKeyValueArray);
1.2730 + var rewrittenDataBindAttributeValue = ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson(dataBindKeyValueArray);
1.2731 +
1.2732 + // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
1.2733 + // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
1.2734 + // extra indirection.
1.2735 + var applyBindingsToNextSiblingScript = "ko.templateRewriting.applyMemoizedBindingsToNextSibling(function() { \
1.2736 + return (function() { return { " + rewrittenDataBindAttributeValue + " } })() \
1.2737 + })";
1.2738 + return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
1.2739 + }
1.2740 +
1.2741 + return {
1.2742 + ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
1.2743 + if (!templateEngine['isTemplateRewritten'](template, templateDocument))
1.2744 + templateEngine['rewriteTemplate'](template, function (htmlString) {
1.2745 + return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
1.2746 + }, templateDocument);
1.2747 + },
1.2748 +
1.2749 + memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
1.2750 + return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
1.2751 + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
1.2752 + }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
1.2753 + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
1.2754 + });
1.2755 + },
1.2756 +
1.2757 + applyMemoizedBindingsToNextSibling: function (bindings) {
1.2758 + return ko.memoization.memoize(function (domNode, bindingContext) {
1.2759 + if (domNode.nextSibling)
1.2760 + ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
1.2761 + });
1.2762 + }
1.2763 + }
1.2764 +})();
1.2765 +
1.2766 +ko.exportSymbol('templateRewriting', ko.templateRewriting);
1.2767 +ko.exportSymbol('templateRewriting.applyMemoizedBindingsToNextSibling', ko.templateRewriting.applyMemoizedBindingsToNextSibling); // Exported only because it has to be referenced by string lookup from within rewritten template
1.2768 +(function() {
1.2769 + // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
1.2770 + // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
1.2771 + //
1.2772 + // Two are provided by default:
1.2773 + // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
1.2774 + // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
1.2775 + // without reading/writing the actual element text content, since it will be overwritten
1.2776 + // with the rendered template output.
1.2777 + // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
1.2778 + // Template sources need to have the following functions:
1.2779 + // text() - returns the template text from your storage location
1.2780 + // text(value) - writes the supplied template text to your storage location
1.2781 + // data(key) - reads values stored using data(key, value) - see below
1.2782 + // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
1.2783 + //
1.2784 + // Optionally, template sources can also have the following functions:
1.2785 + // nodes() - returns a DOM element containing the nodes of this template, where available
1.2786 + // nodes(value) - writes the given DOM element to your storage location
1.2787 + // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
1.2788 + // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
1.2789 + //
1.2790 + // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
1.2791 + // using and overriding "makeTemplateSource" to return an instance of your custom template source.
1.2792 +
1.2793 + ko.templateSources = {};
1.2794 +
1.2795 + // ---- ko.templateSources.domElement -----
1.2796 +
1.2797 + ko.templateSources.domElement = function(element) {
1.2798 + this.domElement = element;
1.2799 + }
1.2800 +
1.2801 + ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
1.2802 + var tagNameLower = ko.utils.tagNameLower(this.domElement),
1.2803 + elemContentsProperty = tagNameLower === "script" ? "text"
1.2804 + : tagNameLower === "textarea" ? "value"
1.2805 + : "innerHTML";
1.2806 +
1.2807 + if (arguments.length == 0) {
1.2808 + return this.domElement[elemContentsProperty];
1.2809 + } else {
1.2810 + var valueToWrite = arguments[0];
1.2811 + if (elemContentsProperty === "innerHTML")
1.2812 + ko.utils.setHtml(this.domElement, valueToWrite);
1.2813 + else
1.2814 + this.domElement[elemContentsProperty] = valueToWrite;
1.2815 + }
1.2816 + };
1.2817 +
1.2818 + ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
1.2819 + if (arguments.length === 1) {
1.2820 + return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
1.2821 + } else {
1.2822 + ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
1.2823 + }
1.2824 + };
1.2825 +
1.2826 + // ---- ko.templateSources.anonymousTemplate -----
1.2827 + // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
1.2828 + // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
1.2829 + // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
1.2830 +
1.2831 + var anonymousTemplatesDomDataKey = "__ko_anon_template__";
1.2832 + ko.templateSources.anonymousTemplate = function(element) {
1.2833 + this.domElement = element;
1.2834 + }
1.2835 + ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
1.2836 + ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
1.2837 + if (arguments.length == 0) {
1.2838 + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
1.2839 + if (templateData.textData === undefined && templateData.containerData)
1.2840 + templateData.textData = templateData.containerData.innerHTML;
1.2841 + return templateData.textData;
1.2842 + } else {
1.2843 + var valueToWrite = arguments[0];
1.2844 + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
1.2845 + }
1.2846 + };
1.2847 + ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
1.2848 + if (arguments.length == 0) {
1.2849 + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
1.2850 + return templateData.containerData;
1.2851 + } else {
1.2852 + var valueToWrite = arguments[0];
1.2853 + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
1.2854 + }
1.2855 + };
1.2856 +
1.2857 + ko.exportSymbol('templateSources', ko.templateSources);
1.2858 + ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
1.2859 + ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
1.2860 +})();
1.2861 +(function () {
1.2862 + var _templateEngine;
1.2863 + ko.setTemplateEngine = function (templateEngine) {
1.2864 + if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
1.2865 + throw new Error("templateEngine must inherit from ko.templateEngine");
1.2866 + _templateEngine = templateEngine;
1.2867 + }
1.2868 +
1.2869 + function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
1.2870 + var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
1.2871 + while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
1.2872 + nextInQueue = ko.virtualElements.nextSibling(node);
1.2873 + if (node.nodeType === 1 || node.nodeType === 8)
1.2874 + action(node);
1.2875 + }
1.2876 + }
1.2877 +
1.2878 + function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
1.2879 + // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
1.2880 + // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
1.2881 + // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
1.2882 + // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
1.2883 + // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
1.2884 +
1.2885 + if (continuousNodeArray.length) {
1.2886 + var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
1.2887 +
1.2888 + // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
1.2889 + // whereas a regular applyBindings won't introduce new memoized nodes
1.2890 + invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
1.2891 + ko.applyBindings(bindingContext, node);
1.2892 + });
1.2893 + invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
1.2894 + ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
1.2895 + });
1.2896 + }
1.2897 + }
1.2898 +
1.2899 + function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
1.2900 + return nodeOrNodeArray.nodeType ? nodeOrNodeArray
1.2901 + : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
1.2902 + : null;
1.2903 + }
1.2904 +
1.2905 + function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
1.2906 + options = options || {};
1.2907 + var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
1.2908 + var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
1.2909 + var templateEngineToUse = (options['templateEngine'] || _templateEngine);
1.2910 + ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
1.2911 + var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
1.2912 +
1.2913 + // Loosely check result is an array of DOM nodes
1.2914 + if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
1.2915 + throw new Error("Template engine must return an array of DOM nodes");
1.2916 +
1.2917 + var haveAddedNodesToParent = false;
1.2918 + switch (renderMode) {
1.2919 + case "replaceChildren":
1.2920 + ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
1.2921 + haveAddedNodesToParent = true;
1.2922 + break;
1.2923 + case "replaceNode":
1.2924 + ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
1.2925 + haveAddedNodesToParent = true;
1.2926 + break;
1.2927 + case "ignoreTargetNode": break;
1.2928 + default:
1.2929 + throw new Error("Unknown renderMode: " + renderMode);
1.2930 + }
1.2931 +
1.2932 + if (haveAddedNodesToParent) {
1.2933 + activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
1.2934 + if (options['afterRender'])
1.2935 + options['afterRender'](renderedNodesArray, bindingContext['$data']);
1.2936 + }
1.2937 +
1.2938 + return renderedNodesArray;
1.2939 + }
1.2940 +
1.2941 + ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
1.2942 + options = options || {};
1.2943 + if ((options['templateEngine'] || _templateEngine) == undefined)
1.2944 + throw new Error("Set a template engine before calling renderTemplate");
1.2945 + renderMode = renderMode || "replaceChildren";
1.2946 +
1.2947 + if (targetNodeOrNodeArray) {
1.2948 + var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
1.2949 +
1.2950 + var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
1.2951 + var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
1.2952 +
1.2953 + return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
1.2954 + function () {
1.2955 + // Ensure we've got a proper binding context to work with
1.2956 + var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
1.2957 + ? dataOrBindingContext
1.2958 + : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
1.2959 +
1.2960 + // Support selecting template as a function of the data being rendered
1.2961 + var templateName = typeof(template) == 'function' ? template(bindingContext['$data']) : template;
1.2962 +
1.2963 + var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
1.2964 + if (renderMode == "replaceNode") {
1.2965 + targetNodeOrNodeArray = renderedNodesArray;
1.2966 + firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
1.2967 + }
1.2968 + },
1.2969 + null,
1.2970 + { 'disposeWhen': whenToDispose, 'disposeWhenNodeIsRemoved': activelyDisposeWhenNodeIsRemoved }
1.2971 + );
1.2972 + } else {
1.2973 + // We don't yet have a DOM node to evaluate, so use a memo and render the template later when there is a DOM node
1.2974 + return ko.memoization.memoize(function (domNode) {
1.2975 + ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
1.2976 + });
1.2977 + }
1.2978 + };
1.2979 +
1.2980 + ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
1.2981 + // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
1.2982 + // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
1.2983 + var arrayItemContext;
1.2984 +
1.2985 + // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
1.2986 + var executeTemplateForArrayItem = function (arrayValue, index) {
1.2987 + // Support selecting template as a function of the data being rendered
1.2988 + var templateName = typeof(template) == 'function' ? template(arrayValue) : template;
1.2989 + arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue));
1.2990 + arrayItemContext['$index'] = index;
1.2991 + return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
1.2992 + }
1.2993 +
1.2994 + // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
1.2995 + var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
1.2996 + activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
1.2997 + if (options['afterRender'])
1.2998 + options['afterRender'](addedNodesArray, arrayValue);
1.2999 + };
1.3000 +
1.3001 + return ko.dependentObservable(function () {
1.3002 + var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
1.3003 + if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
1.3004 + unwrappedArray = [unwrappedArray];
1.3005 +
1.3006 + // Filter out any entries marked as destroyed
1.3007 + var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
1.3008 + return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
1.3009 + });
1.3010 +
1.3011 + ko.utils.setDomNodeChildrenFromArrayMapping(targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback);
1.3012 +
1.3013 + }, null, { 'disposeWhenNodeIsRemoved': targetNode });
1.3014 + };
1.3015 +
1.3016 + var templateSubscriptionDomDataKey = '__ko__templateSubscriptionDomDataKey__';
1.3017 + function disposeOldSubscriptionAndStoreNewOne(element, newSubscription) {
1.3018 + var oldSubscription = ko.utils.domData.get(element, templateSubscriptionDomDataKey);
1.3019 + if (oldSubscription && (typeof(oldSubscription.dispose) == 'function'))
1.3020 + oldSubscription.dispose();
1.3021 + ko.utils.domData.set(element, templateSubscriptionDomDataKey, newSubscription);
1.3022 + }
1.3023 +
1.3024 + ko.bindingHandlers['template'] = {
1.3025 + 'init': function(element, valueAccessor) {
1.3026 + // Support anonymous templates
1.3027 + var bindingValue = ko.utils.unwrapObservable(valueAccessor());
1.3028 + if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
1.3029 + // It's an anonymous template - store the element contents, then clear the element
1.3030 + var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
1.3031 + container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
1.3032 + new ko.templateSources.anonymousTemplate(element)['nodes'](container);
1.3033 + }
1.3034 + return { 'controlsDescendantBindings': true };
1.3035 + },
1.3036 + 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
1.3037 + var bindingValue = ko.utils.unwrapObservable(valueAccessor());
1.3038 + var templateName;
1.3039 + var shouldDisplay = true;
1.3040 +
1.3041 + if (typeof bindingValue == "string") {
1.3042 + templateName = bindingValue;
1.3043 + } else {
1.3044 + templateName = bindingValue['name'];
1.3045 +
1.3046 + // Support "if"/"ifnot" conditions
1.3047 + if ('if' in bindingValue)
1.3048 + shouldDisplay = shouldDisplay && ko.utils.unwrapObservable(bindingValue['if']);
1.3049 + if ('ifnot' in bindingValue)
1.3050 + shouldDisplay = shouldDisplay && !ko.utils.unwrapObservable(bindingValue['ifnot']);
1.3051 + }
1.3052 +
1.3053 + var templateSubscription = null;
1.3054 +
1.3055 + if ((typeof bindingValue === 'object') && ('foreach' in bindingValue)) { // Note: can't use 'in' operator on strings
1.3056 + // Render once for each data point (treating data set as empty if shouldDisplay==false)
1.3057 + var dataArray = (shouldDisplay && bindingValue['foreach']) || [];
1.3058 + templateSubscription = ko.renderTemplateForEach(templateName || element, dataArray, /* options: */ bindingValue, element, bindingContext);
1.3059 + } else {
1.3060 + if (shouldDisplay) {
1.3061 + // Render once for this single data point (or use the viewModel if no data was provided)
1.3062 + var innerBindingContext = (typeof bindingValue == 'object') && ('data' in bindingValue)
1.3063 + ? bindingContext['createChildContext'](ko.utils.unwrapObservable(bindingValue['data'])) // Given an explitit 'data' value, we create a child binding context for it
1.3064 + : bindingContext; // Given no explicit 'data' value, we retain the same binding context
1.3065 + templateSubscription = ko.renderTemplate(templateName || element, innerBindingContext, /* options: */ bindingValue, element);
1.3066 + } else
1.3067 + ko.virtualElements.emptyNode(element);
1.3068 + }
1.3069 +
1.3070 + // It only makes sense to have a single template subscription per element (otherwise which one should have its output displayed?)
1.3071 + disposeOldSubscriptionAndStoreNewOne(element, templateSubscription);
1.3072 + }
1.3073 + };
1.3074 +
1.3075 + // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
1.3076 + ko.jsonExpressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
1.3077 + var parsedBindingValue = ko.jsonExpressionRewriting.parseObjectLiteral(bindingValue);
1.3078 +
1.3079 + if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
1.3080 + return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
1.3081 +
1.3082 + if (ko.jsonExpressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
1.3083 + return null; // Named templates can be rewritten, so return "no error"
1.3084 + return "This template engine does not support anonymous templates nested within its templates";
1.3085 + };
1.3086 +
1.3087 + ko.virtualElements.allowedBindings['template'] = true;
1.3088 +})();
1.3089 +
1.3090 +ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
1.3091 +ko.exportSymbol('renderTemplate', ko.renderTemplate);
1.3092 +
1.3093 +(function () {
1.3094 + // Simple calculation based on Levenshtein distance.
1.3095 + function calculateEditDistanceMatrix(oldArray, newArray, maxAllowedDistance) {
1.3096 + var distances = [];
1.3097 + for (var i = 0; i <= newArray.length; i++)
1.3098 + distances[i] = [];
1.3099 +
1.3100 + // Top row - transform old array into empty array via deletions
1.3101 + for (var i = 0, j = Math.min(oldArray.length, maxAllowedDistance); i <= j; i++)
1.3102 + distances[0][i] = i;
1.3103 +
1.3104 + // Left row - transform empty array into new array via additions
1.3105 + for (var i = 1, j = Math.min(newArray.length, maxAllowedDistance); i <= j; i++) {
1.3106 + distances[i][0] = i;
1.3107 + }
1.3108 +
1.3109 + // Fill out the body of the array
1.3110 + var oldIndex, oldIndexMax = oldArray.length, newIndex, newIndexMax = newArray.length;
1.3111 + var distanceViaAddition, distanceViaDeletion;
1.3112 + for (oldIndex = 1; oldIndex <= oldIndexMax; oldIndex++) {
1.3113 + var newIndexMinForRow = Math.max(1, oldIndex - maxAllowedDistance);
1.3114 + var newIndexMaxForRow = Math.min(newIndexMax, oldIndex + maxAllowedDistance);
1.3115 + for (newIndex = newIndexMinForRow; newIndex <= newIndexMaxForRow; newIndex++) {
1.3116 + if (oldArray[oldIndex - 1] === newArray[newIndex - 1])
1.3117 + distances[newIndex][oldIndex] = distances[newIndex - 1][oldIndex - 1];
1.3118 + else {
1.3119 + var northDistance = distances[newIndex - 1][oldIndex] === undefined ? Number.MAX_VALUE : distances[newIndex - 1][oldIndex] + 1;
1.3120 + var westDistance = distances[newIndex][oldIndex - 1] === undefined ? Number.MAX_VALUE : distances[newIndex][oldIndex - 1] + 1;
1.3121 + distances[newIndex][oldIndex] = Math.min(northDistance, westDistance);
1.3122 + }
1.3123 + }
1.3124 + }
1.3125 +
1.3126 + return distances;
1.3127 + }
1.3128 +
1.3129 + function findEditScriptFromEditDistanceMatrix(editDistanceMatrix, oldArray, newArray) {
1.3130 + var oldIndex = oldArray.length;
1.3131 + var newIndex = newArray.length;
1.3132 + var editScript = [];
1.3133 + var maxDistance = editDistanceMatrix[newIndex][oldIndex];
1.3134 + if (maxDistance === undefined)
1.3135 + return null; // maxAllowedDistance must be too small
1.3136 + while ((oldIndex > 0) || (newIndex > 0)) {
1.3137 + var me = editDistanceMatrix[newIndex][oldIndex];
1.3138 + var distanceViaAdd = (newIndex > 0) ? editDistanceMatrix[newIndex - 1][oldIndex] : maxDistance + 1;
1.3139 + var distanceViaDelete = (oldIndex > 0) ? editDistanceMatrix[newIndex][oldIndex - 1] : maxDistance + 1;
1.3140 + var distanceViaRetain = (newIndex > 0) && (oldIndex > 0) ? editDistanceMatrix[newIndex - 1][oldIndex - 1] : maxDistance + 1;
1.3141 + if ((distanceViaAdd === undefined) || (distanceViaAdd < me - 1)) distanceViaAdd = maxDistance + 1;
1.3142 + if ((distanceViaDelete === undefined) || (distanceViaDelete < me - 1)) distanceViaDelete = maxDistance + 1;
1.3143 + if (distanceViaRetain < me - 1) distanceViaRetain = maxDistance + 1;
1.3144 +
1.3145 + if ((distanceViaAdd <= distanceViaDelete) && (distanceViaAdd < distanceViaRetain)) {
1.3146 + editScript.push({ status: "added", value: newArray[newIndex - 1] });
1.3147 + newIndex--;
1.3148 + } else if ((distanceViaDelete < distanceViaAdd) && (distanceViaDelete < distanceViaRetain)) {
1.3149 + editScript.push({ status: "deleted", value: oldArray[oldIndex - 1] });
1.3150 + oldIndex--;
1.3151 + } else {
1.3152 + editScript.push({ status: "retained", value: oldArray[oldIndex - 1] });
1.3153 + newIndex--;
1.3154 + oldIndex--;
1.3155 + }
1.3156 + }
1.3157 + return editScript.reverse();
1.3158 + }
1.3159 +
1.3160 + ko.utils.compareArrays = function (oldArray, newArray, maxEditsToConsider) {
1.3161 + if (maxEditsToConsider === undefined) {
1.3162 + return ko.utils.compareArrays(oldArray, newArray, 1) // First consider likely case where there is at most one edit (very fast)
1.3163 + || ko.utils.compareArrays(oldArray, newArray, 10) // If that fails, account for a fair number of changes while still being fast
1.3164 + || ko.utils.compareArrays(oldArray, newArray, Number.MAX_VALUE); // Ultimately give the right answer, even though it may take a long time
1.3165 + } else {
1.3166 + oldArray = oldArray || [];
1.3167 + newArray = newArray || [];
1.3168 + var editDistanceMatrix = calculateEditDistanceMatrix(oldArray, newArray, maxEditsToConsider);
1.3169 + return findEditScriptFromEditDistanceMatrix(editDistanceMatrix, oldArray, newArray);
1.3170 + }
1.3171 + };
1.3172 +})();
1.3173 +
1.3174 +ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
1.3175 +
1.3176 +(function () {
1.3177 + // Objective:
1.3178 + // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
1.3179 + // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
1.3180 + // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
1.3181 + // so that its children is again the concatenation of the mappings of the array elements, but don't re-map any array elements that we
1.3182 + // previously mapped - retain those nodes, and just insert/delete other ones
1.3183 +
1.3184 + // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
1.3185 + // You can use this, for example, to activate bindings on those nodes.
1.3186 +
1.3187 + function fixUpVirtualElements(contiguousNodeArray) {
1.3188 + // Ensures that contiguousNodeArray really *is* an array of contiguous siblings, even if some of the interior
1.3189 + // ones have changed since your array was first built (e.g., because your array contains virtual elements, and
1.3190 + // their virtual children changed when binding was applied to them).
1.3191 + // This is needed so that we can reliably remove or update the nodes corresponding to a given array item
1.3192 +
1.3193 + if (contiguousNodeArray.length > 2) {
1.3194 + // Build up the actual new contiguous node set
1.3195 + var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
1.3196 + while (current !== last) {
1.3197 + current = current.nextSibling;
1.3198 + if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
1.3199 + return;
1.3200 + newContiguousSet.push(current);
1.3201 + }
1.3202 +
1.3203 + // ... then mutate the input array to match this.
1.3204 + // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
1.3205 + Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
1.3206 + }
1.3207 + }
1.3208 +
1.3209 + function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
1.3210 + // Map this array value inside a dependentObservable so we re-map when any dependency changes
1.3211 + var mappedNodes = [];
1.3212 + var dependentObservable = ko.dependentObservable(function() {
1.3213 + var newMappedNodes = mapping(valueToMap, index) || [];
1.3214 +
1.3215 + // On subsequent evaluations, just replace the previously-inserted DOM nodes
1.3216 + if (mappedNodes.length > 0) {
1.3217 + fixUpVirtualElements(mappedNodes);
1.3218 + ko.utils.replaceDomNodes(mappedNodes, newMappedNodes);
1.3219 + if (callbackAfterAddingNodes)
1.3220 + callbackAfterAddingNodes(valueToMap, newMappedNodes);
1.3221 + }
1.3222 +
1.3223 + // Replace the contents of the mappedNodes array, thereby updating the record
1.3224 + // of which nodes would be deleted if valueToMap was itself later removed
1.3225 + mappedNodes.splice(0, mappedNodes.length);
1.3226 + ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
1.3227 + }, null, { 'disposeWhenNodeIsRemoved': containerNode, 'disposeWhen': function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
1.3228 + return { mappedNodes : mappedNodes, dependentObservable : dependentObservable };
1.3229 + }
1.3230 +
1.3231 + var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
1.3232 +
1.3233 + ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
1.3234 + // Compare the provided array against the previous one
1.3235 + array = array || [];
1.3236 + options = options || {};
1.3237 + var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
1.3238 + var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
1.3239 + var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
1.3240 + var editScript = ko.utils.compareArrays(lastArray, array);
1.3241 +
1.3242 + // Build the new mapping result
1.3243 + var newMappingResult = [];
1.3244 + var lastMappingResultIndex = 0;
1.3245 + var nodesToDelete = [];
1.3246 + var newMappingResultIndex = 0;
1.3247 + var nodesAdded = [];
1.3248 + var insertAfterNode = null;
1.3249 + for (var i = 0, j = editScript.length; i < j; i++) {
1.3250 + switch (editScript[i].status) {
1.3251 + case "retained":
1.3252 + // Just keep the information - don't touch the nodes
1.3253 + var dataToRetain = lastMappingResult[lastMappingResultIndex];
1.3254 + dataToRetain.indexObservable(newMappingResultIndex);
1.3255 + newMappingResultIndex = newMappingResult.push(dataToRetain);
1.3256 + if (dataToRetain.domNodes.length > 0)
1.3257 + insertAfterNode = dataToRetain.domNodes[dataToRetain.domNodes.length - 1];
1.3258 + lastMappingResultIndex++;
1.3259 + break;
1.3260 +
1.3261 + case "deleted":
1.3262 + // Stop tracking changes to the mapping for these nodes
1.3263 + lastMappingResult[lastMappingResultIndex].dependentObservable.dispose();
1.3264 +
1.3265 + // Queue these nodes for later removal
1.3266 + fixUpVirtualElements(lastMappingResult[lastMappingResultIndex].domNodes);
1.3267 + ko.utils.arrayForEach(lastMappingResult[lastMappingResultIndex].domNodes, function (node) {
1.3268 + nodesToDelete.push({
1.3269 + element: node,
1.3270 + index: i,
1.3271 + value: editScript[i].value
1.3272 + });
1.3273 + insertAfterNode = node;
1.3274 + });
1.3275 + lastMappingResultIndex++;
1.3276 + break;
1.3277 +
1.3278 + case "added":
1.3279 + var valueToMap = editScript[i].value;
1.3280 + var indexObservable = ko.observable(newMappingResultIndex);
1.3281 + var mapData = mapNodeAndRefreshWhenChanged(domNode, mapping, valueToMap, callbackAfterAddingNodes, indexObservable);
1.3282 + var mappedNodes = mapData.mappedNodes;
1.3283 +
1.3284 + // On the first evaluation, insert the nodes at the current insertion point
1.3285 + newMappingResultIndex = newMappingResult.push({
1.3286 + arrayEntry: editScript[i].value,
1.3287 + domNodes: mappedNodes,
1.3288 + dependentObservable: mapData.dependentObservable,
1.3289 + indexObservable: indexObservable
1.3290 + });
1.3291 + for (var nodeIndex = 0, nodeIndexMax = mappedNodes.length; nodeIndex < nodeIndexMax; nodeIndex++) {
1.3292 + var node = mappedNodes[nodeIndex];
1.3293 + nodesAdded.push({
1.3294 + element: node,
1.3295 + index: i,
1.3296 + value: editScript[i].value
1.3297 + });
1.3298 + if (insertAfterNode == null) {
1.3299 + // Insert "node" (the newly-created node) as domNode's first child
1.3300 + ko.virtualElements.prepend(domNode, node);
1.3301 + } else {
1.3302 + // Insert "node" into "domNode" immediately after "insertAfterNode"
1.3303 + ko.virtualElements.insertAfter(domNode, node, insertAfterNode);
1.3304 + }
1.3305 + insertAfterNode = node;
1.3306 + }
1.3307 + if (callbackAfterAddingNodes)
1.3308 + callbackAfterAddingNodes(valueToMap, mappedNodes, indexObservable);
1.3309 + break;
1.3310 + }
1.3311 + }
1.3312 +
1.3313 + ko.utils.arrayForEach(nodesToDelete, function (node) { ko.cleanNode(node.element) });
1.3314 +
1.3315 + var invokedBeforeRemoveCallback = false;
1.3316 + if (!isFirstExecution) {
1.3317 + if (options['afterAdd']) {
1.3318 + for (var i = 0; i < nodesAdded.length; i++)
1.3319 + options['afterAdd'](nodesAdded[i].element, nodesAdded[i].index, nodesAdded[i].value);
1.3320 + }
1.3321 + if (options['beforeRemove']) {
1.3322 + for (var i = 0; i < nodesToDelete.length; i++)
1.3323 + options['beforeRemove'](nodesToDelete[i].element, nodesToDelete[i].index, nodesToDelete[i].value);
1.3324 + invokedBeforeRemoveCallback = true;
1.3325 + }
1.3326 + }
1.3327 + if (!invokedBeforeRemoveCallback && nodesToDelete.length) {
1.3328 + for (var i = 0; i < nodesToDelete.length; i++) {
1.3329 + var element = nodesToDelete[i].element;
1.3330 + if (element.parentNode)
1.3331 + element.parentNode.removeChild(element);
1.3332 + }
1.3333 + }
1.3334 +
1.3335 + // Store a copy of the array items we just considered so we can difference it next time
1.3336 + ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
1.3337 + }
1.3338 +})();
1.3339 +
1.3340 +ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
1.3341 +ko.nativeTemplateEngine = function () {
1.3342 + this['allowTemplateRewriting'] = false;
1.3343 +}
1.3344 +
1.3345 +ko.nativeTemplateEngine.prototype = new ko.templateEngine();
1.3346 +ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
1.3347 + var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
1.3348 + templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
1.3349 + templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
1.3350 +
1.3351 + if (templateNodes) {
1.3352 + return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
1.3353 + } else {
1.3354 + var templateText = templateSource['text']();
1.3355 + return ko.utils.parseHtmlFragment(templateText);
1.3356 + }
1.3357 +};
1.3358 +
1.3359 +ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
1.3360 +ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
1.3361 +
1.3362 +ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
1.3363 +(function() {
1.3364 + ko.jqueryTmplTemplateEngine = function () {
1.3365 + // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
1.3366 + // doesn't expose a version number, so we have to infer it.
1.3367 + // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
1.3368 + // which KO internally refers to as version "2", so older versions are no longer detected.
1.3369 + var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
1.3370 + if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
1.3371 + return 0;
1.3372 + // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
1.3373 + try {
1.3374 + if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
1.3375 + // Since 1.0.0pre, custom tags should append markup to an array called "__"
1.3376 + return 2; // Final version of jquery.tmpl
1.3377 + }
1.3378 + } catch(ex) { /* Apparently not the version we were looking for */ }
1.3379 +
1.3380 + return 1; // Any older version that we don't support
1.3381 + })();
1.3382 +
1.3383 + function ensureHasReferencedJQueryTemplates() {
1.3384 + if (jQueryTmplVersion < 2)
1.3385 + throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
1.3386 + }
1.3387 +
1.3388 + function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
1.3389 + return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
1.3390 + }
1.3391 +
1.3392 + this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
1.3393 + options = options || {};
1.3394 + ensureHasReferencedJQueryTemplates();
1.3395 +
1.3396 + // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
1.3397 + var precompiled = templateSource['data']('precompiled');
1.3398 + if (!precompiled) {
1.3399 + var templateText = templateSource['text']() || "";
1.3400 + // Wrap in "with($whatever.koBindingContext) { ... }"
1.3401 + templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
1.3402 +
1.3403 + precompiled = jQuery['template'](null, templateText);
1.3404 + templateSource['data']('precompiled', precompiled);
1.3405 + }
1.3406 +
1.3407 + var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
1.3408 + var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
1.3409 +
1.3410 + var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
1.3411 + resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
1.3412 +
1.3413 + jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
1.3414 + return resultNodes;
1.3415 + };
1.3416 +
1.3417 + this['createJavaScriptEvaluatorBlock'] = function(script) {
1.3418 + return "{{ko_code ((function() { return " + script + " })()) }}";
1.3419 + };
1.3420 +
1.3421 + this['addTemplate'] = function(templateName, templateMarkup) {
1.3422 + document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
1.3423 + };
1.3424 +
1.3425 + if (jQueryTmplVersion > 0) {
1.3426 + jQuery['tmpl']['tag']['ko_code'] = {
1.3427 + open: "__.push($1 || '');"
1.3428 + };
1.3429 + jQuery['tmpl']['tag']['ko_with'] = {
1.3430 + open: "with($1) {",
1.3431 + close: "} "
1.3432 + };
1.3433 + }
1.3434 + };
1.3435 +
1.3436 + ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
1.3437 +
1.3438 + // Use this one by default *only if jquery.tmpl is referenced*
1.3439 + var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
1.3440 + if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
1.3441 + ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
1.3442 +
1.3443 + ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
1.3444 +})();
1.3445 +});
1.3446 +})(window,document,navigator);