vendor: 389,290 bytes, lines 1-6614
1/*! 2 * Knockout JavaScript library v3.5.1 3 * (c) The Knockout.js team - http://knockoutjs.com/ 4 * License: MIT (http://www.opensource.org/licenses/mit-license.php) 5 */ 6 7(function () { 8 var DEBUG = true; 9 (function (undefined) { 10 // (0, eval)('this') is a robust way of getting a reference to the global object 11 // For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023 12 var window = this || (0, eval)('this'), 13 document = window['document'], 14 navigator = window['navigator'], 15 jQueryInstance = window["jQuery"], 16 JSON = window["JSON"]; 17 18 if (!jQueryInstance && typeof jQuery !== "undefined") { 19 jQueryInstance = jQuery; 20 } 21 (function (factory) { 22 // Support three module loading scenarios 23 if (typeof define === 'function' && define['amd']) { 24 // [1] AMD anonymous module 25 define(['exports', 'require'], factory); 26 } else if (typeof exports === 'object' && typeof module === 'object') { 27 // [2] CommonJS/Node.js 28 factory(module['exports'] || exports); // module.exports is for Node.js 29 } else { 30 // [3] No module loader (plain <script> tag) - put directly in global namespace 31 factory(window['ko'] = {}); 32 } 33 }(function (koExports, amdRequire) { 34 // Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler). 35 // In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable. 36 var ko = typeof koExports !== 'undefined' ? koExports : {}; 37 // Google Closure Compiler helpers (used only to make the minified file smaller) 38 ko.exportSymbol = function (koPath, object) { 39 var tokens = koPath.split("."); 40 41 // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable) 42 // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko) 43 var target = ko; 44 45 for (var i = 0; i < tokens.length - 1; i++) 46 target = target[tokens[i]]; 47 target[tokens[tokens.length - 1]] = object; 48 }; 49 ko.exportProperty = function (owner, publicName, object) { 50 owner[publicName] = object; 51 }; 52 ko.version = "3.5.1"; 53 54 ko.exportSymbol('version', ko.version); 55 // For any options that may affect various areas of Knockout and aren't directly associated with data binding. 56 ko.options = { 57 'deferUpdates': false, 58 'useOnlyNativeEvents': false, 59 'foreachHidesDestroyed': false 60 }; 61 62 //ko.exportSymbol('options', ko.options); // 'options' isn't minified 63 ko.utils = (function () { 64 var hasOwnProperty = Object.prototype.hasOwnProperty; 65 66 function objectForEach(obj, action) { 67 for (var prop in obj) { 68 if (hasOwnProperty.call(obj, prop)) { 69 action(prop, obj[prop]); 70 } 71 } 72 } 73 74 function extend(target, source) { 75 if (source) { 76 for (var prop in source) { 77 if (hasOwnProperty.call(source, prop)) { 78 target[prop] = source[prop]; 79 } 80 } 81 } 82 return target; 83 } 84 85 function setPrototypeOf(obj, proto) { 86 obj.__proto__ = proto; 87 return obj; 88 } 89 90 var canSetPrototype = ({ __proto__: [] } instanceof Array); 91 var canUseSymbols = !DEBUG && typeof Symbol === 'function'; 92 93 // 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) 94 var knownEvents = {}, knownEventTypesByEventName = {}; 95 var keyEventTypeName = (navigator && /Firefox\/2/i.test(navigator.userAgent)) ? 'KeyboardEvent' : 'UIEvents'; 96 knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress']; 97 knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave']; 98 objectForEach(knownEvents, function (eventType, knownEventsForType) { 99 if (knownEventsForType.length) { 100 for (var i = 0, j = knownEventsForType.length; i < j; i++) 101 knownEventTypesByEventName[knownEventsForType[i]] = eventType; 102 } 103 }); 104 var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406 105 106 // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness) 107 // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10. 108 // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser. 109 // If there is a future need to detect specific versions of IE10+, we will amend this. 110 var ieVersion = document && (function () { 111 var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i'); 112 113 // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment 114 while ( 115 div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->', 116 iElems[0] 117 ) { } 118 return version > 4 ? version : undefined; 119 }()); 120 var isIe6 = ieVersion === 6, 121 isIe7 = ieVersion === 7; 122 123 function isClickOnCheckableElement(element, eventType) { 124 if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false; 125 if (eventType.toLowerCase() != "click") return false; 126 var inputType = element.type; 127 return (inputType == "checkbox") || (inputType == "radio"); 128 } 129 130 // For details on the pattern for changing node classes 131 // see: https://github.com/knockout/knockout/issues/1597 132 var cssClassNameRegex = /\S+/g; 133 134 var jQueryEventAttachName; 135 136 function toggleDomNodeCssClass(node, classNames, shouldHaveClass) { 137 var addOrRemoveFn; 138 if (classNames) { 139 if (typeof node.classList === 'object') { 140 addOrRemoveFn = node.classList[shouldHaveClass ? 'add' : 'remove']; 141 ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function (className) { 142 addOrRemoveFn.call(node.classList, className); 143 }); 144 } else if (typeof node.className['baseVal'] === 'string') { 145 // SVG tag .classNames is an SVGAnimatedString instance 146 toggleObjectClassPropertyString(node.className, 'baseVal', classNames, shouldHaveClass); 147 } else { 148 // node.className ought to be a string. 149 toggleObjectClassPropertyString(node, 'className', classNames, shouldHaveClass); 150 } 151 } 152 } 153 154 function toggleObjectClassPropertyString(obj, prop, classNames, shouldHaveClass) { 155 // obj/prop is either a node/'className' or a SVGAnimatedString/'baseVal'. 156 var currentClassNames = obj[prop].match(cssClassNameRegex) || []; 157 ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function (className) { 158 ko.utils.addOrRemoveItem(currentClassNames, className, shouldHaveClass); 159 }); 160 obj[prop] = currentClassNames.join(" "); 161 } 162 163 return { 164 fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/], 165 166 arrayForEach: function (array, action, actionOwner) { 167 for (var i = 0, j = array.length; i < j; i++) { 168 action.call(actionOwner, array[i], i, array); 169 } 170 }, 171 172 arrayIndexOf: typeof Array.prototype.indexOf == "function" 173 ? function (array, item) { 174 return Array.prototype.indexOf.call(array, item); 175 } 176 : function (array, item) { 177 for (var i = 0, j = array.length; i < j; i++) { 178 if (array[i] === item) 179 return i; 180 } 181 return -1; 182 }, 183 184 arrayFirst: function (array, predicate, predicateOwner) { 185 for (var i = 0, j = array.length; i < j; i++) { 186 if (predicate.call(predicateOwner, array[i], i, array)) 187 return array[i]; 188 } 189 return undefined; 190 }, 191 192 arrayRemoveItem: function (array, itemToRemove) { 193 var index = ko.utils.arrayIndexOf(array, itemToRemove); 194 if (index > 0) { 195 array.splice(index, 1); 196 } 197 else if (index === 0) { 198 array.shift(); 199 } 200 }, 201 202 arrayGetDistinctValues: function (array) { 203 var result = []; 204 if (array) { 205 ko.utils.arrayForEach(array, function (item) { 206 if (ko.utils.arrayIndexOf(result, item) < 0) 207 result.push(item); 208 }); 209 } 210 return result; 211 }, 212 213 arrayMap: function (array, mapping, mappingOwner) { 214 var result = []; 215 if (array) { 216 for (var i = 0, j = array.length; i < j; i++) 217 result.push(mapping.call(mappingOwner, array[i], i)); 218 } 219 return result; 220 }, 221 222 arrayFilter: function (array, predicate, predicateOwner) { 223 var result = []; 224 if (array) { 225 for (var i = 0, j = array.length; i < j; i++) 226 if (predicate.call(predicateOwner, array[i], i)) 227 result.push(array[i]); 228 } 229 return result; 230 }, 231 232 arrayPushAll: function (array, valuesToPush) { 233 if (valuesToPush instanceof Array) 234 array.push.apply(array, valuesToPush); 235 else 236 for (var i = 0, j = valuesToPush.length; i < j; i++) 237 array.push(valuesToPush[i]); 238 return array; 239 }, 240 241 addOrRemoveItem: function (array, value, included) { 242 var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.peekObservable(array), value); 243 if (existingEntryIndex < 0) { 244 if (included) 245 array.push(value); 246 } else { 247 if (!included) 248 array.splice(existingEntryIndex, 1); 249 } 250 }, 251 252 canSetPrototype: canSetPrototype, 253 254 extend: extend, 255 256 setPrototypeOf: setPrototypeOf, 257 258 setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : extend, 259 260 objectForEach: objectForEach, 261 262 objectMap: function (source, mapping, mappingOwner) { 263 if (!source) 264 return source; 265 var target = {}; 266 for (var prop in source) { 267 if (hasOwnProperty.call(source, prop)) { 268 target[prop] = mapping.call(mappingOwner, source[prop], prop, source); 269 } 270 } 271 return target; 272 }, 273 274 emptyDomNode: function (domNode) { 275 while (domNode.firstChild) { 276 ko.removeNode(domNode.firstChild); 277 } 278 }, 279 280 moveCleanedNodesToContainerElement: function (nodes) { 281 // Ensure it's a real array, as we're about to reparent the nodes and 282 // we don't want the underlying collection to change while we're doing that. 283 var nodesArray = ko.utils.makeArray(nodes); 284 var templateDocument = (nodesArray[0] && nodesArray[0].ownerDocument) || document; 285 286 var container = templateDocument.createElement('div'); 287 for (var i = 0, j = nodesArray.length; i < j; i++) { 288 container.appendChild(ko.cleanNode(nodesArray[i])); 289 } 290 return container; 291 }, 292 293 cloneNodes: function (nodesArray, shouldCleanNodes) { 294 for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) { 295 var clonedNode = nodesArray[i].cloneNode(true); 296 newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode); 297 } 298 return newNodesArray; 299 }, 300 301 setDomNodeChildren: function (domNode, childNodes) { 302 ko.utils.emptyDomNode(domNode); 303 if (childNodes) { 304 for (var i = 0, j = childNodes.length; i < j; i++) 305 domNode.appendChild(childNodes[i]); 306 } 307 }, 308 309 replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) { 310 var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray; 311 if (nodesToReplaceArray.length > 0) { 312 var insertionPoint = nodesToReplaceArray[0]; 313 var parent = insertionPoint.parentNode; 314 for (var i = 0, j = newNodesArray.length; i < j; i++) 315 parent.insertBefore(newNodesArray[i], insertionPoint); 316 for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) { 317 ko.removeNode(nodesToReplaceArray[i]); 318 } 319 } 320 }, 321 322 fixUpContinuousNodeArray: function (continuousNodeArray, parentNode) { 323 // Before acting on a set of nodes that were previously outputted by a template function, we have to reconcile 324 // them against what is in the DOM right now. It may be that some of the nodes have already been removed, or that 325 // new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been 326 // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding. 327 // So, this function translates the old "map" output array into its best guess of the set of current DOM nodes. 328 // 329 // Rules: 330 // [A] Any leading nodes that have been removed should be ignored 331 // These most likely correspond to memoization nodes that were already removed during binding 332 // See https://github.com/knockout/knockout/pull/440 333 // [B] Any trailing nodes that have been remove should be ignored 334 // This prevents the code here from adding unrelated nodes to the array while processing rule [C] 335 // See https://github.com/knockout/knockout/pull/1903 336 // [C] We want to output a continuous series of nodes. So, ignore any nodes that have already been removed, 337 // and include any nodes that have been inserted among the previous collection 338 339 if (continuousNodeArray.length) { 340 // The parent node can be a virtual element; so get the real parent node 341 parentNode = (parentNode.nodeType === 8 && parentNode.parentNode) || parentNode; 342 343 // Rule [A] 344 while (continuousNodeArray.length && continuousNodeArray[0].parentNode !== parentNode) 345 continuousNodeArray.splice(0, 1); 346 347 // Rule [B] 348 while (continuousNodeArray.length > 1 && continuousNodeArray[continuousNodeArray.length - 1].parentNode !== parentNode) 349 continuousNodeArray.length--; 350 351 // Rule [C] 352 if (continuousNodeArray.length > 1) { 353 var current = continuousNodeArray[0], last = continuousNodeArray[continuousNodeArray.length - 1]; 354 // Replace with the actual new continuous node set 355 continuousNodeArray.length = 0; 356 while (current !== last) { 357 continuousNodeArray.push(current); 358 current = current.nextSibling; 359 } 360 continuousNodeArray.push(last); 361 } 362 } 363 return continuousNodeArray; 364 }, 365 366 setOptionNodeSelectionState: function (optionNode, isSelected) { 367 // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser. 368 if (ieVersion < 7) 369 optionNode.setAttribute("selected", isSelected); 370 else 371 optionNode.selected = isSelected; 372 }, 373 374 stringTrim: function (string) { 375 return string === null || string === undefined ? '' : 376 string.trim ? 377 string.trim() : 378 string.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, ''); 379 }, 380 381 stringStartsWith: function (string, startsWith) { 382 string = string || ""; 383 if (startsWith.length > string.length) 384 return false; 385 return string.substring(0, startsWith.length) === startsWith; 386 }, 387 388 domNodeIsContainedBy: function (node, containedByNode) { 389 if (node === containedByNode) 390 return true; 391 if (node.nodeType === 11) 392 return false; // Fixes issue #1162 - can't use node.contains for document fragments on IE8 393 if (containedByNode.contains) 394 return containedByNode.contains(node.nodeType !== 1 ? node.parentNode : node); 395 if (containedByNode.compareDocumentPosition) 396 return (containedByNode.compareDocumentPosition(node) & 16) == 16; 397 while (node && node != containedByNode) { 398 node = node.parentNode; 399 } 400 return !!node; 401 }, 402 403 domNodeIsAttachedToDocument: function (node) { 404 return ko.utils.domNodeIsContainedBy(node, node.ownerDocument.documentElement); 405 }, 406 407 anyDomNodeIsAttachedToDocument: function (nodes) { 408 return !!ko.utils.arrayFirst(nodes, ko.utils.domNodeIsAttachedToDocument); 409 }, 410 411 tagNameLower: function (element) { 412 // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case. 413 // Possible future optimization: If we know it's an element from an XHTML document (not HTML), 414 // we don't need to do the .toLowerCase() as it will always be lower case anyway. 415 return element && element.tagName && element.tagName.toLowerCase(); 416 }, 417 418 catchFunctionErrors: function (delegate) { 419 return ko['onError'] ? function () { 420 try { 421 return delegate.apply(this, arguments); 422 } catch (e) { 423 ko['onError'] && ko['onError'](e); 424 throw e; 425 } 426 } : delegate; 427 }, 428 429 setTimeout: function (handler, timeout) { 430 return setTimeout(ko.utils.catchFunctionErrors(handler), timeout); 431 }, 432 433 deferError: function (error) { 434 setTimeout(function () { 435 ko['onError'] && ko['onError'](error); 436 throw error; 437 }, 0); 438 }, 439 440 registerEventHandler: function (element, eventType, handler) { 441 var wrappedHandler = ko.utils.catchFunctionErrors(handler); 442 443 var mustUseAttachEvent = eventsThatMustBeRegisteredUsingAttachEvent[eventType]; 444 if (!ko.options['useOnlyNativeEvents'] && !mustUseAttachEvent && jQueryInstance) { 445 if (!jQueryEventAttachName) { 446 jQueryEventAttachName = (typeof jQueryInstance(element)['on'] == 'function') ? 'on' : 'bind'; 447 } 448 jQueryInstance(element)[jQueryEventAttachName](eventType, wrappedHandler); 449 } else if (!mustUseAttachEvent && typeof element.addEventListener == "function") 450 element.addEventListener(eventType, wrappedHandler, false); 451 else if (typeof element.attachEvent != "undefined") { 452 var attachEventHandler = function (event) { wrappedHandler.call(element, event); }, 453 attachEventName = "on" + eventType; 454 element.attachEvent(attachEventName, attachEventHandler); 455 456 // IE does not dispose attachEvent handlers automatically (unlike with addEventListener) 457 // so to avoid leaks, we have to remove them manually. See bug #856 458 ko.utils.domNodeDisposal.addDisposeCallback(element, function () { 459 element.detachEvent(attachEventName, attachEventHandler); 460 }); 461 } else 462 throw new Error("Browser doesn't support addEventListener or attachEvent"); 463 }, 464 465 triggerEvent: function (element, eventType) { 466 if (!(element && element.nodeType)) 467 throw new Error("element must be a DOM node when calling triggerEvent"); 468 469 // For click events on checkboxes and radio buttons, jQuery toggles the element checked state *after* the 470 // event handler runs instead of *before*. (This was fixed in 1.9 for checkboxes but not for radio buttons.) 471 // IE doesn't change the checked state when you trigger the click event using "fireEvent". 472 // In both cases, we'll use the click method instead. 473 var useClickWorkaround = isClickOnCheckableElement(element, eventType); 474 475 if (!ko.options['useOnlyNativeEvents'] && jQueryInstance && !useClickWorkaround) { 476 jQueryInstance(element)['trigger'](eventType); 477 } else if (typeof document.createEvent == "function") { 478 if (typeof element.dispatchEvent == "function") { 479 var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents"; 480 var event = document.createEvent(eventCategory); 481 event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element); 482 element.dispatchEvent(event); 483 } 484 else 485 throw new Error("The supplied element doesn't support dispatchEvent"); 486 } else if (useClickWorkaround && element.click) { 487 element.click(); 488 } else if (typeof element.fireEvent != "undefined") { 489 element.fireEvent("on" + eventType); 490 } else { 491 throw new Error("Browser doesn't support triggering events"); 492 } 493 }, 494 495 unwrapObservable: function (value) { 496 return ko.isObservable(value) ? value() : value; 497 }, 498 499 peekObservable: function (value) { 500 return ko.isObservable(value) ? value.peek() : value; 501 }, 502 503 toggleDomNodeCssClass: toggleDomNodeCssClass, 504 505 setTextContent: function (element, textContent) { 506 var value = ko.utils.unwrapObservable(textContent); 507 if ((value === null) || (value === undefined)) 508 value = ""; 509 510 // We need there to be exactly one child: a text node. 511 // If there are no children, more than one, or if it's not a text node, 512 // we'll clear everything and create a single text node. 513 var innerTextNode = ko.virtualElements.firstChild(element); 514 if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) { 515 ko.virtualElements.setDomNodeChildren(element, [element.ownerDocument.createTextNode(value)]); 516 } else { 517 innerTextNode.data = value; 518 } 519 520 ko.utils.forceRefresh(element); 521 }, 522 523 setElementName: function (element, name) { 524 element.name = name; 525 526 // Workaround IE 6/7 issue 527 // - https://github.com/SteveSanderson/knockout/issues/197 528 // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/ 529 if (ieVersion <= 7) { 530 try { 531 var escapedName = element.name.replace(/[&<>'"]/g, function (r) { return "&#" + r.charCodeAt(0) + ";"; }); 532 element.mergeAttributes(document.createElement("<input name='" + escapedName + "'/>"), false); 533 } 534 catch (e) { } // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View" 535 } 536 }, 537 538 forceRefresh: function (node) { 539 // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209 540 if (ieVersion >= 9) { 541 // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container 542 var elem = node.nodeType == 1 ? node : node.parentNode; 543 if (elem.style) 544 elem.style.zoom = elem.style.zoom; 545 } 546 }, 547 548 ensureSelectElementIsRenderedCorrectly: function (selectElement) { 549 // 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. 550 // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option) 551 // Also fixes IE7 and IE8 bug that causes selects to be zero width if enclosed by 'if' or 'with'. (See issue #839) 552 if (ieVersion) { 553 var originalWidth = selectElement.style.width; 554 selectElement.style.width = 0; 555 selectElement.style.width = originalWidth; 556 } 557 }, 558 559 range: function (min, max) { 560 min = ko.utils.unwrapObservable(min); 561 max = ko.utils.unwrapObservable(max); 562 var result = []; 563 for (var i = min; i <= max; i++) 564 result.push(i); 565 return result; 566 }, 567 568 makeArray: function (arrayLikeObject) { 569 var result = []; 570 for (var i = 0, j = arrayLikeObject.length; i < j; i++) { 571 result.push(arrayLikeObject[i]); 572 }; 573 return result; 574 }, 575 576 createSymbolOrString: function (identifier) { 577 return canUseSymbols ? Symbol(identifier) : identifier; 578 }, 579 580 isIe6: isIe6, 581 isIe7: isIe7, 582 ieVersion: ieVersion, 583 584 getFormFields: function (form, fieldName) { 585 var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea"))); 586 var isMatchingField = (typeof fieldName == 'string') 587 ? function (field) { return field.name === fieldName } 588 : function (field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate 589 var matches = []; 590 for (var i = fields.length - 1; i >= 0; i--) { 591 if (isMatchingField(fields[i])) 592 matches.push(fields[i]); 593 }; 594 return matches; 595 }, 596 597 parseJson: function (jsonString) { 598 if (typeof jsonString == "string") { 599 jsonString = ko.utils.stringTrim(jsonString); 600 if (jsonString) { 601 if (JSON && JSON.parse) // Use native parsing where available 602 return JSON.parse(jsonString); 603 return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers 604 } 605 } 606 return null; 607 }, 608 609 stringifyJson: function (data, replacer, space) { // replacer and space are optional 610 if (!JSON || !JSON.stringify) 611 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"); 612 return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space); 613 }, 614 615 postJson: function (urlOrForm, data, options) { 616 options = options || {}; 617 var params = options['params'] || {}; 618 var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost; 619 var url = urlOrForm; 620 621 // If we were given a form, use its 'action' URL and pick out any requested field values 622 if ((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) { 623 var originalForm = urlOrForm; 624 url = originalForm.action; 625 for (var i = includeFields.length - 1; i >= 0; i--) { 626 var fields = ko.utils.getFormFields(originalForm, includeFields[i]); 627 for (var j = fields.length - 1; j >= 0; j--) 628 params[fields[j].name] = fields[j].value; 629 } 630 } 631 632 data = ko.utils.unwrapObservable(data); 633 var form = document.createElement("form"); 634 form.style.display = "none"; 635 form.action = url; 636 form.method = "post"; 637 for (var key in data) { 638 // Since 'data' this is a model object, we include all properties including those inherited from its prototype 639 var input = document.createElement("input"); 640 input.type = "hidden"; 641 input.name = key; 642 input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key])); 643 form.appendChild(input); 644 } 645 objectForEach(params, function (key, value) { 646 var input = document.createElement("input"); 647 input.type = "hidden"; 648 input.name = key; 649 input.value = value; 650 form.appendChild(input); 651 }); 652 document.body.appendChild(form); 653 options['submitter'] ? options['submitter'](form) : form.submit(); 654 setTimeout(function () { form.parentNode.removeChild(form); }, 0); 655 } 656 } 657 }()); 658 659 ko.exportSymbol('utils', ko.utils); 660 ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach); 661 ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst); 662 ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter); 663 ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues); 664 ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf); 665 ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap); 666 ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll); 667 ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem); 668 ko.exportSymbol('utils.cloneNodes', ko.utils.cloneNodes); 669 ko.exportSymbol('utils.createSymbolOrString', ko.utils.createSymbolOrString); 670 ko.exportSymbol('utils.extend', ko.utils.extend); 671 ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost); 672 ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields); 673 ko.exportSymbol('utils.objectMap', ko.utils.objectMap); 674 ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable); 675 ko.exportSymbol('utils.postJson', ko.utils.postJson); 676 ko.exportSymbol('utils.parseJson', ko.utils.parseJson); 677 ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler); 678 ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson); 679 ko.exportSymbol('utils.range', ko.utils.range); 680 ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass); 681 ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent); 682 ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable); 683 ko.exportSymbol('utils.objectForEach', ko.utils.objectForEach); 684 ko.exportSymbol('utils.addOrRemoveItem', ko.utils.addOrRemoveItem); 685 ko.exportSymbol('utils.setTextContent', ko.utils.setTextContent); 686 ko.exportSymbol('unwrap', ko.utils.unwrapObservable); // Convenient shorthand, because this is used so commonly 687 688 if (!Function.prototype['bind']) { 689 // 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) 690 // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js 691 Function.prototype['bind'] = function (object) { 692 var originalFunction = this; 693 if (arguments.length === 1) { 694 return function () { 695 return originalFunction.apply(object, arguments); 696 }; 697 } else { 698 var partialArgs = Array.prototype.slice.call(arguments, 1); 699 return function () { 700 var args = partialArgs.slice(0); 701 args.push.apply(args, arguments); 702 return originalFunction.apply(object, args); 703 }; 704 } 705 }; 706 } 707 708 ko.utils.domData = new (function () { 709 var uniqueId = 0; 710 var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime(); 711 var dataStore = {}; 712 713 var getDataForNode, clear; 714 if (!ko.utils.ieVersion) { 715 // We considered using WeakMap, but it has a problem in IE 11 and Edge that prevents using 716 // it cross-window, so instead we just store the data directly on the node. 717 // See https://github.com/knockout/knockout/issues/2141 718 getDataForNode = function (node, createIfNotFound) { 719 var dataForNode = node[dataStoreKeyExpandoPropertyName]; 720 if (!dataForNode && createIfNotFound) { 721 dataForNode = node[dataStoreKeyExpandoPropertyName] = {}; 722 } 723 return dataForNode; 724 }; 725 clear = function (node) { 726 if (node[dataStoreKeyExpandoPropertyName]) { 727 delete node[dataStoreKeyExpandoPropertyName]; 728 return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended 729 } 730 return false; 731 }; 732 } else { 733 // Old IE versions have memory issues if you store objects on the node, so we use a 734 // separate data storage and link to it from the node using a string key. 735 getDataForNode = function (node, createIfNotFound) { 736 var dataStoreKey = node[dataStoreKeyExpandoPropertyName]; 737 var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey]; 738 if (!hasExistingDataStore) { 739 if (!createIfNotFound) 740 return undefined; 741 dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++; 742 dataStore[dataStoreKey] = {}; 743 } 744 return dataStore[dataStoreKey]; 745 }; 746 clear = function (node) { 747 var dataStoreKey = node[dataStoreKeyExpandoPropertyName]; 748 if (dataStoreKey) { 749 delete dataStore[dataStoreKey]; 750 node[dataStoreKeyExpandoPropertyName] = null; 751 return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended 752 } 753 return false; 754 }; 755 } 756 757 return { 758 get: function (node, key) { 759 var dataForNode = getDataForNode(node, false); 760 return dataForNode && dataForNode[key]; 761 }, 762 set: function (node, key, value) { 763 // Make sure we don't actually create a new domData key if we are actually deleting a value 764 var dataForNode = getDataForNode(node, value !== undefined /* createIfNotFound */); 765 dataForNode && (dataForNode[key] = value); 766 }, 767 getOrSet: function (node, key, value) { 768 var dataForNode = getDataForNode(node, true /* createIfNotFound */); 769 return dataForNode[key] || (dataForNode[key] = value); 770 }, 771 clear: clear, 772 773 nextKey: function () { 774 return (uniqueId++) + dataStoreKeyExpandoPropertyName; 775 } 776 }; 777 })(); 778 779 ko.exportSymbol('utils.domData', ko.utils.domData); 780 ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully 781 782 ko.utils.domNodeDisposal = new (function () { 783 var domDataKey = ko.utils.domData.nextKey(); 784 var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document 785 var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document 786 787 function getDisposeCallbacksCollection(node, createIfNotFound) { 788 var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey); 789 if ((allDisposeCallbacks === undefined) && createIfNotFound) { 790 allDisposeCallbacks = []; 791 ko.utils.domData.set(node, domDataKey, allDisposeCallbacks); 792 } 793 return allDisposeCallbacks; 794 } 795 function destroyCallbacksCollection(node) { 796 ko.utils.domData.set(node, domDataKey, undefined); 797 } 798 799 function cleanSingleNode(node) { 800 // Run all the dispose callbacks 801 var callbacks = getDisposeCallbacksCollection(node, false); 802 if (callbacks) { 803 callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves) 804 for (var i = 0; i < callbacks.length; i++) 805 callbacks[i](node); 806 } 807 808 // Erase the DOM data 809 ko.utils.domData.clear(node); 810 811 // Perform cleanup needed by external libraries (currently only jQuery, but can be extended) 812 ko.utils.domNodeDisposal["cleanExternalData"](node); 813 814 // Clear any immediate-child comment nodes, as these wouldn't have been found by 815 // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements) 816 if (cleanableNodeTypesWithDescendants[node.nodeType]) { 817 cleanNodesInList(node.childNodes, true/*onlyComments*/); 818 } 819 } 820 821 function cleanNodesInList(nodeList, onlyComments) { 822 var cleanedNodes = [], lastCleanedNode; 823 for (var i = 0; i < nodeList.length; i++) { 824 if (!onlyComments || nodeList[i].nodeType === 8) { 825 cleanSingleNode(cleanedNodes[cleanedNodes.length] = lastCleanedNode = nodeList[i]); 826 if (nodeList[i] !== lastCleanedNode) { 827 while (i-- && ko.utils.arrayIndexOf(cleanedNodes, nodeList[i]) == -1) { } 828 } 829 } 830 } 831 } 832 833 return { 834 addDisposeCallback: function (node, callback) { 835 if (typeof callback != "function") 836 throw new Error("Callback must be a function"); 837 getDisposeCallbacksCollection(node, true).push(callback); 838 }, 839 840 removeDisposeCallback: function (node, callback) { 841 var callbacksCollection = getDisposeCallbacksCollection(node, false); 842 if (callbacksCollection) { 843 ko.utils.arrayRemoveItem(callbacksCollection, callback); 844 if (callbacksCollection.length == 0) 845 destroyCallbacksCollection(node); 846 } 847 }, 848 849 cleanNode: function (node) { 850 ko.dependencyDetection.ignore(function () { 851 // First clean this node, where applicable 852 if (cleanableNodeTypes[node.nodeType]) { 853 cleanSingleNode(node); 854 855 // ... then its descendants, where applicable 856 if (cleanableNodeTypesWithDescendants[node.nodeType]) { 857 cleanNodesInList(node.getElementsByTagName("*")); 858 } 859 } 860 }); 861 862 return node; 863 }, 864 865 removeNode: function (node) { 866 ko.cleanNode(node); 867 if (node.parentNode) 868 node.parentNode.removeChild(node); 869 }, 870 871 "cleanExternalData": function (node) { 872 // Special support for jQuery here because it's so commonly used. 873 // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData 874 // so notify it to tear down any resources associated with the node & descendants here. 875 if (jQueryInstance && (typeof jQueryInstance['cleanData'] == "function")) 876 jQueryInstance['cleanData']([node]); 877 } 878 }; 879 })(); 880 ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience 881 ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience 882 ko.exportSymbol('cleanNode', ko.cleanNode); 883 ko.exportSymbol('removeNode', ko.removeNode); 884 ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal); 885 ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback); 886 ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback); 887 (function () { 888 var none = [0, "", ""], 889 table = [1, "<table>", "</table>"], 890 tbody = [2, "<table><tbody>", "</tbody></table>"], 891 tr = [3, "<table><tbody><tr>", "</tr></tbody></table>"], 892 select = [1, "<select multiple='multiple'>", "</select>"], 893 lookup = { 894 'thead': table, 895 'tbody': table, 896 'tfoot': table, 897 'tr': tbody, 898 'td': tr, 899 'th': tr, 900 'option': select, 901 'optgroup': select 902 }, 903 904 // This is needed for old IE if you're *not* using either jQuery or innerShiv. Doesn't affect other cases. 905 mayRequireCreateElementHack = ko.utils.ieVersion <= 8; 906 907 function getWrap(tags) { 908 var m = tags.match(/^(?:<!--.*?-->\s*?)*?<([a-z]+)[\s>]/); 909 return (m && lookup[m[1]]) || none; 910 } 911 912 function simpleHtmlParse(html, documentContext) { 913 documentContext || (documentContext = document); 914 var windowContext = documentContext['parentWindow'] || documentContext['defaultView'] || window; 915 916 // Based on jQuery's "clean" function, but only accounting for table-related elements. 917 // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly 918 919 // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of 920 // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>" 921 // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node 922 // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present. 923 924 // Trim whitespace, otherwise indexOf won't work as expected 925 var tags = ko.utils.stringTrim(html).toLowerCase(), div = documentContext.createElement("div"), 926 wrap = getWrap(tags), 927 depth = wrap[0]; 928 929 // Go to html and back, then peel off extra wrappers 930 // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness. 931 var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>"; 932 if (typeof windowContext['innerShiv'] == "function") { 933 // Note that innerShiv is deprecated in favour of html5shiv. We should consider adding 934 // support for html5shiv (except if no explicit support is needed, e.g., if html5shiv 935 // somehow shims the native APIs so it just works anyway) 936 div.appendChild(windowContext['innerShiv'](markup)); 937 } else { 938 if (mayRequireCreateElementHack) { 939 // The document.createElement('my-element') trick to enable custom elements in IE6-8 940 // only works if we assign innerHTML on an element associated with that document. 941 documentContext.body.appendChild(div); 942 } 943 944 div.innerHTML = markup; 945 946 if (mayRequireCreateElementHack) { 947 div.parentNode.removeChild(div); 948 } 949 } 950 951 // Move to the right depth 952 while (depth--) 953 div = div.lastChild; 954 955 return ko.utils.makeArray(div.lastChild.childNodes); 956 } 957 958 function jQueryHtmlParse(html, documentContext) { 959 // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API. 960 if (jQueryInstance['parseHTML']) { 961 return jQueryInstance['parseHTML'](html, documentContext) || []; // Ensure we always return an array and never null 962 } else { 963 // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function. 964 var elems = jQueryInstance['clean']([html], documentContext); 965 966 // 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. 967 // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time. 968 // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment. 969 if (elems && elems[0]) { 970 // Find the top-most parent element that's a direct child of a document fragment 971 var elem = elems[0]; 972 while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */) 973 elem = elem.parentNode; 974 // ... then detach it 975 if (elem.parentNode) 976 elem.parentNode.removeChild(elem); 977 } 978 979 return elems; 980 } 981 } 982 983 ko.utils.parseHtmlFragment = function (html, documentContext) { 984 return jQueryInstance ? 985 jQueryHtmlParse(html, documentContext) : // As below, benefit from jQuery's optimisations where possible 986 simpleHtmlParse(html, documentContext); // ... otherwise, this simple logic will do in most common cases. 987 }; 988 989 ko.utils.parseHtmlForTemplateNodes = function (html, documentContext) { 990 var nodes = ko.utils.parseHtmlFragment(html, documentContext); 991 return (nodes.length && nodes[0].parentElement) || ko.utils.moveCleanedNodesToContainerElement(nodes); 992 }; 993 994 ko.utils.setHtml = function (node, html) { 995 ko.utils.emptyDomNode(node); 996 997 // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it 998 html = ko.utils.unwrapObservable(html); 999 1000 if ((html !== null) && (html !== undefined)) { 1001 if (typeof html != 'string') 1002 html = html.toString(); 1003 1004 // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments, 1005 // for example <tr> elements which are not normally allowed to exist on their own. 1006 // If you've referenced jQuery we'll use that rather than duplicating its code. 1007 if (jQueryInstance) { 1008 jQueryInstance(node)['html'](html); 1009 } else { 1010 // ... otherwise, use KO's own parsing logic. 1011 var parsedNodes = ko.utils.parseHtmlFragment(html, node.ownerDocument); 1012 for (var i = 0; i < parsedNodes.length; i++) 1013 node.appendChild(parsedNodes[i]); 1014 } 1015 } 1016 }; 1017 })(); 1018 1019 ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment); 1020 ko.exportSymbol('utils.setHtml', ko.utils.setHtml); 1021 1022 ko.memoization = (function () { 1023 var memos = {}; 1024 1025 function randomMax8HexChars() { 1026 return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1); 1027 } 1028 function generateRandomId() { 1029 return randomMax8HexChars() + randomMax8HexChars(); 1030 } 1031 function findMemoNodes(rootNode, appendToArray) { 1032 if (!rootNode) 1033 return; 1034 if (rootNode.nodeType == 8) { 1035 var memoId = ko.memoization.parseMemoText(rootNode.nodeValue); 1036 if (memoId != null) 1037 appendToArray.push({ domNode: rootNode, memoId: memoId }); 1038 } else if (rootNode.nodeType == 1) { 1039 for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++) 1040 findMemoNodes(childNodes[i], appendToArray); 1041 } 1042 } 1043 1044 return { 1045 memoize: function (callback) { 1046 if (typeof callback != "function") 1047 throw new Error("You can only pass a function to ko.memoization.memoize()"); 1048 var memoId = generateRandomId(); 1049 memos[memoId] = callback; 1050 return "<!--[ko_memo:" + memoId + "]-->"; 1051 }, 1052 1053 unmemoize: function (memoId, callbackParams) { 1054 var callback = memos[memoId]; 1055 if (callback === undefined) 1056 throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized."); 1057 try { 1058 callback.apply(null, callbackParams || []); 1059 return true; 1060 } 1061 finally { delete memos[memoId]; } 1062 }, 1063 1064 unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) { 1065 var memos = []; 1066 findMemoNodes(domNode, memos); 1067 for (var i = 0, j = memos.length; i < j; i++) { 1068 var node = memos[i].domNode; 1069 var combinedParams = [node]; 1070 if (extraCallbackParamsArray) 1071 ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray); 1072 ko.memoization.unmemoize(memos[i].memoId, combinedParams); 1073 node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again 1074 if (node.parentNode) 1075 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) 1076 } 1077 }, 1078 1079 parseMemoText: function (memoText) { 1080 var match = memoText.match(/^\[ko_memo\:(.*?)\]$/); 1081 return match ? match[1] : null; 1082 } 1083 }; 1084 })(); 1085 1086 ko.exportSymbol('memoization', ko.memoization); 1087 ko.exportSymbol('memoization.memoize', ko.memoization.memoize); 1088 ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize); 1089 ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText); 1090 ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants); 1091 ko.tasks = (function () { 1092 var scheduler, 1093 taskQueue = [], 1094 taskQueueLength = 0, 1095 nextHandle = 1, 1096 nextIndexToProcess = 0; 1097 1098 if (window['MutationObserver']) { 1099 // Chrome 27+, Firefox 14+, IE 11+, Opera 15+, Safari 6.1+ 1100 // From https://github.com/petkaantonov/bluebird * Copyright (c) 2014 Petka Antonov * License: MIT 1101 scheduler = (function (callback) { 1102 var div = document.createElement("div"); 1103 new MutationObserver(callback).observe(div, { attributes: true }); 1104 return function () { div.classList.toggle("foo"); }; 1105 })(scheduledProcess); 1106 } else if (document && "onreadystatechange" in document.createElement("script")) { 1107 // IE 6-10 1108 // From https://github.com/YuzuJS/setImmediate * Copyright (c) 2012 Barnesandnoble.com, llc, Donavon West, and Domenic Denicola * License: MIT 1109 scheduler = function (callback) { 1110 var script = document.createElement("script"); 1111 script.onreadystatechange = function () { 1112 script.onreadystatechange = null; 1113 document.documentElement.removeChild(script); 1114 script = null; 1115 callback(); 1116 }; 1117 document.documentElement.appendChild(script); 1118 }; 1119 } else { 1120 scheduler = function (callback) { 1121 setTimeout(callback, 0); 1122 }; 1123 } 1124 1125 function processTasks() { 1126 if (taskQueueLength) { 1127 // Each mark represents the end of a logical group of tasks and the number of these groups is 1128 // limited to prevent unchecked recursion. 1129 var mark = taskQueueLength, countMarks = 0; 1130 1131 // nextIndexToProcess keeps track of where we are in the queue; processTasks can be called recursively without issue 1132 for (var task; nextIndexToProcess < taskQueueLength;) { 1133 if (task = taskQueue[nextIndexToProcess++]) { 1134 if (nextIndexToProcess > mark) { 1135 if (++countMarks >= 5000) { 1136 nextIndexToProcess = taskQueueLength; // skip all tasks remaining in the queue since any of them could be causing the recursion 1137 ko.utils.deferError(Error("'Too much recursion' after processing " + countMarks + " task groups.")); 1138 break; 1139 } 1140 mark = taskQueueLength; 1141 } 1142 try { 1143 task(); 1144 } catch (ex) { 1145 ko.utils.deferError(ex); 1146 } 1147 } 1148 } 1149 } 1150 } 1151 1152 function scheduledProcess() { 1153 processTasks(); 1154 1155 // Reset the queue 1156 nextIndexToProcess = taskQueueLength = taskQueue.length = 0; 1157 } 1158 1159 function scheduleTaskProcessing() { 1160 ko.tasks['scheduler'](scheduledProcess); 1161 } 1162 1163 var tasks = { 1164 'scheduler': scheduler, // Allow overriding the scheduler 1165 1166 schedule: function (func) { 1167 if (!taskQueueLength) { 1168 scheduleTaskProcessing(); 1169 } 1170 1171 taskQueue[taskQueueLength++] = func; 1172 return nextHandle++; 1173 }, 1174 1175 cancel: function (handle) { 1176 var index = handle - (nextHandle - taskQueueLength); 1177 if (index >= nextIndexToProcess && index < taskQueueLength) { 1178 taskQueue[index] = null; 1179 } 1180 }, 1181 1182 // For testing only: reset the queue and return the previous queue length 1183 'resetForTesting': function () { 1184 var length = taskQueueLength - nextIndexToProcess; 1185 nextIndexToProcess = taskQueueLength = taskQueue.length = 0; 1186 return length; 1187 }, 1188 1189 runEarly: processTasks 1190 }; 1191 1192 return tasks; 1193 })(); 1194 1195 ko.exportSymbol('tasks', ko.tasks); 1196 ko.exportSymbol('tasks.schedule', ko.tasks.schedule); 1197 //ko.exportSymbol('tasks.cancel', ko.tasks.cancel); "cancel" isn't minified 1198 ko.exportSymbol('tasks.runEarly', ko.tasks.runEarly); 1199 ko.extenders = { 1200 'throttle': function (target, timeout) { 1201 // Throttling means two things: 1202 1203 // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies 1204 // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate 1205 target['throttleEvaluation'] = timeout; 1206 1207 // (2) For writable targets (observables, or writable dependent observables), we throttle *writes* 1208 // so the target cannot change value synchronously or faster than a certain rate 1209 var writeTimeoutInstance = null; 1210 return ko.dependentObservable({ 1211 'read': target, 1212 'write': function (value) { 1213 clearTimeout(writeTimeoutInstance); 1214 writeTimeoutInstance = ko.utils.setTimeout(function () { 1215 target(value); 1216 }, timeout); 1217 } 1218 }); 1219 }, 1220 1221 'rateLimit': function (target, options) { 1222 var timeout, method, limitFunction; 1223 1224 if (typeof options == 'number') { 1225 timeout = options; 1226 } else { 1227 timeout = options['timeout']; 1228 method = options['method']; 1229 } 1230 1231 // rateLimit supersedes deferred updates 1232 target._deferUpdates = false; 1233 1234 limitFunction = typeof method == 'function' ? method : method == 'notifyWhenChangesStop' ? debounce : throttle; 1235 target.limit(function (callback) { 1236 return limitFunction(callback, timeout, options); 1237 }); 1238 }, 1239 1240 'deferred': function (target, options) { 1241 if (options !== true) { 1242 throw new Error('The \'deferred\' extender only accepts the value \'true\', because it is not supported to turn deferral off once enabled.') 1243 } 1244 1245 if (!target._deferUpdates) { 1246 target._deferUpdates = true; 1247 target.limit(function (callback) { 1248 var handle, 1249 ignoreUpdates = false; 1250 return function () { 1251 if (!ignoreUpdates) { 1252 ko.tasks.cancel(handle); 1253 handle = ko.tasks.schedule(callback); 1254 1255 try { 1256 ignoreUpdates = true; 1257 target['notifySubscribers'](undefined, 'dirty'); 1258 } finally { 1259 ignoreUpdates = false; 1260 } 1261 } 1262 }; 1263 }); 1264 } 1265 }, 1266 1267 'notify': function (target, notifyWhen) { 1268 target["equalityComparer"] = notifyWhen == "always" ? 1269 null : // null equalityComparer means to always notify 1270 valuesArePrimitiveAndEqual; 1271 } 1272 }; 1273 1274 var primitiveTypes = { 'undefined': 1, 'boolean': 1, 'number': 1, 'string': 1 }; 1275 function valuesArePrimitiveAndEqual(a, b) { 1276 var oldValueIsPrimitive = (a === null) || (typeof (a) in primitiveTypes); 1277 return oldValueIsPrimitive ? (a === b) : false; 1278 } 1279 1280 function throttle(callback, timeout) { 1281 var timeoutInstance; 1282 return function () { 1283 if (!timeoutInstance) { 1284 timeoutInstance = ko.utils.setTimeout(function () { 1285 timeoutInstance = undefined; 1286 callback(); 1287 }, timeout); 1288 } 1289 }; 1290 } 1291 1292 function debounce(callback, timeout) { 1293 var timeoutInstance; 1294 return function () { 1295 clearTimeout(timeoutInstance); 1296 timeoutInstance = ko.utils.setTimeout(callback, timeout); 1297 }; 1298 } 1299 1300 function applyExtenders(requestedExtenders) { 1301 var target = this; 1302 if (requestedExtenders) { 1303 ko.utils.objectForEach(requestedExtenders, function (key, value) { 1304 var extenderHandler = ko.extenders[key]; 1305 if (typeof extenderHandler == 'function') { 1306 target = extenderHandler(target, value) || target; 1307 } 1308 }); 1309 } 1310 return target; 1311 } 1312 1313 ko.exportSymbol('extenders', ko.extenders); 1314 1315 ko.subscription = function (target, callback, disposeCallback) { 1316 this._target = target; 1317 this._callback = callback; 1318 this._disposeCallback = disposeCallback; 1319 this._isDisposed = false; 1320 this._node = null; 1321 this._domNodeDisposalCallback = null; 1322 ko.exportProperty(this, 'dispose', this.dispose); 1323 ko.exportProperty(this, 'disposeWhenNodeIsRemoved', this.disposeWhenNodeIsRemoved); 1324 }; 1325 ko.subscription.prototype.dispose = function () { 1326 var self = this; 1327 if (!self._isDisposed) { 1328 if (self._domNodeDisposalCallback) { 1329 ko.utils.domNodeDisposal.removeDisposeCallback(self._node, self._domNodeDisposalCallback); 1330 } 1331 self._isDisposed = true; 1332 self._disposeCallback(); 1333 1334 self._target = self._callback = self._disposeCallback = self._node = self._domNodeDisposalCallback = null; 1335 } 1336 }; 1337 ko.subscription.prototype.disposeWhenNodeIsRemoved = function (node) { 1338 this._node = node; 1339 ko.utils.domNodeDisposal.addDisposeCallback(node, this._domNodeDisposalCallback = this.dispose.bind(this)); 1340 }; 1341 1342 ko.subscribable = function () { 1343 ko.utils.setPrototypeOfOrExtend(this, ko_subscribable_fn); 1344 ko_subscribable_fn.init(this); 1345 } 1346 1347 var defaultEvent = "change"; 1348 1349 // Moved out of "limit" to avoid the extra closure 1350 function limitNotifySubscribers(value, event) { 1351 if (!event || event === defaultEvent) { 1352 this._limitChange(value); 1353 } else if (event === 'beforeChange') { 1354 this._limitBeforeChange(value); 1355 } else { 1356 this._origNotifySubscribers(value, event); 1357 } 1358 } 1359 1360 var ko_subscribable_fn = { 1361 init: function (instance) { 1362 instance._subscriptions = { "change": [] }; 1363 instance._versionNumber = 1; 1364 }, 1365 1366 subscribe: function (callback, callbackTarget, event) { 1367 var self = this; 1368 1369 event = event || defaultEvent; 1370 var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback; 1371 1372 var subscription = new ko.subscription(self, boundCallback, function () { 1373 ko.utils.arrayRemoveItem(self._subscriptions[event], subscription); 1374 if (self.afterSubscriptionRemove) 1375 self.afterSubscriptionRemove(event); 1376 }); 1377 1378 if (self.beforeSubscriptionAdd) 1379 self.beforeSubscriptionAdd(event); 1380 1381 if (!self._subscriptions[event]) 1382 self._subscriptions[event] = []; 1383 self._subscriptions[event].push(subscription); 1384 1385 return subscription; 1386 }, 1387 1388 "notifySubscribers": function (valueToNotify, event) { 1389 event = event || defaultEvent; 1390 if (event === defaultEvent) { 1391 this.updateVersion(); 1392 } 1393 if (this.hasSubscriptionsForEvent(event)) { 1394 var subs = event === defaultEvent && this._changeSubscriptions || this._subscriptions[event].slice(0); 1395 try { 1396 ko.dependencyDetection.begin(); // Begin suppressing dependency detection (by setting the top frame to undefined) 1397 for (var i = 0, subscription; subscription = subs[i]; ++i) { 1398 // In case a subscription was disposed during the arrayForEach cycle, check 1399 // for isDisposed on each subscription before invoking its callback 1400 if (!subscription._isDisposed) 1401 subscription._callback(valueToNotify); 1402 } 1403 } finally { 1404 ko.dependencyDetection.end(); // End suppressing dependency detection 1405 } 1406 } 1407 }, 1408 1409 getVersion: function () { 1410 return this._versionNumber; 1411 }, 1412 1413 hasChanged: function (versionToCheck) { 1414 return this.getVersion() !== versionToCheck; 1415 }, 1416 1417 updateVersion: function () { 1418 ++this._versionNumber; 1419 }, 1420 1421 limit: function (limitFunction) { 1422 var self = this, selfIsObservable = ko.isObservable(self), 1423 ignoreBeforeChange, notifyNextChange, previousValue, pendingValue, didUpdate, 1424 beforeChange = 'beforeChange'; 1425 1426 if (!self._origNotifySubscribers) { 1427 self._origNotifySubscribers = self["notifySubscribers"]; 1428 self["notifySubscribers"] = limitNotifySubscribers; 1429 } 1430 1431 var finish = limitFunction(function () { 1432 self._notificationIsPending = false; 1433 1434 // If an observable provided a reference to itself, access it to get the latest value. 1435 // This allows computed observables to delay calculating their value until needed. 1436 if (selfIsObservable && pendingValue === self) { 1437 pendingValue = self._evalIfChanged ? self._evalIfChanged() : self(); 1438 } 1439 var shouldNotify = notifyNextChange || (didUpdate && self.isDifferent(previousValue, pendingValue)); 1440 1441 didUpdate = notifyNextChange = ignoreBeforeChange = false; 1442 1443 if (shouldNotify) { 1444 self._origNotifySubscribers(previousValue = pendingValue); 1445 } 1446 }); 1447 1448 self._limitChange = function (value, isDirty) { 1449 if (!isDirty || !self._notificationIsPending) { 1450 didUpdate = !isDirty; 1451 } 1452 self._changeSubscriptions = self._subscriptions[defaultEvent].slice(0); 1453 self._notificationIsPending = ignoreBeforeChange = true; 1454 pendingValue = value; 1455 finish(); 1456 }; 1457 self._limitBeforeChange = function (value) { 1458 if (!ignoreBeforeChange) { 1459 previousValue = value; 1460 self._origNotifySubscribers(value, beforeChange); 1461 } 1462 }; 1463 self._recordUpdate = function () { 1464 didUpdate = true; 1465 }; 1466 self._notifyNextChangeIfValueIsDifferent = function () { 1467 if (self.isDifferent(previousValue, self.peek(true /*evaluate*/))) { 1468 notifyNextChange = true; 1469 } 1470 }; 1471 }, 1472 1473 hasSubscriptionsForEvent: function (event) { 1474 return this._subscriptions[event] && this._subscriptions[event].length; 1475 }, 1476 1477 getSubscriptionsCount: function (event) { 1478 if (event) { 1479 return this._subscriptions[event] && this._subscriptions[event].length || 0; 1480 } else { 1481 var total = 0; 1482 ko.utils.objectForEach(this._subscriptions, function (eventName, subscriptions) { 1483 if (eventName !== 'dirty') 1484 total += subscriptions.length; 1485 }); 1486 return total; 1487 } 1488 }, 1489 1490 isDifferent: function (oldValue, newValue) { 1491 return !this['equalityComparer'] || !this['equalityComparer'](oldValue, newValue); 1492 }, 1493 1494 toString: function () { 1495 return '[object Object]' 1496 }, 1497 1498 extend: applyExtenders 1499 }; 1500 1501 ko.exportProperty(ko_subscribable_fn, 'init', ko_subscribable_fn.init); 1502 ko.exportProperty(ko_subscribable_fn, 'subscribe', ko_subscribable_fn.subscribe); 1503 ko.exportProperty(ko_subscribable_fn, 'extend', ko_subscribable_fn.extend); 1504 ko.exportProperty(ko_subscribable_fn, 'getSubscriptionsCount', ko_subscribable_fn.getSubscriptionsCount); 1505 1506 // For browsers that support proto assignment, we overwrite the prototype of each 1507 // observable instance. Since observables are functions, we need Function.prototype 1508 // to still be in the prototype chain. 1509 if (ko.utils.canSetPrototype) { 1510 ko.utils.setPrototypeOf(ko_subscribable_fn, Function.prototype); 1511 } 1512 1513 ko.subscribable['fn'] = ko_subscribable_fn; 1514 1515 1516 ko.isSubscribable = function (instance) { 1517 return instance != null && typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function"; 1518 }; 1519 1520 ko.exportSymbol('subscribable', ko.subscribable); 1521 ko.exportSymbol('isSubscribable', ko.isSubscribable); 1522 1523 ko.computedContext = ko.dependencyDetection = (function () { 1524 var outerFrames = [], 1525 currentFrame, 1526 lastId = 0; 1527 1528 // Return a unique ID that can be assigned to an observable for dependency tracking. 1529 // Theoretically, you could eventually overflow the number storage size, resulting 1530 // in duplicate IDs. But in JavaScript, the largest exact integral value is 2^53 1531 // or 9,007,199,254,740,992. If you created 1,000,000 IDs per second, it would 1532 // take over 285 years to reach that number. 1533 // Reference http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html 1534 function getId() { 1535 return ++lastId; 1536 } 1537 1538 function begin(options) { 1539 outerFrames.push(currentFrame); 1540 currentFrame = options; 1541 } 1542 1543 function end() { 1544 currentFrame = outerFrames.pop(); 1545 } 1546 1547 return { 1548 begin: begin, 1549 1550 end: end, 1551 1552 registerDependency: function (subscribable) { 1553 if (currentFrame) { 1554 if (!ko.isSubscribable(subscribable)) 1555 throw new Error("Only subscribable things can act as dependencies"); 1556 currentFrame.callback.call(currentFrame.callbackTarget, subscribable, subscribable._id || (subscribable._id = getId())); 1557 } 1558 }, 1559 1560 ignore: function (callback, callbackTarget, callbackArgs) { 1561 try { 1562 begin(); 1563 return callback.apply(callbackTarget, callbackArgs || []); 1564 } finally { 1565 end(); 1566 } 1567 }, 1568 1569 getDependenciesCount: function () { 1570 if (currentFrame) 1571 return currentFrame.computed.getDependenciesCount(); 1572 }, 1573 1574 getDependencies: function () { 1575 if (currentFrame) 1576 return currentFrame.computed.getDependencies(); 1577 }, 1578 1579 isInitial: function () { 1580 if (currentFrame) 1581 return currentFrame.isInitial; 1582 }, 1583 1584 computed: function () { 1585 if (currentFrame) 1586 return currentFrame.computed; 1587 } 1588 }; 1589 })(); 1590 1591 ko.exportSymbol('computedContext', ko.computedContext); 1592 ko.exportSymbol('computedContext.getDependenciesCount', ko.computedContext.getDependenciesCount); 1593 ko.exportSymbol('computedContext.getDependencies', ko.computedContext.getDependencies); 1594 ko.exportSymbol('computedContext.isInitial', ko.computedContext.isInitial); 1595 ko.exportSymbol('computedContext.registerDependency', ko.computedContext.registerDependency); 1596 1597 ko.exportSymbol('ignoreDependencies', ko.ignoreDependencies = ko.dependencyDetection.ignore); 1598 var observableLatestValue = ko.utils.createSymbolOrString('_latestValue'); 1599 1600 ko.observable = function (initialValue) { 1601 function observable() { 1602 if (arguments.length > 0) { 1603 // Write 1604 1605 // Ignore writes if the value hasn't changed 1606 if (observable.isDifferent(observable[observableLatestValue], arguments[0])) { 1607 observable.valueWillMutate(); 1608 observable[observableLatestValue] = arguments[0]; 1609 observable.valueHasMutated(); 1610 } 1611 return this; // Permits chained assignments 1612 } 1613 else { 1614 // Read 1615 ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation 1616 return observable[observableLatestValue]; 1617 } 1618 } 1619 1620 observable[observableLatestValue] = initialValue; 1621 1622 // Inherit from 'subscribable' 1623 if (!ko.utils.canSetPrototype) { 1624 // 'subscribable' won't be on the prototype chain unless we put it there directly 1625 ko.utils.extend(observable, ko.subscribable['fn']); 1626 } 1627 ko.subscribable['fn'].init(observable); 1628 1629 // Inherit from 'observable' 1630 ko.utils.setPrototypeOfOrExtend(observable, observableFn); 1631 1632 if (ko.options['deferUpdates']) { 1633 ko.extenders['deferred'](observable, true); 1634 } 1635 1636 return observable; 1637 } 1638 1639 // Define prototype for observables 1640 var observableFn = { 1641 'equalityComparer': valuesArePrimitiveAndEqual, 1642 peek: function () { return this[observableLatestValue]; }, 1643 valueHasMutated: function () { 1644 this['notifySubscribers'](this[observableLatestValue], 'spectate'); 1645 this['notifySubscribers'](this[observableLatestValue]); 1646 }, 1647 valueWillMutate: function () { this['notifySubscribers'](this[observableLatestValue], 'beforeChange'); } 1648 }; 1649 1650 // Note that for browsers that don't support proto assignment, the 1651 // inheritance chain is created manually in the ko.observable constructor 1652 if (ko.utils.canSetPrototype) { 1653 ko.utils.setPrototypeOf(observableFn, ko.subscribable['fn']); 1654 } 1655 1656 var protoProperty = ko.observable.protoProperty = '__ko_proto__'; 1657 observableFn[protoProperty] = ko.observable; 1658 1659 ko.isObservable = function (instance) { 1660 var proto = typeof instance == 'function' && instance[protoProperty]; 1661 if (proto && proto !== observableFn[protoProperty] && proto !== ko.computed['fn'][protoProperty]) { 1662 throw Error("Invalid object that looks like an observable; possibly from another Knockout instance"); 1663 } 1664 return !!proto; 1665 }; 1666 1667 ko.isWriteableObservable = function (instance) { 1668 return (typeof instance == 'function' && ( 1669 (instance[protoProperty] === observableFn[protoProperty]) || // Observable 1670 (instance[protoProperty] === ko.computed['fn'][protoProperty] && instance.hasWriteFunction))); // Writable computed observable 1671 }; 1672 1673 ko.exportSymbol('observable', ko.observable); 1674 ko.exportSymbol('isObservable', ko.isObservable); 1675 ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable); 1676 ko.exportSymbol('isWritableObservable', ko.isWriteableObservable); 1677 ko.exportSymbol('observable.fn', observableFn); 1678 ko.exportProperty(observableFn, 'peek', observableFn.peek); 1679 ko.exportProperty(observableFn, 'valueHasMutated', observableFn.valueHasMutated); 1680 ko.exportProperty(observableFn, 'valueWillMutate', observableFn.valueWillMutate); 1681 ko.observableArray = function (initialValues) { 1682 initialValues = initialValues || []; 1683 1684 if (typeof initialValues != 'object' || !('length' in initialValues)) 1685 throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined."); 1686 1687 var result = ko.observable(initialValues); 1688 ko.utils.setPrototypeOfOrExtend(result, ko.observableArray['fn']); 1689 return result.extend({ 'trackArrayChanges': true }); 1690 }; 1691 1692 ko.observableArray['fn'] = { 1693 'remove': function (valueOrPredicate) { 1694 var underlyingArray = this.peek(); 1695 var removedValues = []; 1696 var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; }; 1697 for (var i = 0; i < underlyingArray.length; i++) { 1698 var value = underlyingArray[i]; 1699 if (predicate(value)) { 1700 if (removedValues.length === 0) { 1701 this.valueWillMutate(); 1702 } 1703 if (underlyingArray[i] !== value) { 1704 throw Error("Array modified during remove; cannot remove item"); 1705 } 1706 removedValues.push(value); 1707 underlyingArray.splice(i, 1); 1708 i--; 1709 } 1710 } 1711 if (removedValues.length) { 1712 this.valueHasMutated(); 1713 } 1714 return removedValues; 1715 }, 1716 1717 'removeAll': function (arrayOfValues) { 1718 // If you passed zero args, we remove everything 1719 if (arrayOfValues === undefined) { 1720 var underlyingArray = this.peek(); 1721 var allValues = underlyingArray.slice(0); 1722 this.valueWillMutate(); 1723 underlyingArray.splice(0, underlyingArray.length); 1724 this.valueHasMutated(); 1725 return allValues; 1726 } 1727 // If you passed an arg, we interpret it as an array of entries to remove 1728 if (!arrayOfValues) 1729 return []; 1730 return this['remove'](function (value) { 1731 return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0; 1732 }); 1733 }, 1734 1735 'destroy': function (valueOrPredicate) { 1736 var underlyingArray = this.peek(); 1737 var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; }; 1738 this.valueWillMutate(); 1739 for (var i = underlyingArray.length - 1; i >= 0; i--) { 1740 var value = underlyingArray[i]; 1741 if (predicate(value)) 1742 value["_destroy"] = true; 1743 } 1744 this.valueHasMutated(); 1745 }, 1746 1747 'destroyAll': function (arrayOfValues) { 1748 // If you passed zero args, we destroy everything 1749 if (arrayOfValues === undefined) 1750 return this['destroy'](function () { return true }); 1751 1752 // If you passed an arg, we interpret it as an array of entries to destroy 1753 if (!arrayOfValues) 1754 return []; 1755 return this['destroy'](function (value) { 1756 return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0; 1757 }); 1758 }, 1759 1760 'indexOf': function (item) { 1761 var underlyingArray = this(); 1762 return ko.utils.arrayIndexOf(underlyingArray, item); 1763 }, 1764 1765 'replace': function (oldItem, newItem) { 1766 var index = this['indexOf'](oldItem); 1767 if (index >= 0) { 1768 this.valueWillMutate(); 1769 this.peek()[index] = newItem; 1770 this.valueHasMutated(); 1771 } 1772 }, 1773 1774 'sorted': function (compareFunction) { 1775 var arrayCopy = this().slice(0); 1776 return compareFunction ? arrayCopy.sort(compareFunction) : arrayCopy.sort(); 1777 }, 1778 1779 'reversed': function () { 1780 return this().slice(0).reverse(); 1781 } 1782 }; 1783 1784 // Note that for browsers that don't support proto assignment, the 1785 // inheritance chain is created manually in the ko.observableArray constructor 1786 if (ko.utils.canSetPrototype) { 1787 ko.utils.setPrototypeOf(ko.observableArray['fn'], ko.observable['fn']); 1788 } 1789 1790 // Populate ko.observableArray.fn with read/write functions from native arrays 1791 // Important: Do not add any additional functions here that may reasonably be used to *read* data from the array 1792 // because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale 1793 ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) { 1794 ko.observableArray['fn'][methodName] = function () { 1795 // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of 1796 // (for consistency with mutating regular observables) 1797 var underlyingArray = this.peek(); 1798 this.valueWillMutate(); 1799 this.cacheDiffForKnownOperation(underlyingArray, methodName, arguments); 1800 var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments); 1801 this.valueHasMutated(); 1802 // The native sort and reverse methods return a reference to the array, but it makes more sense to return the observable array instead. 1803 return methodCallResult === underlyingArray ? this : methodCallResult; 1804 }; 1805 }); 1806 1807 // Populate ko.observableArray.fn with read-only functions from native arrays 1808 ko.utils.arrayForEach(["slice"], function (methodName) { 1809 ko.observableArray['fn'][methodName] = function () { 1810 var underlyingArray = this(); 1811 return underlyingArray[methodName].apply(underlyingArray, arguments); 1812 }; 1813 }); 1814 1815 ko.isObservableArray = function (instance) { 1816 return ko.isObservable(instance) 1817 && typeof instance["remove"] == "function" 1818 && typeof instance["push"] == "function"; 1819 }; 1820 1821 ko.exportSymbol('observableArray', ko.observableArray); 1822 ko.exportSymbol('isObservableArray', ko.isObservableArray); 1823 var arrayChangeEventName = 'arrayChange'; 1824 ko.extenders['trackArrayChanges'] = function (target, options) { 1825 // Use the provided options--each call to trackArrayChanges overwrites the previously set options 1826 target.compareArrayOptions = {}; 1827 if (options && typeof options == "object") { 1828 ko.utils.extend(target.compareArrayOptions, options); 1829 } 1830 target.compareArrayOptions['sparse'] = true; 1831 1832 // Only modify the target observable once 1833 if (target.cacheDiffForKnownOperation) { 1834 return; 1835 } 1836 var trackingChanges = false, 1837 cachedDiff = null, 1838 changeSubscription, 1839 spectateSubscription, 1840 pendingChanges = 0, 1841 previousContents, 1842 underlyingBeforeSubscriptionAddFunction = target.beforeSubscriptionAdd, 1843 underlyingAfterSubscriptionRemoveFunction = target.afterSubscriptionRemove; 1844 1845 // Watch "subscribe" calls, and for array change events, ensure change tracking is enabled 1846 target.beforeSubscriptionAdd = function (event) { 1847 if (underlyingBeforeSubscriptionAddFunction) { 1848 underlyingBeforeSubscriptionAddFunction.call(target, event); 1849 } 1850 if (event === arrayChangeEventName) { 1851 trackChanges(); 1852 } 1853 }; 1854 // Watch "dispose" calls, and for array change events, ensure change tracking is disabled when all are disposed 1855 target.afterSubscriptionRemove = function (event) { 1856 if (underlyingAfterSubscriptionRemoveFunction) { 1857 underlyingAfterSubscriptionRemoveFunction.call(target, event); 1858 } 1859 if (event === arrayChangeEventName && !target.hasSubscriptionsForEvent(arrayChangeEventName)) { 1860 if (changeSubscription) { 1861 changeSubscription.dispose(); 1862 } 1863 if (spectateSubscription) { 1864 spectateSubscription.dispose(); 1865 } 1866 spectateSubscription = changeSubscription = null; 1867 trackingChanges = false; 1868 previousContents = undefined; 1869 } 1870 }; 1871 1872 function trackChanges() { 1873 if (trackingChanges) { 1874 // Whenever there's a new subscription and there are pending notifications, make sure all previous 1875 // subscriptions are notified of the change so that all subscriptions are in sync. 1876 notifyChanges(); 1877 return; 1878 } 1879 1880 trackingChanges = true; 1881 1882 // Track how many times the array actually changed value 1883 spectateSubscription = target.subscribe(function () { 1884 ++pendingChanges; 1885 }, null, "spectate"); 1886 1887 // Each time the array changes value, capture a clone so that on the next 1888 // change it's possible to produce a diff 1889 previousContents = [].concat(target.peek() || []); 1890 cachedDiff = null; 1891 changeSubscription = target.subscribe(notifyChanges); 1892 1893 function notifyChanges() { 1894 if (pendingChanges) { 1895 // Make a copy of the current contents and ensure it's an array 1896 var currentContents = [].concat(target.peek() || []), changes; 1897 1898 // Compute the diff and issue notifications, but only if someone is listening 1899 if (target.hasSubscriptionsForEvent(arrayChangeEventName)) { 1900 changes = getChanges(previousContents, currentContents); 1901 } 1902 1903 // Eliminate references to the old, removed items, so they can be GCed 1904 previousContents = currentContents; 1905 cachedDiff = null; 1906 pendingChanges = 0; 1907 1908 if (changes && changes.length) { 1909 target['notifySubscribers'](changes, arrayChangeEventName); 1910 } 1911 } 1912 } 1913 } 1914 1915 function getChanges(previousContents, currentContents) { 1916 // We try to re-use cached diffs. 1917 // The scenarios where pendingChanges > 1 are when using rate limiting or deferred updates, 1918 // which without this check would not be compatible with arrayChange notifications. Normally, 1919 // notifications are issued immediately so we wouldn't be queueing up more than one. 1920 if (!cachedDiff || pendingChanges > 1) { 1921 cachedDiff = ko.utils.compareArrays(previousContents, currentContents, target.compareArrayOptions); 1922 } 1923 1924 return cachedDiff; 1925 } 1926 1927 target.cacheDiffForKnownOperation = function (rawArray, operationName, args) { 1928 // Only run if we're currently tracking changes for this observable array 1929 // and there aren't any pending deferred notifications. 1930 if (!trackingChanges || pendingChanges) { 1931 return; 1932 } 1933 var diff = [], 1934 arrayLength = rawArray.length, 1935 argsLength = args.length, 1936 offset = 0; 1937 1938 function pushDiff(status, value, index) { 1939 return diff[diff.length] = { 'status': status, 'value': value, 'index': index }; 1940 } 1941 switch (operationName) { 1942 case 'push': 1943 offset = arrayLength; 1944 case 'unshift': 1945 for (var index = 0; index < argsLength; index++) { 1946 pushDiff('added', args[index], offset + index); 1947 } 1948 break; 1949 1950 case 'pop': 1951 offset = arrayLength - 1; 1952 case 'shift': 1953 if (arrayLength) { 1954 pushDiff('deleted', rawArray[offset], offset); 1955 } 1956 break; 1957 1958 case 'splice': 1959 // Negative start index means 'from end of array'. After that we clamp to [0...arrayLength]. 1960 // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice 1961 var startIndex = Math.min(Math.max(0, args[0] < 0 ? arrayLength + args[0] : args[0]), arrayLength), 1962 endDeleteIndex = argsLength === 1 ? arrayLength : Math.min(startIndex + (args[1] || 0), arrayLength), 1963 endAddIndex = startIndex + argsLength - 2, 1964 endIndex = Math.max(endDeleteIndex, endAddIndex), 1965 additions = [], deletions = []; 1966 for (var index = startIndex, argsIndex = 2; index < endIndex; ++index, ++argsIndex) { 1967 if (index < endDeleteIndex) 1968 deletions.push(pushDiff('deleted', rawArray[index], index)); 1969 if (index < endAddIndex) 1970 additions.push(pushDiff('added', args[argsIndex], index)); 1971 } 1972 ko.utils.findMovesInArrayComparison(deletions, additions); 1973 break; 1974 1975 default: 1976 return; 1977 } 1978 cachedDiff = diff; 1979 }; 1980 }; 1981 var computedState = ko.utils.createSymbolOrString('_state'); 1982 1983 ko.computed = ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) { 1984 if (typeof evaluatorFunctionOrOptions === "object") { 1985 // Single-parameter syntax - everything is on this "options" param 1986 options = evaluatorFunctionOrOptions; 1987 } else { 1988 // Multi-parameter syntax - construct the options according to the params passed 1989 options = options || {}; 1990 if (evaluatorFunctionOrOptions) { 1991 options["read"] = evaluatorFunctionOrOptions; 1992 } 1993 } 1994 if (typeof options["read"] != "function") 1995 throw Error("Pass a function that returns the value of the ko.computed"); 1996 1997 var writeFunction = options["write"]; 1998 var state = { 1999 latestValue: undefined, 2000 isStale: true, 2001 isDirty: true, 2002 isBeingEvaluated: false, 2003 suppressDisposalUntilDisposeWhenReturnsFalse: false, 2004 isDisposed: false, 2005 pure: false, 2006 isSleeping: false, 2007 readFunction: options["read"], 2008 evaluatorFunctionTarget: evaluatorFunctionTarget || options["owner"], 2009 disposeWhenNodeIsRemoved: options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null, 2010 disposeWhen: options["disposeWhen"] || options.disposeWhen, 2011 domNodeDisposalCallback: null, 2012 dependencyTracking: {}, 2013 dependenciesCount: 0, 2014 evaluationTimeoutInstance: null 2015 }; 2016 2017 function computedObservable() { 2018 if (arguments.length > 0) { 2019 if (typeof writeFunction === "function") { 2020 // Writing a value 2021 writeFunction.apply(state.evaluatorFunctionTarget, arguments); 2022 } else { 2023 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."); 2024 } 2025 return this; // Permits chained assignments 2026 } else { 2027 // Reading the value 2028 if (!state.isDisposed) { 2029 ko.dependencyDetection.registerDependency(computedObservable); 2030 } 2031 if (state.isDirty || (state.isSleeping && computedObservable.haveDependenciesChanged())) { 2032 computedObservable.evaluateImmediate(); 2033 } 2034 return state.latestValue; 2035 } 2036 } 2037 2038 computedObservable[computedState] = state; 2039 computedObservable.hasWriteFunction = typeof writeFunction === "function"; 2040 2041 // Inherit from 'subscribable' 2042 if (!ko.utils.canSetPrototype) { 2043 // 'subscribable' won't be on the prototype chain unless we put it there directly 2044 ko.utils.extend(computedObservable, ko.subscribable['fn']); 2045 } 2046 ko.subscribable['fn'].init(computedObservable); 2047 2048 // Inherit from 'computed' 2049 ko.utils.setPrototypeOfOrExtend(computedObservable, computedFn); 2050 2051 if (options['pure']) { 2052 state.pure = true; 2053 state.isSleeping = true; // Starts off sleeping; will awake on the first subscription 2054 ko.utils.extend(computedObservable, pureComputedOverrides); 2055 } else if (options['deferEvaluation']) { 2056 ko.utils.extend(computedObservable, deferEvaluationOverrides); 2057 } 2058 2059 if (ko.options['deferUpdates']) { 2060 ko.extenders['deferred'](computedObservable, true); 2061 } 2062 2063 if (DEBUG) { 2064 // #1731 - Aid debugging by exposing the computed's options 2065 computedObservable["_options"] = options; 2066 } 2067 2068 if (state.disposeWhenNodeIsRemoved) { 2069 // Since this computed is associated with a DOM node, and we don't want to dispose the computed 2070 // until the DOM node is *removed* from the document (as opposed to never having been in the document), 2071 // we'll prevent disposal until "disposeWhen" first returns false. 2072 state.suppressDisposalUntilDisposeWhenReturnsFalse = true; 2073 2074 // disposeWhenNodeIsRemoved: true can be used to opt into the "only dispose after first false result" 2075 // behaviour even if there's no specific node to watch. In that case, clear the option so we don't try 2076 // to watch for a non-node's disposal. This technique is intended for KO's internal use only and shouldn't 2077 // be documented or used by application code, as it's likely to change in a future version of KO. 2078 if (!state.disposeWhenNodeIsRemoved.nodeType) { 2079 state.disposeWhenNodeIsRemoved = null; 2080 } 2081 } 2082 2083 // Evaluate, unless sleeping or deferEvaluation is true 2084 if (!state.isSleeping && !options['deferEvaluation']) { 2085 computedObservable.evaluateImmediate(); 2086 } 2087 2088 // Attach a DOM node disposal callback so that the computed will be proactively disposed as soon as the node is 2089 // removed using ko.removeNode. But skip if isActive is false (there will never be any dependencies to dispose). 2090 if (state.disposeWhenNodeIsRemoved && computedObservable.isActive()) { 2091 ko.utils.domNodeDisposal.addDisposeCallback(state.disposeWhenNodeIsRemoved, state.domNodeDisposalCallback = function () { 2092 computedObservable.dispose(); 2093 }); 2094 } 2095 2096 return computedObservable; 2097 }; 2098 2099 // Utility function that disposes a given dependencyTracking entry 2100 function computedDisposeDependencyCallback(id, entryToDispose) { 2101 if (entryToDispose !== null && entryToDispose.dispose) { 2102 entryToDispose.dispose(); 2103 } 2104 } 2105 2106 // This function gets called each time a dependency is detected while evaluating a computed. 2107 // It's factored out as a shared function to avoid creating unnecessary function instances during evaluation. 2108 function computedBeginDependencyDetectionCallback(subscribable, id) { 2109 var computedObservable = this.computedObservable, 2110 state = computedObservable[computedState]; 2111 if (!state.isDisposed) { 2112 if (this.disposalCount && this.disposalCandidates[id]) { 2113 // Don't want to dispose this subscription, as it's still being used 2114 computedObservable.addDependencyTracking(id, subscribable, this.disposalCandidates[id]); 2115 this.disposalCandidates[id] = null; // No need to actually delete the property - disposalCandidates is a transient object anyway 2116 --this.disposalCount; 2117 } else if (!state.dependencyTracking[id]) { 2118 // Brand new subscription - add it 2119 computedObservable.addDependencyTracking(id, subscribable, state.isSleeping ? { _target: subscribable } : computedObservable.subscribeToDependency(subscribable)); 2120 } 2121 // If the observable we've accessed has a pending notification, ensure we get notified of the actual final value (bypass equality checks) 2122 if (subscribable._notificationIsPending) { 2123 subscribable._notifyNextChangeIfValueIsDifferent(); 2124 } 2125 } 2126 } 2127 2128 var computedFn = { 2129 "equalityComparer": valuesArePrimitiveAndEqual, 2130 getDependenciesCount: function () { 2131 return this[computedState].dependenciesCount; 2132 }, 2133 getDependencies: function () { 2134 var dependencyTracking = this[computedState].dependencyTracking, dependentObservables = []; 2135 2136 ko.utils.objectForEach(dependencyTracking, function (id, dependency) { 2137 dependentObservables[dependency._order] = dependency._target; 2138 }); 2139 2140 return dependentObservables; 2141 }, 2142 hasAncestorDependency: function (obs) { 2143 if (!this[computedState].dependenciesCount) { 2144 return false; 2145 } 2146 var dependencies = this.getDependencies(); 2147 if (ko.utils.arrayIndexOf(dependencies, obs) !== -1) { 2148 return true; 2149 } 2150 return !!ko.utils.arrayFirst(dependencies, function (dep) { 2151 return dep.hasAncestorDependency && dep.hasAncestorDependency(obs); 2152 }); 2153 }, 2154 addDependencyTracking: function (id, target, trackingObj) { 2155 if (this[computedState].pure && target === this) { 2156 throw Error("A 'pure' computed must not be called recursively"); 2157 } 2158 2159 this[computedState].dependencyTracking[id] = trackingObj; 2160 trackingObj._order = this[computedState].dependenciesCount++; 2161 trackingObj._version = target.getVersion(); 2162 }, 2163 haveDependenciesChanged: function () { 2164 var id, dependency, dependencyTracking = this[computedState].dependencyTracking; 2165 for (id in dependencyTracking) { 2166 if (Object.prototype.hasOwnProperty.call(dependencyTracking, id)) { 2167 dependency = dependencyTracking[id]; 2168 if ((this._evalDelayed && dependency._target._notificationIsPending) || dependency._target.hasChanged(dependency._version)) { 2169 return true; 2170 } 2171 } 2172 } 2173 }, 2174 markDirty: function () { 2175 // Process "dirty" events if we can handle delayed notifications 2176 if (this._evalDelayed && !this[computedState].isBeingEvaluated) { 2177 this._evalDelayed(false /*isChange*/); 2178 } 2179 }, 2180 isActive: function () { 2181 var state = this[computedState]; 2182 return state.isDirty || state.dependenciesCount > 0; 2183 }, 2184 respondToChange: function () { 2185 // Ignore "change" events if we've already scheduled a delayed notification 2186 if (!this._notificationIsPending) { 2187 this.evaluatePossiblyAsync(); 2188 } else if (this[computedState].isDirty) { 2189 this[computedState].isStale = true; 2190 } 2191 }, 2192 subscribeToDependency: function (target) { 2193 if (target._deferUpdates) { 2194 var dirtySub = target.subscribe(this.markDirty, this, 'dirty'), 2195 changeSub = target.subscribe(this.respondToChange, this); 2196 return { 2197 _target: target, 2198 dispose: function () { 2199 dirtySub.dispose(); 2200 changeSub.dispose(); 2201 } 2202 }; 2203 } else { 2204 return target.subscribe(this.evaluatePossiblyAsync, this); 2205 } 2206 }, 2207 evaluatePossiblyAsync: function () { 2208 var computedObservable = this, 2209 throttleEvaluationTimeout = computedObservable['throttleEvaluation']; 2210 if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) { 2211 clearTimeout(this[computedState].evaluationTimeoutInstance); 2212 this[computedState].evaluationTimeoutInstance = ko.utils.setTimeout(function () { 2213 computedObservable.evaluateImmediate(true /*notifyChange*/); 2214 }, throttleEvaluationTimeout); 2215 } else if (computedObservable._evalDelayed) { 2216 computedObservable._evalDelayed(true /*isChange*/); 2217 } else { 2218 computedObservable.evaluateImmediate(true /*notifyChange*/); 2219 } 2220 }, 2221 evaluateImmediate: function (notifyChange) { 2222 var computedObservable = this, 2223 state = computedObservable[computedState], 2224 disposeWhen = state.disposeWhen, 2225 changed = false; 2226 2227 if (state.isBeingEvaluated) { 2228 // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation. 2229 // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost 2230 // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing 2231 // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387 2232 return; 2233 } 2234 2235 // Do not evaluate (and possibly capture new dependencies) if disposed 2236 if (state.isDisposed) { 2237 return; 2238 } 2239 2240 if (state.disposeWhenNodeIsRemoved && !ko.utils.domNodeIsAttachedToDocument(state.disposeWhenNodeIsRemoved) || disposeWhen && disposeWhen()) { 2241 // See comment above about suppressDisposalUntilDisposeWhenReturnsFalse 2242 if (!state.suppressDisposalUntilDisposeWhenReturnsFalse) { 2243 computedObservable.dispose(); 2244 return; 2245 } 2246 } else { 2247 // It just did return false, so we can stop suppressing now 2248 state.suppressDisposalUntilDisposeWhenReturnsFalse = false; 2249 } 2250 2251 state.isBeingEvaluated = true; 2252 try { 2253 changed = this.evaluateImmediate_CallReadWithDependencyDetection(notifyChange); 2254 } finally { 2255 state.isBeingEvaluated = false; 2256 } 2257 2258 return changed; 2259 }, 2260 evaluateImmediate_CallReadWithDependencyDetection: function (notifyChange) { 2261 // This function is really just part of the evaluateImmediate logic. You would never call it from anywhere else. 2262 // Factoring it out into a separate function means it can be independent of the try/catch block in evaluateImmediate, 2263 // which contributes to saving about 40% off the CPU overhead of computed evaluation (on V8 at least). 2264 2265 var computedObservable = this, 2266 state = computedObservable[computedState], 2267 changed = false; 2268 2269 // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal). 2270 // Then, during evaluation, we cross off any that are in fact still being used. 2271 var isInitial = state.pure ? undefined : !state.dependenciesCount, // If we're evaluating when there are no previous dependencies, it must be the first time 2272 dependencyDetectionContext = { 2273 computedObservable: computedObservable, 2274 disposalCandidates: state.dependencyTracking, 2275 disposalCount: state.dependenciesCount 2276 }; 2277 2278 ko.dependencyDetection.begin({ 2279 callbackTarget: dependencyDetectionContext, 2280 callback: computedBeginDependencyDetectionCallback, 2281 computed: computedObservable, 2282 isInitial: isInitial 2283 }); 2284 2285 state.dependencyTracking = {}; 2286 state.dependenciesCount = 0; 2287 2288 var newValue = this.evaluateImmediate_CallReadThenEndDependencyDetection(state, dependencyDetectionContext); 2289 2290 if (!state.dependenciesCount) { 2291 computedObservable.dispose(); 2292 changed = true; // When evaluation causes a disposal, make sure all dependent computeds get notified so they'll see the new state 2293 } else { 2294 changed = computedObservable.isDifferent(state.latestValue, newValue); 2295 } 2296 2297 if (changed) { 2298 if (!state.isSleeping) { 2299 computedObservable["notifySubscribers"](state.latestValue, "beforeChange"); 2300 } else { 2301 computedObservable.updateVersion(); 2302 } 2303 2304 state.latestValue = newValue; 2305 if (DEBUG) computedObservable._latestValue = newValue; 2306 2307 computedObservable["notifySubscribers"](state.latestValue, "spectate"); 2308 2309 if (!state.isSleeping && notifyChange) { 2310 computedObservable["notifySubscribers"](state.latestValue); 2311 } 2312 if (computedObservable._recordUpdate) { 2313 computedObservable._recordUpdate(); 2314 } 2315 } 2316 2317 if (isInitial) { 2318 computedObservable["notifySubscribers"](state.latestValue, "awake"); 2319 } 2320 2321 return changed; 2322 }, 2323 evaluateImmediate_CallReadThenEndDependencyDetection: function (state, dependencyDetectionContext) { 2324 // This function is really part of the evaluateImmediate_CallReadWithDependencyDetection logic. 2325 // You'd never call it from anywhere else. Factoring it out means that evaluateImmediate_CallReadWithDependencyDetection 2326 // can be independent of try/finally blocks, which contributes to saving about 40% off the CPU 2327 // overhead of computed evaluation (on V8 at least). 2328 2329 try { 2330 var readFunction = state.readFunction; 2331 return state.evaluatorFunctionTarget ? readFunction.call(state.evaluatorFunctionTarget) : readFunction(); 2332 } finally { 2333 ko.dependencyDetection.end(); 2334 2335 // For each subscription no longer being used, remove it from the active subscriptions list and dispose it 2336 if (dependencyDetectionContext.disposalCount && !state.isSleeping) { 2337 ko.utils.objectForEach(dependencyDetectionContext.disposalCandidates, computedDisposeDependencyCallback); 2338 } 2339 2340 state.isStale = state.isDirty = false; 2341 } 2342 }, 2343 peek: function (evaluate) { 2344 // By default, peek won't re-evaluate, except while the computed is sleeping or to get the initial value when "deferEvaluation" is set. 2345 // Pass in true to evaluate if needed. 2346 var state = this[computedState]; 2347 if ((state.isDirty && (evaluate || !state.dependenciesCount)) || (state.isSleeping && this.haveDependenciesChanged())) { 2348 this.evaluateImmediate(); 2349 } 2350 return state.latestValue; 2351 }, 2352 limit: function (limitFunction) { 2353 // Override the limit function with one that delays evaluation as well 2354 ko.subscribable['fn'].limit.call(this, limitFunction); 2355 this._evalIfChanged = function () { 2356 if (!this[computedState].isSleeping) { 2357 if (this[computedState].isStale) { 2358 this.evaluateImmediate(); 2359 } else { 2360 this[computedState].isDirty = false; 2361 } 2362 } 2363 return this[computedState].latestValue; 2364 }; 2365 this._evalDelayed = function (isChange) { 2366 this._limitBeforeChange(this[computedState].latestValue); 2367 2368 // Mark as dirty 2369 this[computedState].isDirty = true; 2370 if (isChange) { 2371 this[computedState].isStale = true; 2372 } 2373 2374 // Pass the observable to the "limit" code, which will evaluate it when 2375 // it's time to do the notification. 2376 this._limitChange(this, !isChange /* isDirty */); 2377 }; 2378 }, 2379 dispose: function () { 2380 var state = this[computedState]; 2381 if (!state.isSleeping && state.dependencyTracking) { 2382 ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) { 2383 if (dependency.dispose) 2384 dependency.dispose(); 2385 }); 2386 } 2387 if (state.disposeWhenNodeIsRemoved && state.domNodeDisposalCallback) { 2388 ko.utils.domNodeDisposal.removeDisposeCallback(state.disposeWhenNodeIsRemoved, state.domNodeDisposalCallback); 2389 } 2390 state.dependencyTracking = undefined; 2391 state.dependenciesCount = 0; 2392 state.isDisposed = true; 2393 state.isStale = false; 2394 state.isDirty = false; 2395 state.isSleeping = false; 2396 state.disposeWhenNodeIsRemoved = undefined; 2397 state.disposeWhen = undefined; 2398 state.readFunction = undefined; 2399 if (!this.hasWriteFunction) { 2400 state.evaluatorFunctionTarget = undefined; 2401 } 2402 } 2403 }; 2404 2405 var pureComputedOverrides = { 2406 beforeSubscriptionAdd: function (event) { 2407 // If asleep, wake up the computed by subscribing to any dependencies. 2408 var computedObservable = this, 2409 state = computedObservable[computedState]; 2410 if (!state.isDisposed && state.isSleeping && event == 'change') { 2411 state.isSleeping = false; 2412 if (state.isStale || computedObservable.haveDependenciesChanged()) { 2413 state.dependencyTracking = null; 2414 state.dependenciesCount = 0; 2415 if (computedObservable.evaluateImmediate()) { 2416 computedObservable.updateVersion(); 2417 } 2418 } else { 2419 // First put the dependencies in order 2420 var dependenciesOrder = []; 2421 ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) { 2422 dependenciesOrder[dependency._order] = id; 2423 }); 2424 // Next, subscribe to each one 2425 ko.utils.arrayForEach(dependenciesOrder, function (id, order) { 2426 var dependency = state.dependencyTracking[id], 2427 subscription = computedObservable.subscribeToDependency(dependency._target); 2428 subscription._order = order; 2429 subscription._version = dependency._version; 2430 state.dependencyTracking[id] = subscription; 2431 }); 2432 // Waking dependencies may have triggered effects 2433 if (computedObservable.haveDependenciesChanged()) { 2434 if (computedObservable.evaluateImmediate()) { 2435 computedObservable.updateVersion(); 2436 } 2437 } 2438 } 2439 2440 if (!state.isDisposed) { // test since evaluating could trigger disposal 2441 computedObservable["notifySubscribers"](state.latestValue, "awake"); 2442 } 2443 } 2444 }, 2445 afterSubscriptionRemove: function (event) { 2446 var state = this[computedState]; 2447 if (!state.isDisposed && event == 'change' && !this.hasSubscriptionsForEvent('change')) { 2448 ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) { 2449 if (dependency.dispose) { 2450 state.dependencyTracking[id] = { 2451 _target: dependency._target, 2452 _order: dependency._order, 2453 _version: dependency._version 2454 }; 2455 dependency.dispose(); 2456 } 2457 }); 2458 state.isSleeping = true; 2459 this["notifySubscribers"](undefined, "asleep"); 2460 } 2461 }, 2462 getVersion: function () { 2463 // Because a pure computed is not automatically updated while it is sleeping, we can't 2464 // simply return the version number. Instead, we check if any of the dependencies have 2465 // changed and conditionally re-evaluate the computed observable. 2466 var state = this[computedState]; 2467 if (state.isSleeping && (state.isStale || this.haveDependenciesChanged())) { 2468 this.evaluateImmediate(); 2469 } 2470 return ko.subscribable['fn'].getVersion.call(this); 2471 } 2472 }; 2473 2474 var deferEvaluationOverrides = { 2475 beforeSubscriptionAdd: function (event) { 2476 // This will force a computed with deferEvaluation to evaluate when the first subscription is registered. 2477 if (event == 'change' || event == 'beforeChange') { 2478 this.peek(); 2479 } 2480 } 2481 }; 2482 2483 // Note that for browsers that don't support proto assignment, the 2484 // inheritance chain is created manually in the ko.computed constructor 2485 if (ko.utils.canSetPrototype) { 2486 ko.utils.setPrototypeOf(computedFn, ko.subscribable['fn']); 2487 } 2488 2489 // Set the proto values for ko.computed 2490 var protoProp = ko.observable.protoProperty; // == "__ko_proto__" 2491 computedFn[protoProp] = ko.computed; 2492 2493 ko.isComputed = function (instance) { 2494 return (typeof instance == 'function' && instance[protoProp] === computedFn[protoProp]); 2495 }; 2496 2497 ko.isPureComputed = function (instance) { 2498 return ko.isComputed(instance) && instance[computedState] && instance[computedState].pure; 2499 }; 2500 2501 ko.exportSymbol('computed', ko.computed); 2502 ko.exportSymbol('dependentObservable', ko.computed); // export ko.dependentObservable for backwards compatibility (1.x) 2503 ko.exportSymbol('isComputed', ko.isComputed); 2504 ko.exportSymbol('isPureComputed', ko.isPureComputed); 2505 ko.exportSymbol('computed.fn', computedFn); 2506 ko.exportProperty(computedFn, 'peek', computedFn.peek); 2507 ko.exportProperty(computedFn, 'dispose', computedFn.dispose); 2508 ko.exportProperty(computedFn, 'isActive', computedFn.isActive); 2509 ko.exportProperty(computedFn, 'getDependenciesCount', computedFn.getDependenciesCount); 2510 ko.exportProperty(computedFn, 'getDependencies', computedFn.getDependencies); 2511 2512 ko.pureComputed = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget) { 2513 if (typeof evaluatorFunctionOrOptions === 'function') { 2514 return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget, { 'pure': true }); 2515 } else { 2516 evaluatorFunctionOrOptions = ko.utils.extend({}, evaluatorFunctionOrOptions); // make a copy of the parameter object 2517 evaluatorFunctionOrOptions['pure'] = true; 2518 return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget); 2519 } 2520 } 2521 ko.exportSymbol('pureComputed', ko.pureComputed); 2522 2523 (function () { 2524 var maxNestedObservableDepth = 10; // Escape the (unlikely) pathological case where an observable's current value is itself (or similar reference cycle) 2525 2526 ko.toJS = function (rootObject) { 2527 if (arguments.length == 0) 2528 throw new Error("When calling ko.toJS, pass the object you want to convert."); 2529 2530 // We just unwrap everything at every level in the object graph 2531 return mapJsObjectGraph(rootObject, function (valueToMap) { 2532 // Loop because an observable's value might in turn be another observable wrapper 2533 for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++) 2534 valueToMap = valueToMap(); 2535 return valueToMap; 2536 }); 2537 }; 2538 2539 ko.toJSON = function (rootObject, replacer, space) { // replacer and space are optional 2540 var plainJavaScriptObject = ko.toJS(rootObject); 2541 return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space); 2542 }; 2543 2544 function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) { 2545 visitedObjects = visitedObjects || new objectLookup(); 2546 2547 rootObject = mapInputCallback(rootObject); 2548 var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof RegExp)) && (!(rootObject instanceof Date)) && (!(rootObject instanceof String)) && (!(rootObject instanceof Number)) && (!(rootObject instanceof Boolean)); 2549 if (!canHaveProperties) 2550 return rootObject; 2551 2552 var outputProperties = rootObject instanceof Array ? [] : {}; 2553 visitedObjects.save(rootObject, outputProperties); 2554 2555 visitPropertiesOrArrayEntries(rootObject, function (indexer) { 2556 var propertyValue = mapInputCallback(rootObject[indexer]); 2557 2558 switch (typeof propertyValue) { 2559 case "boolean": 2560 case "number": 2561 case "string": 2562 case "function": 2563 outputProperties[indexer] = propertyValue; 2564 break; 2565 case "object": 2566 case "undefined": 2567 var previouslyMappedValue = visitedObjects.get(propertyValue); 2568 outputProperties[indexer] = (previouslyMappedValue !== undefined) 2569 ? previouslyMappedValue 2570 : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects); 2571 break; 2572 } 2573 }); 2574 2575 return outputProperties; 2576 } 2577 2578 function visitPropertiesOrArrayEntries(rootObject, visitorCallback) { 2579 if (rootObject instanceof Array) { 2580 for (var i = 0; i < rootObject.length; i++) 2581 visitorCallback(i); 2582 2583 // For arrays, also respect toJSON property for custom mappings (fixes #278) 2584 if (typeof rootObject['toJSON'] == 'function') 2585 visitorCallback('toJSON'); 2586 } else { 2587 for (var propertyName in rootObject) { 2588 visitorCallback(propertyName); 2589 } 2590 } 2591 }; 2592 2593 function objectLookup() { 2594 this.keys = []; 2595 this.values = []; 2596 }; 2597 2598 objectLookup.prototype = { 2599 constructor: objectLookup, 2600 save: function (key, value) { 2601 var existingIndex = ko.utils.arrayIndexOf(this.keys, key); 2602 if (existingIndex >= 0) 2603 this.values[existingIndex] = value; 2604 else { 2605 this.keys.push(key); 2606 this.values.push(value); 2607 } 2608 }, 2609 get: function (key) { 2610 var existingIndex = ko.utils.arrayIndexOf(this.keys, key); 2611 return (existingIndex >= 0) ? this.values[existingIndex] : undefined; 2612 } 2613 }; 2614 })(); 2615 2616 ko.exportSymbol('toJS', ko.toJS); 2617 ko.exportSymbol('toJSON', ko.toJSON); 2618 ko.when = function (predicate, callback, context) { 2619 function kowhen(resolve) { 2620 var observable = ko.pureComputed(predicate, context).extend({ notify: 'always' }); 2621 var subscription = observable.subscribe(function (value) { 2622 if (value) { 2623 subscription.dispose(); 2624 resolve(value); 2625 } 2626 }); 2627 // In case the initial value is true, process it right away 2628 observable['notifySubscribers'](observable.peek()); 2629 2630 return subscription; 2631 } 2632 if (typeof Promise === "function" && !callback) { 2633 return new Promise(kowhen); 2634 } else { 2635 return kowhen(callback.bind(context)); 2636 } 2637 }; 2638 2639 ko.exportSymbol('when', ko.when); 2640 (function () { 2641 var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__'; 2642 2643 // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values 2644 // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values 2645 // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns. 2646 ko.selectExtensions = { 2647 readValue: function (element) { 2648 switch (ko.utils.tagNameLower(element)) { 2649 case 'option': 2650 if (element[hasDomDataExpandoProperty] === true) 2651 return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey); 2652 return ko.utils.ieVersion <= 7 2653 ? (element.getAttributeNode('value') && element.getAttributeNode('value').specified ? element.value : element.text) 2654 : element.value; 2655 case 'select': 2656 return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined; 2657 default: 2658 return element.value; 2659 } 2660 }, 2661 2662 writeValue: function (element, value, allowUnset) { 2663 switch (ko.utils.tagNameLower(element)) { 2664 case 'option': 2665 if (typeof value === "string") { 2666 ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined); 2667 if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node 2668 delete element[hasDomDataExpandoProperty]; 2669 } 2670 element.value = value; 2671 } 2672 else { 2673 // Store arbitrary object using DomData 2674 ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value); 2675 element[hasDomDataExpandoProperty] = true; 2676 2677 // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value. 2678 element.value = typeof value === "number" ? value : ""; 2679 } 2680 break; 2681 case 'select': 2682 if (value === "" || value === null) // A blank string or null value will select the caption 2683 value = undefined; 2684 var selection = -1; 2685 for (var i = 0, n = element.options.length, optionValue; i < n; ++i) { 2686 optionValue = ko.selectExtensions.readValue(element.options[i]); 2687 // Include special check to handle selecting a caption with a blank string value 2688 if (optionValue == value || (optionValue === "" && value === undefined)) { 2689 selection = i; 2690 break; 2691 } 2692 } 2693 if (allowUnset || selection >= 0 || (value === undefined && element.size > 1)) { 2694 element.selectedIndex = selection; 2695 if (ko.utils.ieVersion === 6) { 2696 // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread 2697 // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread 2698 // to apply the value as well. 2699 ko.utils.setTimeout(function () { 2700 element.selectedIndex = selection; 2701 }, 0); 2702 } 2703 } 2704 break; 2705 default: 2706 if ((value === null) || (value === undefined)) 2707 value = ""; 2708 element.value = value; 2709 break; 2710 } 2711 } 2712 }; 2713 })(); 2714 2715 ko.exportSymbol('selectExtensions', ko.selectExtensions); 2716 ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue); 2717 ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue); 2718 ko.expressionRewriting = (function () { 2719 var javaScriptReservedWords = ["true", "false", "null", "undefined"]; 2720 2721 // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor 2722 // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c). 2723 // This also will not properly handle nested brackets (e.g., obj1[obj2['prop']]; see #911). 2724 var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i; 2725 2726 function getWriteableValue(expression) { 2727 if (ko.utils.arrayIndexOf(javaScriptReservedWords, expression) >= 0) 2728 return false; 2729 var match = expression.match(javaScriptAssignmentTarget); 2730 return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression; 2731 } 2732 2733 // The following regular expressions will be used to split an object-literal string into tokens 2734 2735 var specials = ',"\'`{}()/:[\\]', // These characters have special meaning to the parser and must not appear in the middle of a token, except as part of a string. 2736 // Create the actual regular expression by or-ing the following regex strings. The order is important. 2737 bindingToken = RegExp([ 2738 // These match strings, either with double quotes, single quotes, or backticks 2739 '"(?:\\\\.|[^"])*"', 2740 "'(?:\\\\.|[^'])*'", 2741 "`(?:\\\\.|[^`])*`", 2742 // Match C style comments 2743 "/\\*(?:[^*]|\\*+[^*/])*\\*+/", 2744 // Match C++ style comments 2745 "//.*\n", 2746 // Match a regular expression (text enclosed by slashes), but will also match sets of divisions 2747 // as a regular expression (this is handled by the parsing loop below). 2748 '/(?:\\\\.|[^/])+/\w*', 2749 // Match text (at least two characters) that does not contain any of the above special characters, 2750 // although some of the special characters are allowed to start it (all but the colon and comma). 2751 // The text can contain spaces, but leading or trailing spaces are skipped. 2752 '[^\\s:,/][^' + specials + ']*[^\\s' + specials + ']', 2753 // Match any non-space character not matched already. This will match colons and commas, since they're 2754 // not matched by "everyThingElse", but will also match any other single character that wasn't already 2755 // matched (for example: in "a: 1, b: 2", each of the non-space characters will be matched by oneNotSpace). 2756 '[^\\s]' 2757 ].join('|'), 'g'), 2758 2759 // Match end of previous token to determine whether a slash is a division or regex. 2760 divisionLookBehind = /[\])"'A-Za-z0-9_$]+$/, 2761 keywordRegexLookBehind = { 'in': 1, 'return': 1, 'typeof': 1 }; 2762 2763 function parseObjectLiteral(objectLiteralString) { 2764 // Trim leading and trailing spaces from the string 2765 var str = ko.utils.stringTrim(objectLiteralString); 2766 2767 // Trim braces '{' surrounding the whole object literal 2768 if (str.charCodeAt(0) === 123) str = str.slice(1, -1); 2769 2770 // Add a newline to correctly match a C++ style comment at the end of the string and 2771 // add a comma so that we don't need a separate code block to deal with the last item 2772 str += "\n,"; 2773 2774 // Split into tokens 2775 var result = [], toks = str.match(bindingToken), key, values = [], depth = 0; 2776 2777 if (toks.length > 1) { 2778 for (var i = 0, tok; tok = toks[i]; ++i) { 2779 var c = tok.charCodeAt(0); 2780 // A comma signals the end of a key/value pair if depth is zero 2781 if (c === 44) { // "," 2782 if (depth <= 0) { 2783 result.push((key && values.length) ? { key: key, value: values.join('') } : { 'unknown': key || values.join('') }); 2784 key = depth = 0; 2785 values = []; 2786 continue; 2787 } 2788 // Simply skip the colon that separates the name and value 2789 } else if (c === 58) { // ":" 2790 if (!depth && !key && values.length === 1) { 2791 key = values.pop(); 2792 continue; 2793 } 2794 // Comments: skip them 2795 } else if (c === 47 && tok.length > 1 && (tok.charCodeAt(1) === 47 || tok.charCodeAt(1) === 42)) { // "//" or "/*" 2796 continue; 2797 // A set of slashes is initially matched as a regular expression, but could be division 2798 } else if (c === 47 && i && tok.length > 1) { // "/" 2799 // Look at the end of the previous token to determine if the slash is actually division 2800 var match = toks[i - 1].match(divisionLookBehind); 2801 if (match && !keywordRegexLookBehind[match[0]]) { 2802 // The slash is actually a division punctuator; re-parse the remainder of the string (not including the slash) 2803 str = str.substr(str.indexOf(tok) + 1); 2804 toks = str.match(bindingToken); 2805 i = -1; 2806 // Continue with just the slash 2807 tok = '/'; 2808 } 2809 // Increment depth for parentheses, braces, and brackets so that interior commas are ignored 2810 } else if (c === 40 || c === 123 || c === 91) { // '(', '{', '[' 2811 ++depth; 2812 } else if (c === 41 || c === 125 || c === 93) { // ')', '}', ']' 2813 --depth; 2814 // The key will be the first token; if it's a string, trim the quotes 2815 } else if (!key && !values.length && (c === 34 || c === 39)) { // '"', "'" 2816 tok = tok.slice(1, -1); 2817 } 2818 values.push(tok); 2819 } 2820 if (depth > 0) { 2821 throw Error("Unbalanced parentheses, braces, or brackets"); 2822 } 2823 } 2824 return result; 2825 } 2826 2827 // Two-way bindings include a write function that allow the handler to update the value even if it's not an observable. 2828 var twoWayBindings = {}; 2829 2830 function preProcessBindings(bindingsStringOrKeyValueArray, bindingOptions) { 2831 bindingOptions = bindingOptions || {}; 2832 2833 function processKeyValue(key, val) { 2834 var writableVal; 2835 function callPreprocessHook(obj) { 2836 return (obj && obj['preprocess']) ? (val = obj['preprocess'](val, key, processKeyValue)) : true; 2837 } 2838 if (!bindingParams) { 2839 if (!callPreprocessHook(ko['getBindingHandler'](key))) 2840 return; 2841 2842 if (twoWayBindings[key] && (writableVal = getWriteableValue(val))) { 2843 // For two-way bindings, provide a write method in case the value 2844 // isn't a writable observable. 2845 var writeKey = typeof twoWayBindings[key] == 'string' ? twoWayBindings[key] : key; 2846 propertyAccessorResultStrings.push("'" + writeKey + "':function(_z){" + writableVal + "=_z}"); 2847 } 2848 } 2849 // Values are wrapped in a function so that each value can be accessed independently 2850 if (makeValueAccessors) { 2851 val = 'function(){return ' + val + ' }'; 2852 } 2853 resultStrings.push("'" + key + "':" + val); 2854 } 2855 2856 var resultStrings = [], 2857 propertyAccessorResultStrings = [], 2858 makeValueAccessors = bindingOptions['valueAccessors'], 2859 bindingParams = bindingOptions['bindingParams'], 2860 keyValueArray = typeof bindingsStringOrKeyValueArray === "string" ? 2861 parseObjectLiteral(bindingsStringOrKeyValueArray) : bindingsStringOrKeyValueArray; 2862 2863 ko.utils.arrayForEach(keyValueArray, function (keyValue) { 2864 processKeyValue(keyValue.key || keyValue['unknown'], keyValue.value); 2865 }); 2866 2867 if (propertyAccessorResultStrings.length) 2868 processKeyValue('_ko_property_writers', "{" + propertyAccessorResultStrings.join(",") + " }"); 2869 2870 return resultStrings.join(","); 2871 } 2872 2873 return { 2874 bindingRewriteValidators: [], 2875 2876 twoWayBindings: twoWayBindings, 2877 2878 parseObjectLiteral: parseObjectLiteral, 2879 2880 preProcessBindings: preProcessBindings, 2881 2882 keyValueArrayContainsKey: function (keyValueArray, key) { 2883 for (var i = 0; i < keyValueArray.length; i++) 2884 if (keyValueArray[i]['key'] == key) 2885 return true; 2886 return false; 2887 }, 2888 2889 // Internal, private KO utility for updating model properties from within bindings 2890 // property: If the property being updated is (or might be) an observable, pass it here 2891 // If it turns out to be a writable observable, it will be written to directly 2892 // allBindings: An object with a get method to retrieve bindings in the current execution context. 2893 // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable 2894 // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus' 2895 // value: The value to be written 2896 // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if 2897 // it is !== existing value on that writable observable 2898 writeValueToProperty: function (property, allBindings, key, value, checkIfDifferent) { 2899 if (!property || !ko.isObservable(property)) { 2900 var propWriters = allBindings.get('_ko_property_writers'); 2901 if (propWriters && propWriters[key]) 2902 propWriters[key](value); 2903 } else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) { 2904 property(value); 2905 } 2906 } 2907 }; 2908 })(); 2909 2910 ko.exportSymbol('expressionRewriting', ko.expressionRewriting); 2911 ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators); 2912 ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral); 2913 ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings); 2914 2915 // Making bindings explicitly declare themselves as "two way" isn't ideal in the long term (it would be better if 2916 // all bindings could use an official 'property writer' API without needing to declare that they might). However, 2917 // since this is not, and has never been, a public API (_ko_property_writers was never documented), it's acceptable 2918 // as an internal implementation detail in the short term. 2919 // For those developers who rely on _ko_property_writers in their custom bindings, we expose _twoWayBindings as an 2920 // undocumented feature that makes it relatively easy to upgrade to KO 3.0. However, this is still not an official 2921 // public API, and we reserve the right to remove it at any time if we create a real public property writers API. 2922 ko.exportSymbol('expressionRewriting._twoWayBindings', ko.expressionRewriting.twoWayBindings); 2923 2924 // For backward compatibility, define the following aliases. (Previously, these function names were misleading because 2925 // they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.) 2926 ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting); 2927 ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings); 2928 (function () { 2929 // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes 2930 // may be used to represent hierarchy (in addition to the DOM's natural hierarchy). 2931 // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state 2932 // of that virtual hierarchy 2933 // 2934 // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->) 2935 // without having to scatter special cases all over the binding and templating code. 2936 2937 // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186) 2938 // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property. 2939 // So, use node.text where available, and node.nodeValue elsewhere 2940 var commentNodesHaveTextProperty = document && document.createComment("test").text === "<!--test-->"; 2941 2942 var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/; 2943 var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/; 2944 var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true }; 2945 2946 function isStartComment(node) { 2947 return (node.nodeType == 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue); 2948 } 2949 2950 function isEndComment(node) { 2951 return (node.nodeType == 8) && endCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue); 2952 } 2953 2954 function isUnmatchedEndComment(node) { 2955 return isEndComment(node) && !(ko.utils.domData.get(node, matchedEndCommentDataKey)); 2956 } 2957 2958 var matchedEndCommentDataKey = "__ko_matchedEndComment__" 2959 2960 function getVirtualChildren(startComment, allowUnbalanced) { 2961 var currentNode = startComment; 2962 var depth = 1; 2963 var children = []; 2964 while (currentNode = currentNode.nextSibling) { 2965 if (isEndComment(currentNode)) { 2966 ko.utils.domData.set(currentNode, matchedEndCommentDataKey, true); 2967 depth--; 2968 if (depth === 0) 2969 return children; 2970 } 2971 2972 children.push(currentNode); 2973 2974 if (isStartComment(currentNode)) 2975 depth++; 2976 } 2977 if (!allowUnbalanced) 2978 throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue); 2979 return null; 2980 } 2981 2982 function getMatchingEndComment(startComment, allowUnbalanced) { 2983 var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced); 2984 if (allVirtualChildren) { 2985 if (allVirtualChildren.length > 0) 2986 return allVirtualChildren[allVirtualChildren.length - 1].nextSibling; 2987 return startComment.nextSibling; 2988 } else 2989 return null; // Must have no matching end comment, and allowUnbalanced is true 2990 } 2991 2992 function getUnbalancedChildTags(node) { 2993 // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span> 2994 // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko --> 2995 var childNode = node.firstChild, captureRemaining = null; 2996 if (childNode) { 2997 do { 2998 if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes 2999 captureRemaining.push(childNode); 3000 else if (isStartComment(childNode)) { 3001 var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true); 3002 if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set 3003 childNode = matchingEndComment; 3004 else 3005 captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point 3006 } else if (isEndComment(childNode)) { 3007 captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing 3008 } 3009 } while (childNode = childNode.nextSibling); 3010 } 3011 return captureRemaining; 3012 } 3013 3014 ko.virtualElements = { 3015 allowedBindings: {}, 3016 3017 childNodes: function (node) { 3018 return isStartComment(node) ? getVirtualChildren(node) : node.childNodes; 3019 }, 3020 3021 emptyNode: function (node) { 3022 if (!isStartComment(node)) 3023 ko.utils.emptyDomNode(node); 3024 else { 3025 var virtualChildren = ko.virtualElements.childNodes(node); 3026 for (var i = 0, j = virtualChildren.length; i < j; i++) 3027 ko.removeNode(virtualChildren[i]); 3028 } 3029 }, 3030 3031 setDomNodeChildren: function (node, childNodes) { 3032 if (!isStartComment(node)) 3033 ko.utils.setDomNodeChildren(node, childNodes); 3034 else { 3035 ko.virtualElements.emptyNode(node); 3036 var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children 3037 for (var i = 0, j = childNodes.length; i < j; i++) 3038 endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode); 3039 } 3040 }, 3041 3042 prepend: function (containerNode, nodeToPrepend) { 3043 var insertBeforeNode; 3044 3045 if (isStartComment(containerNode)) { 3046 // Start comments must always have a parent and at least one following sibling (the end comment) 3047 insertBeforeNode = containerNode.nextSibling; 3048 containerNode = containerNode.parentNode; 3049 } else { 3050 insertBeforeNode = containerNode.firstChild; 3051 } 3052 3053 if (!insertBeforeNode) { 3054 containerNode.appendChild(nodeToPrepend); 3055 } else if (nodeToPrepend !== insertBeforeNode) { // IE will sometimes crash if you try to insert a node before itself 3056 containerNode.insertBefore(nodeToPrepend, insertBeforeNode); 3057 } 3058 }, 3059 3060 insertAfter: function (containerNode, nodeToInsert, insertAfterNode) { 3061 if (!insertAfterNode) { 3062 ko.virtualElements.prepend(containerNode, nodeToInsert); 3063 } else { 3064 // Children of start comments must always have a parent and at least one following sibling (the end comment) 3065 var insertBeforeNode = insertAfterNode.nextSibling; 3066 3067 if (isStartComment(containerNode)) { 3068 containerNode = containerNode.parentNode; 3069 } 3070 3071 if (!insertBeforeNode) { 3072 containerNode.appendChild(nodeToInsert); 3073 } else if (nodeToInsert !== insertBeforeNode) { // IE will sometimes crash if you try to insert a node before itself 3074 containerNode.insertBefore(nodeToInsert, insertBeforeNode); 3075 } 3076 } 3077 }, 3078 3079 firstChild: function (node) { 3080 if (!isStartComment(node)) { 3081 if (node.firstChild && isEndComment(node.firstChild)) { 3082 throw new Error("Found invalid end comment, as the first child of " + node); 3083 } 3084 return node.firstChild; 3085 } else if (!node.nextSibling || isEndComment(node.nextSibling)) { 3086 return null; 3087 } else { 3088 return node.nextSibling; 3089 } 3090 }, 3091 3092 nextSibling: function (node) { 3093 if (isStartComment(node)) { 3094 node = getMatchingEndComment(node); 3095 } 3096 3097 if (node.nextSibling && isEndComment(node.nextSibling)) { 3098 if (isUnmatchedEndComment(node.nextSibling)) { 3099 throw Error("Found end comment without a matching opening comment, as child of " + node); 3100 } else { 3101 return null; 3102 } 3103 } else { 3104 return node.nextSibling; 3105 } 3106 }, 3107 3108 hasBindingValue: isStartComment, 3109 3110 virtualNodeBindingValue: function (node) { 3111 var regexMatch = (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex); 3112 return regexMatch ? regexMatch[1] : null; 3113 }, 3114 3115 normaliseVirtualElementDomStructure: function (elementVerified) { 3116 // Workaround for https://github.com/SteveSanderson/knockout/issues/155 3117 // (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 3118 // that are direct descendants of <ul> into the preceding <li>) 3119 if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)]) 3120 return; 3121 3122 // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags 3123 // must be intended to appear *after* that child, so move them there. 3124 var childNode = elementVerified.firstChild; 3125 if (childNode) { 3126 do { 3127 if (childNode.nodeType === 1) { 3128 var unbalancedTags = getUnbalancedChildTags(childNode); 3129 if (unbalancedTags) { 3130 // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child 3131 var nodeToInsertBefore = childNode.nextSibling; 3132 for (var i = 0; i < unbalancedTags.length; i++) { 3133 if (nodeToInsertBefore) 3134 elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore); 3135 else 3136 elementVerified.appendChild(unbalancedTags[i]); 3137 } 3138 } 3139 } 3140 } while (childNode = childNode.nextSibling); 3141 } 3142 } 3143 }; 3144 })(); 3145 ko.exportSymbol('virtualElements', ko.virtualElements); 3146 ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings); 3147 ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode); 3148 //ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified 3149 ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter); 3150 //ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified 3151 ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend); 3152 ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren); 3153 (function () { 3154 var defaultBindingAttributeName = "data-bind"; 3155 3156 ko.bindingProvider = function () { 3157 this.bindingCache = {}; 3158 }; 3159 3160 ko.utils.extend(ko.bindingProvider.prototype, { 3161 'nodeHasBindings': function (node) { 3162 switch (node.nodeType) { 3163 case 1: // Element 3164 return node.getAttribute(defaultBindingAttributeName) != null 3165 || ko.components['getComponentNameForNode'](node); 3166 case 8: // Comment node 3167 return ko.virtualElements.hasBindingValue(node); 3168 default: return false; 3169 } 3170 }, 3171 3172 'getBindings': function (node, bindingContext) { 3173 var bindingsString = this['getBindingsString'](node, bindingContext), 3174 parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null; 3175 return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ false); 3176 }, 3177 3178 'getBindingAccessors': function (node, bindingContext) { 3179 var bindingsString = this['getBindingsString'](node, bindingContext), 3180 parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node, { 'valueAccessors': true }) : null; 3181 return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ true); 3182 }, 3183 3184 // The following function is only used internally by this default provider. 3185 // It's not part of the interface definition for a general binding provider. 3186 'getBindingsString': function (node, bindingContext) { 3187 switch (node.nodeType) { 3188 case 1: return node.getAttribute(defaultBindingAttributeName); // Element 3189 case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node 3190 default: return null; 3191 } 3192 }, 3193 3194 // The following function is only used internally by this default provider. 3195 // It's not part of the interface definition for a general binding provider. 3196 'parseBindingsString': function (bindingsString, bindingContext, node, options) { 3197 try { 3198 var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache, options); 3199 return bindingFunction(bindingContext, node); 3200 } catch (ex) { 3201 ex.message = "Unable to parse bindings.\nBindings value: " + bindingsString + "\nMessage: " + ex.message; 3202 throw ex; 3203 } 3204 } 3205 }); 3206 3207 ko.bindingProvider['instance'] = new ko.bindingProvider(); 3208 3209 function createBindingsStringEvaluatorViaCache(bindingsString, cache, options) { 3210 var cacheKey = bindingsString + (options && options['valueAccessors'] || ''); 3211 return cache[cacheKey] 3212 || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, options)); 3213 } 3214 3215 function createBindingsStringEvaluator(bindingsString, options) { 3216 // Build the source for a function that evaluates "expression" 3217 // For each scope variable, add an extra level of "with" nesting 3218 // Example result: with(sc1) { with(sc0) { return (expression) } } 3219 var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString, options), 3220 functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}"; 3221 return new Function("$context", "$element", functionBody); 3222 } 3223 })(); 3224 3225 ko.exportSymbol('bindingProvider', ko.bindingProvider); 3226 (function () { 3227 // Hide or don't minify context properties, see https://github.com/knockout/knockout/issues/2294 3228 var contextSubscribable = ko.utils.createSymbolOrString('_subscribable'); 3229 var contextAncestorBindingInfo = ko.utils.createSymbolOrString('_ancestorBindingInfo'); 3230 var contextDataDependency = ko.utils.createSymbolOrString('_dataDependency'); 3231 3232 ko.bindingHandlers = {}; 3233 3234 // The following element types will not be recursed into during binding. 3235 var bindingDoesNotRecurseIntoElementTypes = { 3236 // Don't want bindings that operate on text nodes to mutate <script> and <textarea> contents, 3237 // because it's unexpected and a potential XSS issue. 3238 // Also bindings should not operate on <template> elements since this breaks in Internet Explorer 3239 // and because such elements' contents are always intended to be bound in a different context 3240 // from where they appear in the document. 3241 'script': true, 3242 'textarea': true, 3243 'template': true 3244 }; 3245 3246 // Use an overridable method for retrieving binding handlers so that plugins may support dynamically created handlers 3247 ko['getBindingHandler'] = function (bindingKey) { 3248 return ko.bindingHandlers[bindingKey]; 3249 }; 3250 3251 var inheritParentVm = {}; 3252 3253 // The ko.bindingContext constructor is only called directly to create the root context. For child 3254 // contexts, use bindingContext.createChildContext or bindingContext.extend. 3255 ko.bindingContext = function (dataItemOrAccessor, parentContext, dataItemAlias, extendCallback, options) { 3256 3257 // The binding context object includes static properties for the current, parent, and root view models. 3258 // If a view model is actually stored in an observable, the corresponding binding context object, and 3259 // any child contexts, must be updated when the view model is changed. 3260 function updateContext() { 3261 // Most of the time, the context will directly get a view model object, but if a function is given, 3262 // we call the function to retrieve the view model. If the function accesses any observables or returns 3263 // an observable, the dependency is tracked, and those observables can later cause the binding 3264 // context to be updated. 3265 var dataItemOrObservable = isFunc ? realDataItemOrAccessor() : realDataItemOrAccessor, 3266 dataItem = ko.utils.unwrapObservable(dataItemOrObservable); 3267 3268 if (parentContext) { 3269 // Copy $root and any custom properties from the parent context 3270 ko.utils.extend(self, parentContext); 3271 3272 // Copy Symbol properties 3273 if (contextAncestorBindingInfo in parentContext) { 3274 self[contextAncestorBindingInfo] = parentContext[contextAncestorBindingInfo]; 3275 } 3276 } else { 3277 self['$parents'] = []; 3278 self['$root'] = dataItem; 3279 3280 // Export 'ko' in the binding context so it will be available in bindings and templates 3281 // even if 'ko' isn't exported as a global, such as when using an AMD loader. 3282 // See https://github.com/SteveSanderson/knockout/issues/490 3283 self['ko'] = ko; 3284 } 3285 3286 self[contextSubscribable] = subscribable; 3287 3288 if (shouldInheritData) { 3289 dataItem = self['$data']; 3290 } else { 3291 self['$rawData'] = dataItemOrObservable; 3292 self['$data'] = dataItem; 3293 } 3294 3295 if (dataItemAlias) 3296 self[dataItemAlias] = dataItem; 3297 3298 // The extendCallback function is provided when creating a child context or extending a context. 3299 // It handles the specific actions needed to finish setting up the binding context. Actions in this 3300 // function could also add dependencies to this binding context. 3301 if (extendCallback) 3302 extendCallback(self, parentContext, dataItem); 3303 3304 // When a "parent" context is given and we don't already have a dependency on its context, register a dependency on it. 3305 // Thus whenever the parent context is updated, this context will also be updated. 3306 if (parentContext && parentContext[contextSubscribable] && !ko.computedContext.computed().hasAncestorDependency(parentContext[contextSubscribable])) { 3307 parentContext[contextSubscribable](); 3308 } 3309 3310 if (dataDependency) { 3311 self[contextDataDependency] = dataDependency; 3312 } 3313 3314 return self['$data']; 3315 } 3316 3317 var self = this, 3318 shouldInheritData = dataItemOrAccessor === inheritParentVm, 3319 realDataItemOrAccessor = shouldInheritData ? undefined : dataItemOrAccessor, 3320 isFunc = typeof (realDataItemOrAccessor) == "function" && !ko.isObservable(realDataItemOrAccessor), 3321 nodes, 3322 subscribable, 3323 dataDependency = options && options['dataDependency']; 3324 3325 if (options && options['exportDependencies']) { 3326 // The "exportDependencies" option means that the calling code will track any dependencies and re-create 3327 // the binding context when they change. 3328 updateContext(); 3329 } else { 3330 subscribable = ko.pureComputed(updateContext); 3331 subscribable.peek(); 3332 3333 // At this point, the binding context has been initialized, and the "subscribable" computed observable is 3334 // subscribed to any observables that were accessed in the process. If there is nothing to track, the 3335 // computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in 3336 // the context object. 3337 if (subscribable.isActive()) { 3338 // Always notify because even if the model ($data) hasn't changed, other context properties might have changed 3339 subscribable['equalityComparer'] = null; 3340 } else { 3341 self[contextSubscribable] = undefined; 3342 } 3343 } 3344 } 3345 3346 // Extend the binding context hierarchy with a new view model object. If the parent context is watching 3347 // any observables, the new child context will automatically get a dependency on the parent context. 3348 // But this does not mean that the $data value of the child context will also get updated. If the child 3349 // view model also depends on the parent view model, you must provide a function that returns the correct 3350 // view model on each update. 3351 ko.bindingContext.prototype['createChildContext'] = function (dataItemOrAccessor, dataItemAlias, extendCallback, options) { 3352 if (!options && dataItemAlias && typeof dataItemAlias == "object") { 3353 options = dataItemAlias; 3354 dataItemAlias = options['as']; 3355 extendCallback = options['extend']; 3356 } 3357 3358 if (dataItemAlias && options && options['noChildContext']) { 3359 var isFunc = typeof (dataItemOrAccessor) == "function" && !ko.isObservable(dataItemOrAccessor); 3360 return new ko.bindingContext(inheritParentVm, this, null, function (self) { 3361 if (extendCallback) 3362 extendCallback(self); 3363 self[dataItemAlias] = isFunc ? dataItemOrAccessor() : dataItemOrAccessor; 3364 }, options); 3365 } 3366 3367 return new ko.bindingContext(dataItemOrAccessor, this, dataItemAlias, function (self, parentContext) { 3368 // Extend the context hierarchy by setting the appropriate pointers 3369 self['$parentContext'] = parentContext; 3370 self['$parent'] = parentContext['$data']; 3371 self['$parents'] = (parentContext['$parents'] || []).slice(0); 3372 self['$parents'].unshift(self['$parent']); 3373 if (extendCallback) 3374 extendCallback(self); 3375 }, options); 3376 }; 3377 3378 // Extend the binding context with new custom properties. This doesn't change the context hierarchy. 3379 // Similarly to "child" contexts, provide a function here to make sure that the correct values are set 3380 // when an observable view model is updated. 3381 ko.bindingContext.prototype['extend'] = function (properties, options) { 3382 return new ko.bindingContext(inheritParentVm, this, null, function (self, parentContext) { 3383 ko.utils.extend(self, typeof (properties) == "function" ? properties(self) : properties); 3384 }, options); 3385 }; 3386 3387 var boundElementDomDataKey = ko.utils.domData.nextKey(); 3388 3389 function asyncContextDispose(node) { 3390 var bindingInfo = ko.utils.domData.get(node, boundElementDomDataKey), 3391 asyncContext = bindingInfo && bindingInfo.asyncContext; 3392 if (asyncContext) { 3393 bindingInfo.asyncContext = null; 3394 asyncContext.notifyAncestor(); 3395 } 3396 } 3397 function AsyncCompleteContext(node, bindingInfo, ancestorBindingInfo) { 3398 this.node = node; 3399 this.bindingInfo = bindingInfo; 3400 this.asyncDescendants = []; 3401 this.childrenComplete = false; 3402 3403 if (!bindingInfo.asyncContext) { 3404 ko.utils.domNodeDisposal.addDisposeCallback(node, asyncContextDispose); 3405 } 3406 3407 if (ancestorBindingInfo && ancestorBindingInfo.asyncContext) { 3408 ancestorBindingInfo.asyncContext.asyncDescendants.push(node); 3409 this.ancestorBindingInfo = ancestorBindingInfo; 3410 } 3411 } 3412 AsyncCompleteContext.prototype.notifyAncestor = function () { 3413 if (this.ancestorBindingInfo && this.ancestorBindingInfo.asyncContext) { 3414 this.ancestorBindingInfo.asyncContext.descendantComplete(this.node); 3415 } 3416 }; 3417 AsyncCompleteContext.prototype.descendantComplete = function (node) { 3418 ko.utils.arrayRemoveItem(this.asyncDescendants, node); 3419 if (!this.asyncDescendants.length && this.childrenComplete) { 3420 this.completeChildren(); 3421 } 3422 }; 3423 AsyncCompleteContext.prototype.completeChildren = function () { 3424 this.childrenComplete = true; 3425 if (this.bindingInfo.asyncContext && !this.asyncDescendants.length) { 3426 this.bindingInfo.asyncContext = null; 3427 ko.utils.domNodeDisposal.removeDisposeCallback(this.node, asyncContextDispose); 3428 ko.bindingEvent.notify(this.node, ko.bindingEvent.descendantsComplete); 3429 this.notifyAncestor(); 3430 } 3431 }; 3432 3433 ko.bindingEvent = { 3434 childrenComplete: "childrenComplete", 3435 descendantsComplete: "descendantsComplete", 3436 3437 subscribe: function (node, event, callback, context, options) { 3438 var bindingInfo = ko.utils.domData.getOrSet(node, boundElementDomDataKey, {}); 3439 if (!bindingInfo.eventSubscribable) { 3440 bindingInfo.eventSubscribable = new ko.subscribable; 3441 } 3442 if (options && options['notifyImmediately'] && bindingInfo.notifiedEvents[event]) { 3443 ko.dependencyDetection.ignore(callback, context, [node]); 3444 } 3445 return bindingInfo.eventSubscribable.subscribe(callback, context, event); 3446 }, 3447 3448 notify: function (node, event) { 3449 var bindingInfo = ko.utils.domData.get(node, boundElementDomDataKey); 3450 if (bindingInfo) { 3451 bindingInfo.notifiedEvents[event] = true; 3452 if (bindingInfo.eventSubscribable) { 3453 bindingInfo.eventSubscribable['notifySubscribers'](node, event); 3454 } 3455 if (event == ko.bindingEvent.childrenComplete) { 3456 if (bindingInfo.asyncContext) { 3457 bindingInfo.asyncContext.completeChildren(); 3458 } else if (bindingInfo.asyncContext === undefined && bindingInfo.eventSubscribable && bindingInfo.eventSubscribable.hasSubscriptionsForEvent(ko.bindingEvent.descendantsComplete)) { 3459 // It's currently an error to register a descendantsComplete handler for a node that was never registered as completing asynchronously. 3460 // That's because without the asyncContext, we don't have a way to know that all descendants have completed. 3461 throw new Error("descendantsComplete event not supported for bindings on this node"); 3462 } 3463 } 3464 } 3465 }, 3466 3467 startPossiblyAsyncContentBinding: function (node, bindingContext) { 3468 var bindingInfo = ko.utils.domData.getOrSet(node, boundElementDomDataKey, {}); 3469 3470 if (!bindingInfo.asyncContext) { 3471 bindingInfo.asyncContext = new AsyncCompleteContext(node, bindingInfo, bindingContext[contextAncestorBindingInfo]); 3472 } 3473 3474 // If the provided context was already extended with this node's binding info, just return the extended context 3475 if (bindingContext[contextAncestorBindingInfo] == bindingInfo) { 3476 return bindingContext; 3477 } 3478 3479 return bindingContext['extend'](function (ctx) { 3480 ctx[contextAncestorBindingInfo] = bindingInfo; 3481 }); 3482 } 3483 }; 3484 3485 // Returns the valueAccessor function for a binding value 3486 function makeValueAccessor(value) { 3487 return function () { 3488 return value; 3489 }; 3490 } 3491 3492 // Returns the value of a valueAccessor function 3493 function evaluateValueAccessor(valueAccessor) { 3494 return valueAccessor(); 3495 } 3496 3497 // Given a function that returns bindings, create and return a new object that contains 3498 // binding value-accessors functions. Each accessor function calls the original function 3499 // so that it always gets the latest value and all dependencies are captured. This is used 3500 // by ko.applyBindingsToNode and getBindingsAndMakeAccessors. 3501 function makeAccessorsFromFunction(callback) { 3502 return ko.utils.objectMap(ko.dependencyDetection.ignore(callback), function (value, key) { 3503 return function () { 3504 return callback()[key]; 3505 }; 3506 }); 3507 } 3508 3509 // Given a bindings function or object, create and return a new object that contains 3510 // binding value-accessors functions. This is used by ko.applyBindingsToNode. 3511 function makeBindingAccessors(bindings, context, node) { 3512 if (typeof bindings === 'function') { 3513 return makeAccessorsFromFunction(bindings.bind(null, context, node)); 3514 } else { 3515 return ko.utils.objectMap(bindings, makeValueAccessor); 3516 } 3517 } 3518 3519 // This function is used if the binding provider doesn't include a getBindingAccessors function. 3520 // It must be called with 'this' set to the provider instance. 3521 function getBindingsAndMakeAccessors(node, context) { 3522 return makeAccessorsFromFunction(this['getBindings'].bind(this, node, context)); 3523 } 3524 3525 function validateThatBindingIsAllowedForVirtualElements(bindingName) { 3526 var validator = ko.virtualElements.allowedBindings[bindingName]; 3527 if (!validator) 3528 throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements") 3529 } 3530 3531 function applyBindingsToDescendantsInternal(bindingContext, elementOrVirtualElement) { 3532 var nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement); 3533 3534 if (nextInQueue) { 3535 var currentChild, 3536 provider = ko.bindingProvider['instance'], 3537 preprocessNode = provider['preprocessNode']; 3538 3539 // Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's 3540 // possible to insert new siblings after it, and/or replace the node with a different one. This can be used to 3541 // implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that 3542 // trigger insertion of <template> contents at that point in the document. 3543 if (preprocessNode) { 3544 while (currentChild = nextInQueue) { 3545 nextInQueue = ko.virtualElements.nextSibling(currentChild); 3546 preprocessNode.call(provider, currentChild); 3547 } 3548 // Reset nextInQueue for the next loop 3549 nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement); 3550 } 3551 3552 while (currentChild = nextInQueue) { 3553 // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position 3554 nextInQueue = ko.virtualElements.nextSibling(currentChild); 3555 applyBindingsToNodeAndDescendantsInternal(bindingContext, currentChild); 3556 } 3557 } 3558 ko.bindingEvent.notify(elementOrVirtualElement, ko.bindingEvent.childrenComplete); 3559 } 3560 3561 function applyBindingsToNodeAndDescendantsInternal(bindingContext, nodeVerified) { 3562 var bindingContextForDescendants = bindingContext; 3563 3564 var isElement = (nodeVerified.nodeType === 1); 3565 if (isElement) // Workaround IE <= 8 HTML parsing weirdness 3566 ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified); 3567 3568 // Perf optimisation: Apply bindings only if... 3569 // (1) We need to store the binding info for the node (all element nodes) 3570 // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template) 3571 var shouldApplyBindings = isElement || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); 3572 if (shouldApplyBindings) 3573 bindingContextForDescendants = applyBindingsToNodeInternal(nodeVerified, null, bindingContext)['bindingContextForDescendants']; 3574 3575 if (bindingContextForDescendants && !bindingDoesNotRecurseIntoElementTypes[ko.utils.tagNameLower(nodeVerified)]) { 3576 applyBindingsToDescendantsInternal(bindingContextForDescendants, nodeVerified); 3577 } 3578 } 3579 3580 function topologicalSortBindings(bindings) { 3581 // Depth-first sort 3582 var result = [], // The list of key/handler pairs that we will return 3583 bindingsConsidered = {}, // A temporary record of which bindings are already in 'result' 3584 cyclicDependencyStack = []; // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it 3585 ko.utils.objectForEach(bindings, function pushBinding(bindingKey) { 3586 if (!bindingsConsidered[bindingKey]) { 3587 var binding = ko['getBindingHandler'](bindingKey); 3588 if (binding) { 3589 // First add dependencies (if any) of the current binding 3590 if (binding['after']) { 3591 cyclicDependencyStack.push(bindingKey); 3592 ko.utils.arrayForEach(binding['after'], function (bindingDependencyKey) { 3593 if (bindings[bindingDependencyKey]) { 3594 if (ko.utils.arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) { 3595 throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + cyclicDependencyStack.join(", ")); 3596 } else { 3597 pushBinding(bindingDependencyKey); 3598 } 3599 } 3600 }); 3601 cyclicDependencyStack.length--; 3602 } 3603 // Next add the current binding 3604 result.push({ key: bindingKey, handler: binding }); 3605 } 3606 bindingsConsidered[bindingKey] = true; 3607 } 3608 }); 3609 3610 return result; 3611 } 3612 3613 function applyBindingsToNodeInternal(node, sourceBindings, bindingContext) { 3614 var bindingInfo = ko.utils.domData.getOrSet(node, boundElementDomDataKey, {}); 3615 3616 // Prevent multiple applyBindings calls for the same node, except when a binding value is specified 3617 var alreadyBound = bindingInfo.alreadyBound; 3618 if (!sourceBindings) { 3619 if (alreadyBound) { 3620 throw Error("You cannot apply bindings multiple times to the same element."); 3621 } 3622 bindingInfo.alreadyBound = true; 3623 } 3624 if (!alreadyBound) { 3625 bindingInfo.context = bindingContext; 3626 } 3627 if (!bindingInfo.notifiedEvents) { 3628 bindingInfo.notifiedEvents = {}; 3629 } 3630 3631 // Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings 3632 var bindings; 3633 if (sourceBindings && typeof sourceBindings !== 'function') { 3634 bindings = sourceBindings; 3635 } else { 3636 var provider = ko.bindingProvider['instance'], 3637 getBindings = provider['getBindingAccessors'] || getBindingsAndMakeAccessors; 3638 3639 // Get the binding from the provider within a computed observable so that we can update the bindings whenever 3640 // the binding context is updated or if the binding provider accesses observables. 3641 var bindingsUpdater = ko.dependentObservable( 3642 function () { 3643 bindings = sourceBindings ? sourceBindings(bindingContext, node) : getBindings.call(provider, node, bindingContext); 3644 // Register a dependency on the binding context to support observable view models. 3645 if (bindings) { 3646 if (bindingContext[contextSubscribable]) { 3647 bindingContext[contextSubscribable](); 3648 } 3649 if (bindingContext[contextDataDependency]) { 3650 bindingContext[contextDataDependency](); 3651 } 3652 } 3653 return bindings; 3654 }, 3655 null, { disposeWhenNodeIsRemoved: node } 3656 ); 3657 3658 if (!bindings || !bindingsUpdater.isActive()) 3659 bindingsUpdater = null; 3660 } 3661 3662 var contextToExtend = bindingContext; 3663 var bindingHandlerThatControlsDescendantBindings; 3664 if (bindings) { 3665 // Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding 3666 // context update), just return the value accessor from the binding. Otherwise, return a function that always gets 3667 // the latest binding value and registers a dependency on the binding updater. 3668 var getValueAccessor = bindingsUpdater 3669 ? function (bindingKey) { 3670 return function () { 3671 return evaluateValueAccessor(bindingsUpdater()[bindingKey]); 3672 }; 3673 } : function (bindingKey) { 3674 return bindings[bindingKey]; 3675 }; 3676 3677 // Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated 3678 function allBindings() { 3679 return ko.utils.objectMap(bindingsUpdater ? bindingsUpdater() : bindings, evaluateValueAccessor); 3680 } 3681 // The following is the 3.x allBindings API 3682 allBindings['get'] = function (key) { 3683 return bindings[key] && evaluateValueAccessor(getValueAccessor(key)); 3684 }; 3685 allBindings['has'] = function (key) { 3686 return key in bindings; 3687 }; 3688 3689 if (ko.bindingEvent.childrenComplete in bindings) { 3690 ko.bindingEvent.subscribe(node, ko.bindingEvent.childrenComplete, function () { 3691 var callback = evaluateValueAccessor(bindings[ko.bindingEvent.childrenComplete]); 3692 if (callback) { 3693 var nodes = ko.virtualElements.childNodes(node); 3694 if (nodes.length) { 3695 callback(nodes, ko.dataFor(nodes[0])); 3696 } 3697 } 3698 }); 3699 } 3700 3701 if (ko.bindingEvent.descendantsComplete in bindings) { 3702 contextToExtend = ko.bindingEvent.startPossiblyAsyncContentBinding(node, bindingContext); 3703 ko.bindingEvent.subscribe(node, ko.bindingEvent.descendantsComplete, function () { 3704 var callback = evaluateValueAccessor(bindings[ko.bindingEvent.descendantsComplete]); 3705 if (callback && ko.virtualElements.firstChild(node)) { 3706 callback(node); 3707 } 3708 }); 3709 } 3710 3711 // First put the bindings into the right order 3712 var orderedBindings = topologicalSortBindings(bindings); 3713 3714 // Go through the sorted bindings, calling init and update for each 3715 ko.utils.arrayForEach(orderedBindings, function (bindingKeyAndHandler) { 3716 // Note that topologicalSortBindings has already filtered out any nonexistent binding handlers, 3717 // so bindingKeyAndHandler.handler will always be nonnull. 3718 var handlerInitFn = bindingKeyAndHandler.handler["init"], 3719 handlerUpdateFn = bindingKeyAndHandler.handler["update"], 3720 bindingKey = bindingKeyAndHandler.key; 3721 3722 if (node.nodeType === 8) { 3723 validateThatBindingIsAllowedForVirtualElements(bindingKey); 3724 } 3725 3726 try { 3727 // Run init, ignoring any dependencies 3728 if (typeof handlerInitFn == "function") { 3729 ko.dependencyDetection.ignore(function () { 3730 var initResult = handlerInitFn(node, getValueAccessor(bindingKey), allBindings, contextToExtend['$data'], contextToExtend); 3731 3732 // If this binding handler claims to control descendant bindings, make a note of this 3733 if (initResult && initResult['controlsDescendantBindings']) { 3734 if (bindingHandlerThatControlsDescendantBindings !== undefined) 3735 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."); 3736 bindingHandlerThatControlsDescendantBindings = bindingKey; 3737 } 3738 }); 3739 } 3740 3741 // Run update in its own computed wrapper 3742 if (typeof handlerUpdateFn == "function") { 3743 ko.dependentObservable( 3744 function () { 3745 handlerUpdateFn(node, getValueAccessor(bindingKey), allBindings, contextToExtend['$data'], contextToExtend); 3746 }, 3747 null, 3748 { disposeWhenNodeIsRemoved: node } 3749 ); 3750 } 3751 } catch (ex) { 3752 ex.message = "Unable to process binding \"" + bindingKey + ": " + bindings[bindingKey] + "\"\nMessage: " + ex.message; 3753 throw ex; 3754 } 3755 }); 3756 } 3757 3758 var shouldBindDescendants = bindingHandlerThatControlsDescendantBindings === undefined; 3759 return { 3760 'shouldBindDescendants': shouldBindDescendants, 3761 'bindingContextForDescendants': shouldBindDescendants && contextToExtend 3762 }; 3763 }; 3764 3765 ko.storedBindingContextForNode = function (node) { 3766 var bindingInfo = ko.utils.domData.get(node, boundElementDomDataKey); 3767 return bindingInfo && bindingInfo.context; 3768 } 3769 3770 function getBindingContext(viewModelOrBindingContext, extendContextCallback) { 3771 return viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext) 3772 ? viewModelOrBindingContext 3773 : new ko.bindingContext(viewModelOrBindingContext, undefined, undefined, extendContextCallback); 3774 } 3775 3776 ko.applyBindingAccessorsToNode = function (node, bindings, viewModelOrBindingContext) { 3777 if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness 3778 ko.virtualElements.normaliseVirtualElementDomStructure(node); 3779 return applyBindingsToNodeInternal(node, bindings, getBindingContext(viewModelOrBindingContext)); 3780 }; 3781 3782 ko.applyBindingsToNode = function (node, bindings, viewModelOrBindingContext) { 3783 var context = getBindingContext(viewModelOrBindingContext); 3784 return ko.applyBindingAccessorsToNode(node, makeBindingAccessors(bindings, context, node), context); 3785 }; 3786 3787 ko.applyBindingsToDescendants = function (viewModelOrBindingContext, rootNode) { 3788 if (rootNode.nodeType === 1 || rootNode.nodeType === 8) 3789 applyBindingsToDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode); 3790 }; 3791 3792 ko.applyBindings = function (viewModelOrBindingContext, rootNode, extendContextCallback) { 3793 // If jQuery is loaded after Knockout, we won't initially have access to it. So save it here. 3794 if (!jQueryInstance && window['jQuery']) { 3795 jQueryInstance = window['jQuery']; 3796 } 3797 3798 if (arguments.length < 2) { 3799 rootNode = document.body; 3800 if (!rootNode) { 3801 throw Error("ko.applyBindings: could not find document.body; has the document been loaded?"); 3802 } 3803 } else if (!rootNode || (rootNode.nodeType !== 1 && rootNode.nodeType !== 8)) { 3804 throw Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node"); 3805 } 3806 3807 applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext, extendContextCallback), rootNode); 3808 }; 3809 3810 // Retrieving binding context from arbitrary nodes 3811 ko.contextFor = function (node) { 3812 // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them) 3813 if (node && (node.nodeType === 1 || node.nodeType === 8)) { 3814 return ko.storedBindingContextForNode(node); 3815 } 3816 return undefined; 3817 }; 3818 ko.dataFor = function (node) { 3819 var context = ko.contextFor(node); 3820 return context ? context['$data'] : undefined; 3821 }; 3822 3823 ko.exportSymbol('bindingHandlers', ko.bindingHandlers); 3824 ko.exportSymbol('bindingEvent', ko.bindingEvent); 3825 ko.exportSymbol('bindingEvent.subscribe', ko.bindingEvent.subscribe); 3826 ko.exportSymbol('bindingEvent.startPossiblyAsyncContentBinding', ko.bindingEvent.startPossiblyAsyncContentBinding); 3827 ko.exportSymbol('applyBindings', ko.applyBindings); 3828 ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants); 3829 ko.exportSymbol('applyBindingAccessorsToNode', ko.applyBindingAccessorsToNode); 3830 ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode); 3831 ko.exportSymbol('contextFor', ko.contextFor); 3832 ko.exportSymbol('dataFor', ko.dataFor); 3833 })(); 3834 (function (undefined) { 3835 var loadingSubscribablesCache = {}, // Tracks component loads that are currently in flight 3836 loadedDefinitionsCache = {}; // Tracks component loads that have already completed 3837 3838 ko.components = { 3839 get: function (componentName, callback) { 3840 var cachedDefinition = getObjectOwnProperty(loadedDefinitionsCache, componentName); 3841 if (cachedDefinition) { 3842 // It's already loaded and cached. Reuse the same definition object. 3843 // Note that for API consistency, even cache hits complete asynchronously by default. 3844 // You can bypass this by putting synchronous:true on your component config. 3845 if (cachedDefinition.isSynchronousComponent) { 3846 ko.dependencyDetection.ignore(function () { // See comment in loaderRegistryBehaviors.js for reasoning 3847 callback(cachedDefinition.definition); 3848 }); 3849 } else { 3850 ko.tasks.schedule(function () { callback(cachedDefinition.definition); }); 3851 } 3852 } else { 3853 // Join the loading process that is already underway, or start a new one. 3854 loadComponentAndNotify(componentName, callback); 3855 } 3856 }, 3857 3858 clearCachedDefinition: function (componentName) { 3859 delete loadedDefinitionsCache[componentName]; 3860 }, 3861 3862 _getFirstResultFromLoaders: getFirstResultFromLoaders 3863 }; 3864 3865 function getObjectOwnProperty(obj, propName) { 3866 return Object.prototype.hasOwnProperty.call(obj, propName) ? obj[propName] : undefined; 3867 } 3868 3869 function loadComponentAndNotify(componentName, callback) { 3870 var subscribable = getObjectOwnProperty(loadingSubscribablesCache, componentName), 3871 completedAsync; 3872 if (!subscribable) { 3873 // It's not started loading yet. Start loading, and when it's done, move it to loadedDefinitionsCache. 3874 subscribable = loadingSubscribablesCache[componentName] = new ko.subscribable(); 3875 subscribable.subscribe(callback); 3876 3877 beginLoadingComponent(componentName, function (definition, config) { 3878 var isSynchronousComponent = !!(config && config['synchronous']); 3879 loadedDefinitionsCache[componentName] = { definition: definition, isSynchronousComponent: isSynchronousComponent }; 3880 delete loadingSubscribablesCache[componentName]; 3881 3882 // For API consistency, all loads complete asynchronously. However we want to avoid 3883 // adding an extra task schedule if it's unnecessary (i.e., the completion is already 3884 // async). 3885 // 3886 // You can bypass the 'always asynchronous' feature by putting the synchronous:true 3887 // flag on your component configuration when you register it. 3888 if (completedAsync || isSynchronousComponent) { 3889 // Note that notifySubscribers ignores any dependencies read within the callback. 3890 // See comment in loaderRegistryBehaviors.js for reasoning 3891 subscribable['notifySubscribers'](definition); 3892 } else { 3893 ko.tasks.schedule(function () { 3894 subscribable['notifySubscribers'](definition); 3895 }); 3896 } 3897 }); 3898 completedAsync = true; 3899 } else { 3900 subscribable.subscribe(callback); 3901 } 3902 } 3903 3904 function beginLoadingComponent(componentName, callback) { 3905 getFirstResultFromLoaders('getConfig', [componentName], function (config) { 3906 if (config) { 3907 // We have a config, so now load its definition 3908 getFirstResultFromLoaders('loadComponent', [componentName, config], function (definition) { 3909 callback(definition, config); 3910 }); 3911 } else { 3912 // The component has no config - it's unknown to all the loaders. 3913 // Note that this is not an error (e.g., a module loading error) - that would abort the 3914 // process and this callback would not run. For this callback to run, all loaders must 3915 // have confirmed they don't know about this component. 3916 callback(null, null); 3917 } 3918 }); 3919 } 3920 3921 function getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders) { 3922 // On the first call in the stack, start with the full set of loaders 3923 if (!candidateLoaders) { 3924 candidateLoaders = ko.components['loaders'].slice(0); // Use a copy, because we'll be mutating this array 3925 } 3926 3927 // Try the next candidate 3928 var currentCandidateLoader = candidateLoaders.shift(); 3929 if (currentCandidateLoader) { 3930 var methodInstance = currentCandidateLoader[methodName]; 3931 if (methodInstance) { 3932 var wasAborted = false, 3933 synchronousReturnValue = methodInstance.apply(currentCandidateLoader, argsExceptCallback.concat(function (result) { 3934 if (wasAborted) { 3935 callback(null); 3936 } else if (result !== null) { 3937 // This candidate returned a value. Use it. 3938 callback(result); 3939 } else { 3940 // Try the next candidate 3941 getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders); 3942 } 3943 })); 3944 3945 // Currently, loaders may not return anything synchronously. This leaves open the possibility 3946 // that we'll extend the API to support synchronous return values in the future. It won't be 3947 // a breaking change, because currently no loader is allowed to return anything except undefined. 3948 if (synchronousReturnValue !== undefined) { 3949 wasAborted = true; 3950 3951 // Method to suppress exceptions will remain undocumented. This is only to keep 3952 // KO's specs running tidily, since we can observe the loading got aborted without 3953 // having exceptions cluttering up the console too. 3954 if (!currentCandidateLoader['suppressLoaderExceptions']) { 3955 throw new Error('Component loaders must supply values by invoking the callback, not by returning values synchronously.'); 3956 } 3957 } 3958 } else { 3959 // This candidate doesn't have the relevant handler. Synchronously move on to the next one. 3960 getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders); 3961 } 3962 } else { 3963 // No candidates returned a value 3964 callback(null); 3965 } 3966 } 3967 3968 // Reference the loaders via string name so it's possible for developers 3969 // to replace the whole array by assigning to ko.components.loaders 3970 ko.components['loaders'] = []; 3971 3972 ko.exportSymbol('components', ko.components); 3973 ko.exportSymbol('components.get', ko.components.get); 3974 ko.exportSymbol('components.clearCachedDefinition', ko.components.clearCachedDefinition); 3975 })(); 3976 (function (undefined) { 3977 3978 // The default loader is responsible for two things: 3979 // 1. Maintaining the default in-memory registry of component configuration objects 3980 // (i.e., the thing you're writing to when you call ko.components.register(someName, ...)) 3981 // 2. Answering requests for components by fetching configuration objects 3982 // from that default in-memory registry and resolving them into standard 3983 // component definition objects (of the form { createViewModel: ..., template: ... }) 3984 // Custom loaders may override either of these facilities, i.e., 3985 // 1. To supply configuration objects from some other source (e.g., conventions) 3986 // 2. Or, to resolve configuration objects by loading viewmodels/templates via arbitrary logic. 3987 3988 var defaultConfigRegistry = {}; 3989 3990 ko.components.register = function (componentName, config) { 3991 if (!config) { 3992 throw new Error('Invalid configuration for ' + componentName); 3993 } 3994 3995 if (ko.components.isRegistered(componentName)) { 3996 throw new Error('Component ' + componentName + ' is already registered'); 3997 } 3998 3999 defaultConfigRegistry[componentName] = config; 4000 }; 4001 4002 ko.components.isRegistered = function (componentName) { 4003 return Object.prototype.hasOwnProperty.call(defaultConfigRegistry, componentName); 4004 }; 4005 4006 ko.components.unregister = function (componentName) { 4007 delete defaultConfigRegistry[componentName]; 4008 ko.components.clearCachedDefinition(componentName); 4009 }; 4010 4011 ko.components.defaultLoader = { 4012 'getConfig': function (componentName, callback) { 4013 var result = ko.components.isRegistered(componentName) 4014 ? defaultConfigRegistry[componentName] 4015 : null; 4016 callback(result); 4017 }, 4018 4019 'loadComponent': function (componentName, config, callback) { 4020 var errorCallback = makeErrorCallback(componentName); 4021 possiblyGetConfigFromAmd(errorCallback, config, function (loadedConfig) { 4022 resolveConfig(componentName, errorCallback, loadedConfig, callback); 4023 }); 4024 }, 4025 4026 'loadTemplate': function (componentName, templateConfig, callback) { 4027 resolveTemplate(makeErrorCallback(componentName), templateConfig, callback); 4028 }, 4029 4030 'loadViewModel': function (componentName, viewModelConfig, callback) { 4031 resolveViewModel(makeErrorCallback(componentName), viewModelConfig, callback); 4032 } 4033 }; 4034 4035 var createViewModelKey = 'createViewModel'; 4036 4037 // Takes a config object of the form { template: ..., viewModel: ... }, and asynchronously convert it 4038 // into the standard component definition format: 4039 // { template: <ArrayOfDomNodes>, createViewModel: function(params, componentInfo) { ... } }. 4040 // Since both template and viewModel may need to be resolved asynchronously, both tasks are performed 4041 // in parallel, and the results joined when both are ready. We don't depend on any promises infrastructure, 4042 // so this is implemented manually below. 4043 function resolveConfig(componentName, errorCallback, config, callback) { 4044 var result = {}, 4045 makeCallBackWhenZero = 2, 4046 tryIssueCallback = function () { 4047 if (--makeCallBackWhenZero === 0) { 4048 callback(result); 4049 } 4050 }, 4051 templateConfig = config['template'], 4052 viewModelConfig = config['viewModel']; 4053 4054 if (templateConfig) { 4055 possiblyGetConfigFromAmd(errorCallback, templateConfig, function (loadedConfig) { 4056 ko.components._getFirstResultFromLoaders('loadTemplate', [componentName, loadedConfig], function (resolvedTemplate) { 4057 result['template'] = resolvedTemplate; 4058 tryIssueCallback(); 4059 }); 4060 }); 4061 } else { 4062 tryIssueCallback(); 4063 } 4064 4065 if (viewModelConfig) { 4066 possiblyGetConfigFromAmd(errorCallback, viewModelConfig, function (loadedConfig) { 4067 ko.components._getFirstResultFromLoaders('loadViewModel', [componentName, loadedConfig], function (resolvedViewModel) { 4068 result[createViewModelKey] = resolvedViewModel; 4069 tryIssueCallback(); 4070 }); 4071 }); 4072 } else { 4073 tryIssueCallback(); 4074 } 4075 } 4076 4077 function resolveTemplate(errorCallback, templateConfig, callback) { 4078 if (typeof templateConfig === 'string') { 4079 // Markup - parse it 4080 callback(ko.utils.parseHtmlFragment(templateConfig)); 4081 } else if (templateConfig instanceof Array) { 4082 // Assume already an array of DOM nodes - pass through unchanged 4083 callback(templateConfig); 4084 } else if (isDocumentFragment(templateConfig)) { 4085 // Document fragment - use its child nodes 4086 callback(ko.utils.makeArray(templateConfig.childNodes)); 4087 } else if (templateConfig['element']) { 4088 var element = templateConfig['element']; 4089 if (isDomElement(element)) { 4090 // Element instance - copy its child nodes 4091 callback(cloneNodesFromTemplateSourceElement(element)); 4092 } else if (typeof element === 'string') { 4093 // Element ID - find it, then copy its child nodes 4094 var elemInstance = document.getElementById(element); 4095 if (elemInstance) { 4096 callback(cloneNodesFromTemplateSourceElement(elemInstance)); 4097 } else { 4098 errorCallback('Cannot find element with ID ' + element); 4099 } 4100 } else { 4101 errorCallback('Unknown element type: ' + element); 4102 } 4103 } else { 4104 errorCallback('Unknown template value: ' + templateConfig); 4105 } 4106 } 4107 4108 function resolveViewModel(errorCallback, viewModelConfig, callback) { 4109 if (typeof viewModelConfig === 'function') { 4110 // Constructor - convert to standard factory function format 4111 // By design, this does *not* supply componentInfo to the constructor, as the intent is that 4112 // componentInfo contains non-viewmodel data (e.g., the component's element) that should only 4113 // be used in factory functions, not viewmodel constructors. 4114 callback(function (params /*, componentInfo */) { 4115 return new viewModelConfig(params); 4116 }); 4117 } else if (typeof viewModelConfig[createViewModelKey] === 'function') { 4118 // Already a factory function - use it as-is 4119 callback(viewModelConfig[createViewModelKey]); 4120 } else if ('instance' in viewModelConfig) { 4121 // Fixed object instance - promote to createViewModel format for API consistency 4122 var fixedInstance = viewModelConfig['instance']; 4123 callback(function (params, componentInfo) { 4124 return fixedInstance; 4125 }); 4126 } else if ('viewModel' in viewModelConfig) { 4127 // Resolved AMD module whose value is of the form { viewModel: ... } 4128 resolveViewModel(errorCallback, viewModelConfig['viewModel'], callback); 4129 } else { 4130 errorCallback('Unknown viewModel value: ' + viewModelConfig); 4131 } 4132 } 4133 4134 function cloneNodesFromTemplateSourceElement(elemInstance) { 4135 switch (ko.utils.tagNameLower(elemInstance)) { 4136 case 'script': 4137 return ko.utils.parseHtmlFragment(elemInstance.text); 4138 case 'textarea': 4139 return ko.utils.parseHtmlFragment(elemInstance.value); 4140 case 'template': 4141 // For browsers with proper <template> element support (i.e., where the .content property 4142 // gives a document fragment), use that document fragment. 4143 if (isDocumentFragment(elemInstance.content)) { 4144 return ko.utils.cloneNodes(elemInstance.content.childNodes); 4145 } 4146 } 4147 4148 // Regular elements such as <div>, and <template> elements on old browsers that don't really 4149 // understand <template> and just treat it as a regular container 4150 return ko.utils.cloneNodes(elemInstance.childNodes); 4151 } 4152 4153 function isDomElement(obj) { 4154 if (window['HTMLElement']) { 4155 return obj instanceof HTMLElement; 4156 } else { 4157 return obj && obj.tagName && obj.nodeType === 1; 4158 } 4159 } 4160 4161 function isDocumentFragment(obj) { 4162 if (window['DocumentFragment']) { 4163 return obj instanceof DocumentFragment; 4164 } else { 4165 return obj && obj.nodeType === 11; 4166 } 4167 } 4168 4169 function possiblyGetConfigFromAmd(errorCallback, config, callback) { 4170 if (typeof config['require'] === 'string') { 4171 // The config is the value of an AMD module 4172 if (amdRequire || window['require']) { 4173 (amdRequire || window['require'])([config['require']], function (module) { 4174 if (module && typeof module === 'object' && module.__esModule && module.default) { 4175 module = module.default; 4176 } 4177 callback(module); 4178 }); 4179 } else { 4180 errorCallback('Uses require, but no AMD loader is present'); 4181 } 4182 } else { 4183 callback(config); 4184 } 4185 } 4186 4187 function makeErrorCallback(componentName) { 4188 return function (message) { 4189 throw new Error('Component \'' + componentName + '\': ' + message); 4190 }; 4191 } 4192 4193 ko.exportSymbol('components.register', ko.components.register); 4194 ko.exportSymbol('components.isRegistered', ko.components.isRegistered); 4195 ko.exportSymbol('components.unregister', ko.components.unregister); 4196 4197 // Expose the default loader so that developers can directly ask it for configuration 4198 // or to resolve configuration 4199 ko.exportSymbol('components.defaultLoader', ko.components.defaultLoader); 4200 4201 // By default, the default loader is the only registered component loader 4202 ko.components['loaders'].push(ko.components.defaultLoader); 4203 4204 // Privately expose the underlying config registry for use in old-IE shim 4205 ko.components._allRegisteredComponents = defaultConfigRegistry; 4206 })(); 4207 (function (undefined) { 4208 // Overridable API for determining which component name applies to a given node. By overriding this, 4209 // you can for example map specific tagNames to components that are not preregistered. 4210 ko.components['getComponentNameForNode'] = function (node) { 4211 var tagNameLower = ko.utils.tagNameLower(node); 4212 if (ko.components.isRegistered(tagNameLower)) { 4213 // Try to determine that this node can be considered a *custom* element; see https://github.com/knockout/knockout/issues/1603 4214 if (tagNameLower.indexOf('-') != -1 || ('' + node) == "[object HTMLUnknownElement]" || (ko.utils.ieVersion <= 8 && node.tagName === tagNameLower)) { 4215 return tagNameLower; 4216 } 4217 } 4218 }; 4219 4220 ko.components.addBindingsForCustomElement = function (allBindings, node, bindingContext, valueAccessors) { 4221 // Determine if it's really a custom element matching a component 4222 if (node.nodeType === 1) { 4223 var componentName = ko.components['getComponentNameForNode'](node); 4224 if (componentName) { 4225 // It does represent a component, so add a component binding for it 4226 allBindings = allBindings || {}; 4227 4228 if (allBindings['component']) { 4229 // Avoid silently overwriting some other 'component' binding that may already be on the element 4230 throw new Error('Cannot use the "component" binding on a custom element matching a component'); 4231 } 4232 4233 var componentBindingValue = { 'name': componentName, 'params': getComponentParamsFromCustomElement(node, bindingContext) }; 4234 4235 allBindings['component'] = valueAccessors 4236 ? function () { return componentBindingValue; } 4237 : componentBindingValue; 4238 } 4239 } 4240 4241 return allBindings; 4242 } 4243 4244 var nativeBindingProviderInstance = new ko.bindingProvider(); 4245 4246 function getComponentParamsFromCustomElement(elem, bindingContext) { 4247 var paramsAttribute = elem.getAttribute('params'); 4248 4249 if (paramsAttribute) { 4250 var params = nativeBindingProviderInstance['parseBindingsString'](paramsAttribute, bindingContext, elem, { 'valueAccessors': true, 'bindingParams': true }), 4251 rawParamComputedValues = ko.utils.objectMap(params, function (paramValue, paramName) { 4252 return ko.computed(paramValue, null, { disposeWhenNodeIsRemoved: elem }); 4253 }), 4254 result = ko.utils.objectMap(rawParamComputedValues, function (paramValueComputed, paramName) { 4255 var paramValue = paramValueComputed.peek(); 4256 // Does the evaluation of the parameter value unwrap any observables? 4257 if (!paramValueComputed.isActive()) { 4258 // No it doesn't, so there's no need for any computed wrapper. Just pass through the supplied value directly. 4259 // Example: "someVal: firstName, age: 123" (whether or not firstName is an observable/computed) 4260 return paramValue; 4261 } else { 4262 // Yes it does. Supply a computed property that unwraps both the outer (binding expression) 4263 // level of observability, and any inner (resulting model value) level of observability. 4264 // This means the component doesn't have to worry about multiple unwrapping. If the value is a 4265 // writable observable, the computed will also be writable and pass the value on to the observable. 4266 return ko.computed({ 4267 'read': function () { 4268 return ko.utils.unwrapObservable(paramValueComputed()); 4269 }, 4270 'write': ko.isWriteableObservable(paramValue) && function (value) { 4271 paramValueComputed()(value); 4272 }, 4273 disposeWhenNodeIsRemoved: elem 4274 }); 4275 } 4276 }); 4277 4278 // Give access to the raw computeds, as long as that wouldn't overwrite any custom param also called '$raw' 4279 // This is in case the developer wants to react to outer (binding) observability separately from inner 4280 // (model value) observability, or in case the model value observable has subobservables. 4281 if (!Object.prototype.hasOwnProperty.call(result, '$raw')) { 4282 result['$raw'] = rawParamComputedValues; 4283 } 4284 4285 return result; 4286 } else { 4287 // For consistency, absence of a "params" attribute is treated the same as the presence of 4288 // any empty one. Otherwise component viewmodels need special code to check whether or not 4289 // 'params' or 'params.$raw' is null/undefined before reading subproperties, which is annoying. 4290 return { '$raw': {} }; 4291 } 4292 } 4293 4294 // -------------------------------------------------------------------------------- 4295 // Compatibility code for older (pre-HTML5) IE browsers 4296 4297 if (ko.utils.ieVersion < 9) { 4298 // Whenever you preregister a component, enable it as a custom element in the current document 4299 ko.components['register'] = (function (originalFunction) { 4300 return function (componentName) { 4301 document.createElement(componentName); // Allows IE<9 to parse markup containing the custom element 4302 return originalFunction.apply(this, arguments); 4303 } 4304 })(ko.components['register']); 4305 4306 // Whenever you create a document fragment, enable all preregistered component names as custom elements 4307 // This is needed to make innerShiv/jQuery HTML parsing correctly handle the custom elements 4308 document.createDocumentFragment = (function (originalFunction) { 4309 return function () { 4310 var newDocFrag = originalFunction(), 4311 allComponents = ko.components._allRegisteredComponents; 4312 for (var componentName in allComponents) { 4313 if (Object.prototype.hasOwnProperty.call(allComponents, componentName)) { 4314 newDocFrag.createElement(componentName); 4315 } 4316 } 4317 return newDocFrag; 4318 }; 4319 })(document.createDocumentFragment); 4320 } 4321 })(); (function (undefined) { 4322 var componentLoadingOperationUniqueId = 0; 4323 4324 ko.bindingHandlers['component'] = { 4325 'init': function (element, valueAccessor, ignored1, ignored2, bindingContext) { 4326 var currentViewModel, 4327 currentLoadingOperationId, 4328 afterRenderSub, 4329 disposeAssociatedComponentViewModel = function () { 4330 var currentViewModelDispose = currentViewModel && currentViewModel['dispose']; 4331 if (typeof currentViewModelDispose === 'function') { 4332 currentViewModelDispose.call(currentViewModel); 4333 } 4334 if (afterRenderSub) { 4335 afterRenderSub.dispose(); 4336 } 4337 afterRenderSub = null; 4338 currentViewModel = null; 4339 // Any in-flight loading operation is no longer relevant, so make sure we ignore its completion 4340 currentLoadingOperationId = null; 4341 }, 4342 originalChildNodes = ko.utils.makeArray(ko.virtualElements.childNodes(element)); 4343 4344 ko.virtualElements.emptyNode(element); 4345 ko.utils.domNodeDisposal.addDisposeCallback(element, disposeAssociatedComponentViewModel); 4346 4347 ko.computed(function () { 4348 var value = ko.utils.unwrapObservable(valueAccessor()), 4349 componentName, componentParams; 4350 4351 if (typeof value === 'string') { 4352 componentName = value; 4353 } else { 4354 componentName = ko.utils.unwrapObservable(value['name']); 4355 componentParams = ko.utils.unwrapObservable(value['params']); 4356 } 4357 4358 if (!componentName) { 4359 throw new Error('No component name specified'); 4360 } 4361 4362 var asyncContext = ko.bindingEvent.startPossiblyAsyncContentBinding(element, bindingContext); 4363 4364 var loadingOperationId = currentLoadingOperationId = ++componentLoadingOperationUniqueId; 4365 ko.components.get(componentName, function (componentDefinition) { 4366 // If this is not the current load operation for this element, ignore it. 4367 if (currentLoadingOperationId !== loadingOperationId) { 4368 return; 4369 } 4370 4371 // Clean up previous state 4372 disposeAssociatedComponentViewModel(); 4373 4374 // Instantiate and bind new component. Implicitly this cleans any old DOM nodes. 4375 if (!componentDefinition) { 4376 throw new Error('Unknown component \'' + componentName + '\''); 4377 } 4378 cloneTemplateIntoElement(componentName, componentDefinition, element); 4379 4380 var componentInfo = { 4381 'element': element, 4382 'templateNodes': originalChildNodes 4383 }; 4384 4385 var componentViewModel = createViewModel(componentDefinition, componentParams, componentInfo), 4386 childBindingContext = asyncContext['createChildContext'](componentViewModel, { 4387 'extend': function (ctx) { 4388 ctx['$component'] = componentViewModel; 4389 ctx['$componentTemplateNodes'] = originalChildNodes; 4390 } 4391 }); 4392 4393 if (componentViewModel && componentViewModel['koDescendantsComplete']) { 4394 afterRenderSub = ko.bindingEvent.subscribe(element, ko.bindingEvent.descendantsComplete, componentViewModel['koDescendantsComplete'], componentViewModel); 4395 } 4396 4397 currentViewModel = componentViewModel; 4398 ko.applyBindingsToDescendants(childBindingContext, element); 4399 }); 4400 }, null, { disposeWhenNodeIsRemoved: element }); 4401 4402 return { 'controlsDescendantBindings': true }; 4403 } 4404 }; 4405 4406 ko.virtualElements.allowedBindings['component'] = true; 4407 4408 function cloneTemplateIntoElement(componentName, componentDefinition, element) { 4409 var template = componentDefinition['template']; 4410 if (!template) { 4411 throw new Error('Component \'' + componentName + '\' has no template'); 4412 } 4413 4414 var clonedNodesArray = ko.utils.cloneNodes(template); 4415 ko.virtualElements.setDomNodeChildren(element, clonedNodesArray); 4416 } 4417 4418 function createViewModel(componentDefinition, componentParams, componentInfo) { 4419 var componentViewModelFactory = componentDefinition['createViewModel']; 4420 return componentViewModelFactory 4421 ? componentViewModelFactory.call(componentDefinition, componentParams, componentInfo) 4422 : componentParams; // Template-only component 4423 } 4424 4425 })(); 4426 var attrHtmlToJavaScriptMap = { 'class': 'className', 'for': 'htmlFor' }; 4427 ko.bindingHandlers['attr'] = { 4428 'update': function (element, valueAccessor, allBindings) { 4429 var value = ko.utils.unwrapObservable(valueAccessor()) || {}; 4430 ko.utils.objectForEach(value, function (attrName, attrValue) { 4431 attrValue = ko.utils.unwrapObservable(attrValue); 4432 4433 // Find the namespace of this attribute, if any. 4434 var prefixLen = attrName.indexOf(':'); 4435 var namespace = "lookupNamespaceURI" in element && prefixLen > 0 && element.lookupNamespaceURI(attrName.substr(0, prefixLen)); 4436 4437 // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely 4438 // when someProp is a "no value"-like value (strictly null, false, or undefined) 4439 // (because the absence of the "checked" attr is how to mark an element as not checked, etc.) 4440 var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined); 4441 if (toRemove) { 4442 namespace ? element.removeAttributeNS(namespace, attrName) : element.removeAttribute(attrName); 4443 } else { 4444 attrValue = attrValue.toString(); 4445 } 4446 4447 // In IE <= 7 and IE8 Quirks Mode, you have to use the JavaScript property name instead of the 4448 // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior, 4449 // but instead of figuring out the mode, we'll just set the attribute through the JavaScript 4450 // property for IE <= 8. 4451 if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavaScriptMap) { 4452 attrName = attrHtmlToJavaScriptMap[attrName]; 4453 if (toRemove) 4454 element.removeAttribute(attrName); 4455 else 4456 element[attrName] = attrValue; 4457 } else if (!toRemove) { 4458 namespace ? element.setAttributeNS(namespace, attrName, attrValue) : element.setAttribute(attrName, attrValue); 4459 } 4460 4461 // Treat "name" specially - although you can think of it as an attribute, it also needs 4462 // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333) 4463 // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing 4464 // entirely, and there's no strong reason to allow for such casing in HTML. 4465 if (attrName === "name") { 4466 ko.utils.setElementName(element, toRemove ? "" : attrValue); 4467 } 4468 }); 4469 } 4470 }; 4471 (function () { 4472 4473 ko.bindingHandlers['checked'] = { 4474 'after': ['value', 'attr'], 4475 'init': function (element, valueAccessor, allBindings) { 4476 var checkedValue = ko.pureComputed(function () { 4477 // Treat "value" like "checkedValue" when it is included with "checked" binding 4478 if (allBindings['has']('checkedValue')) { 4479 return ko.utils.unwrapObservable(allBindings.get('checkedValue')); 4480 } else if (useElementValue) { 4481 if (allBindings['has']('value')) { 4482 return ko.utils.unwrapObservable(allBindings.get('value')); 4483 } else { 4484 return element.value; 4485 } 4486 } 4487 }); 4488 4489 function updateModel() { 4490 // This updates the model value from the view value. 4491 // It runs in response to DOM events (click) and changes in checkedValue. 4492 var isChecked = element.checked, 4493 elemValue = checkedValue(); 4494 4495 // When we're first setting up this computed, don't change any model state. 4496 if (ko.computedContext.isInitial()) { 4497 return; 4498 } 4499 4500 // We can ignore unchecked radio buttons, because some other radio 4501 // button will be checked, and that one can take care of updating state. 4502 // Also ignore value changes to an already unchecked checkbox. 4503 if (!isChecked && (isRadio || ko.computedContext.getDependenciesCount())) { 4504 return; 4505 } 4506 4507 var modelValue = ko.dependencyDetection.ignore(valueAccessor); 4508 if (valueIsArray) { 4509 var writableValue = rawValueIsNonArrayObservable ? modelValue.peek() : modelValue, 4510 saveOldValue = oldElemValue; 4511 oldElemValue = elemValue; 4512 4513 if (saveOldValue !== elemValue) { 4514 // When we're responding to the checkedValue changing, and the element is 4515 // currently checked, replace the old elem value with the new elem value 4516 // in the model array. 4517 if (isChecked) { 4518 ko.utils.addOrRemoveItem(writableValue, elemValue, true); 4519 ko.utils.addOrRemoveItem(writableValue, saveOldValue, false); 4520 } 4521 } else { 4522 // When we're responding to the user having checked/unchecked a checkbox, 4523 // add/remove the element value to the model array. 4524 ko.utils.addOrRemoveItem(writableValue, elemValue, isChecked); 4525 } 4526 4527 if (rawValueIsNonArrayObservable && ko.isWriteableObservable(modelValue)) { 4528 modelValue(writableValue); 4529 } 4530 } else { 4531 if (isCheckbox) { 4532 if (elemValue === undefined) { 4533 elemValue = isChecked; 4534 } else if (!isChecked) { 4535 elemValue = undefined; 4536 } 4537 } 4538 ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'checked', elemValue, true); 4539 } 4540 }; 4541 4542 function updateView() { 4543 // This updates the view value from the model value. 4544 // It runs in response to changes in the bound (checked) value. 4545 var modelValue = ko.utils.unwrapObservable(valueAccessor()), 4546 elemValue = checkedValue(); 4547 4548 if (valueIsArray) { 4549 // When a checkbox is bound to an array, being checked represents its value being present in that array 4550 element.checked = ko.utils.arrayIndexOf(modelValue, elemValue) >= 0; 4551 oldElemValue = elemValue; 4552 } else if (isCheckbox && elemValue === undefined) { 4553 // When a checkbox is bound to any other value (not an array) and "checkedValue" is not defined, 4554 // being checked represents the value being trueish 4555 element.checked = !!modelValue; 4556 } else { 4557 // Otherwise, being checked means that the checkbox or radio button's value corresponds to the model value 4558 element.checked = (checkedValue() === modelValue); 4559 } 4560 }; 4561 4562 var isCheckbox = element.type == "checkbox", 4563 isRadio = element.type == "radio"; 4564 4565 // Only bind to check boxes and radio buttons 4566 if (!isCheckbox && !isRadio) { 4567 return; 4568 } 4569 4570 var rawValue = valueAccessor(), 4571 valueIsArray = isCheckbox && (ko.utils.unwrapObservable(rawValue) instanceof Array), 4572 rawValueIsNonArrayObservable = !(valueIsArray && rawValue.push && rawValue.splice), 4573 useElementValue = isRadio || valueIsArray, 4574 oldElemValue = valueIsArray ? checkedValue() : undefined; 4575 4576 // IE 6 won't allow radio buttons to be selected unless they have a name 4577 if (isRadio && !element.name) 4578 ko.bindingHandlers['uniqueName']['init'](element, function () { return true }); 4579 4580 // Set up two computeds to update the binding: 4581 4582 // The first responds to changes in the checkedValue value and to element clicks 4583 ko.computed(updateModel, null, { disposeWhenNodeIsRemoved: element }); 4584 ko.utils.registerEventHandler(element, "click", updateModel); 4585 4586 // The second responds to changes in the model value (the one associated with the checked binding) 4587 ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element }); 4588 4589 rawValue = undefined; 4590 } 4591 }; 4592 ko.expressionRewriting.twoWayBindings['checked'] = true; 4593 4594 ko.bindingHandlers['checkedValue'] = { 4595 'update': function (element, valueAccessor) { 4596 element.value = ko.utils.unwrapObservable(valueAccessor()); 4597 } 4598 }; 4599 4600 })(); var classesWrittenByBindingKey = '__ko__cssValue'; 4601 ko.bindingHandlers['class'] = { 4602 'update': function (element, valueAccessor) { 4603 var value = ko.utils.stringTrim(ko.utils.unwrapObservable(valueAccessor())); 4604 ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false); 4605 element[classesWrittenByBindingKey] = value; 4606 ko.utils.toggleDomNodeCssClass(element, value, true); 4607 } 4608 }; 4609 4610 ko.bindingHandlers['css'] = { 4611 'update': function (element, valueAccessor) { 4612 var value = ko.utils.unwrapObservable(valueAccessor()); 4613 if (value !== null && typeof value == "object") { 4614 ko.utils.objectForEach(value, function (className, shouldHaveClass) { 4615 shouldHaveClass = ko.utils.unwrapObservable(shouldHaveClass); 4616 ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass); 4617 }); 4618 } else { 4619 ko.bindingHandlers['class']['update'](element, valueAccessor); 4620 } 4621 } 4622 }; 4623 ko.bindingHandlers['enable'] = { 4624 'update': function (element, valueAccessor) { 4625 var value = ko.utils.unwrapObservable(valueAccessor()); 4626 if (value && element.disabled) 4627 element.removeAttribute("disabled"); 4628 else if ((!value) && (!element.disabled)) 4629 element.disabled = true; 4630 } 4631 }; 4632 4633 ko.bindingHandlers['disable'] = { 4634 'update': function (element, valueAccessor) { 4635 ko.bindingHandlers['enable']['update'](element, function () { return !ko.utils.unwrapObservable(valueAccessor()) }); 4636 } 4637 }; 4638 // For certain common events (currently just 'click'), allow a simplified data-binding syntax 4639 // e.g. click:handler instead of the usual full-length event:{click:handler} 4640 function makeEventHandlerShortcut(eventName) { 4641 ko.bindingHandlers[eventName] = { 4642 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) { 4643 var newValueAccessor = function () { 4644 var result = {}; 4645 result[eventName] = valueAccessor(); 4646 return result; 4647 }; 4648 return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindings, viewModel, bindingContext); 4649 } 4650 } 4651 } 4652 4653 ko.bindingHandlers['event'] = { 4654 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) { 4655 var eventsToHandle = valueAccessor() || {}; 4656 ko.utils.objectForEach(eventsToHandle, function (eventName) { 4657 if (typeof eventName == "string") { 4658 ko.utils.registerEventHandler(element, eventName, function (event) { 4659 var handlerReturnValue; 4660 var handlerFunction = valueAccessor()[eventName]; 4661 if (!handlerFunction) 4662 return; 4663 4664 try { 4665 // Take all the event args, and prefix with the viewmodel 4666 var argsForHandler = ko.utils.makeArray(arguments); 4667 viewModel = bindingContext['$data']; 4668 argsForHandler.unshift(viewModel); 4669 handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler); 4670 } finally { 4671 if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true. 4672 if (event.preventDefault) 4673 event.preventDefault(); 4674 else 4675 event.returnValue = false; 4676 } 4677 } 4678 4679 var bubble = allBindings.get(eventName + 'Bubble') !== false; 4680 if (!bubble) { 4681 event.cancelBubble = true; 4682 if (event.stopPropagation) 4683 event.stopPropagation(); 4684 } 4685 }); 4686 } 4687 }); 4688 } 4689 }; 4690 // "foreach: someExpression" is equivalent to "template: { foreach: someExpression }" 4691 // "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }" 4692 ko.bindingHandlers['foreach'] = { 4693 makeTemplateValueAccessor: function (valueAccessor) { 4694 return function () { 4695 var modelValue = valueAccessor(), 4696 unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here 4697 4698 // If unwrappedValue is the array, pass in the wrapped value on its own 4699 // The value will be unwrapped and tracked within the template binding 4700 // (See https://github.com/SteveSanderson/knockout/issues/523) 4701 if ((!unwrappedValue) || typeof unwrappedValue.length == "number") 4702 return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance }; 4703 4704 // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates 4705 ko.utils.unwrapObservable(modelValue); 4706 return { 4707 'foreach': unwrappedValue['data'], 4708 'as': unwrappedValue['as'], 4709 'noChildContext': unwrappedValue['noChildContext'], 4710 'includeDestroyed': unwrappedValue['includeDestroyed'], 4711 'afterAdd': unwrappedValue['afterAdd'], 4712 'beforeRemove': unwrappedValue['beforeRemove'], 4713 'afterRender': unwrappedValue['afterRender'], 4714 'beforeMove': unwrappedValue['beforeMove'], 4715 'afterMove': unwrappedValue['afterMove'], 4716 'templateEngine': ko.nativeTemplateEngine.instance 4717 }; 4718 }; 4719 }, 4720 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) { 4721 return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor)); 4722 }, 4723 'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) { 4724 return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindings, viewModel, bindingContext); 4725 } 4726 }; 4727 ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings 4728 ko.virtualElements.allowedBindings['foreach'] = true; 4729 var hasfocusUpdatingProperty = '__ko_hasfocusUpdating'; 4730 var hasfocusLastValue = '__ko_hasfocusLastValue'; 4731 ko.bindingHandlers['hasfocus'] = { 4732 'init': function (element, valueAccessor, allBindings) { 4733 var handleElementFocusChange = function (isFocused) { 4734 // Where possible, ignore which event was raised and determine focus state using activeElement, 4735 // as this avoids phantom focus/blur events raised when changing tabs in modern browsers. 4736 // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers, 4737 // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus 4738 // from calling 'blur()' on the element when it loses focus. 4739 // Discussion at https://github.com/SteveSanderson/knockout/pull/352 4740 element[hasfocusUpdatingProperty] = true; 4741 var ownerDoc = element.ownerDocument; 4742 if ("activeElement" in ownerDoc) { 4743 var active; 4744 try { 4745 active = ownerDoc.activeElement; 4746 } catch (e) { 4747 // IE9 throws if you access activeElement during page load (see issue #703) 4748 active = ownerDoc.body; 4749 } 4750 isFocused = (active === element); 4751 } 4752 var modelValue = valueAccessor(); 4753 ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'hasfocus', isFocused, true); 4754 4755 //cache the latest value, so we can avoid unnecessarily calling focus/blur in the update function 4756 element[hasfocusLastValue] = isFocused; 4757 element[hasfocusUpdatingProperty] = false; 4758 }; 4759 var handleElementFocusIn = handleElementFocusChange.bind(null, true); 4760 var handleElementFocusOut = handleElementFocusChange.bind(null, false); 4761 4762 ko.utils.registerEventHandler(element, "focus", handleElementFocusIn); 4763 ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE 4764 ko.utils.registerEventHandler(element, "blur", handleElementFocusOut); 4765 ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE 4766 4767 // Assume element is not focused (prevents "blur" being called initially) 4768 element[hasfocusLastValue] = false; 4769 }, 4770 'update': function (element, valueAccessor) { 4771 var value = !!ko.utils.unwrapObservable(valueAccessor()); 4772 4773 if (!element[hasfocusUpdatingProperty] && element[hasfocusLastValue] !== value) { 4774 value ? element.focus() : element.blur(); 4775 4776 // In IE, the blur method doesn't always cause the element to lose focus (for example, if the window is not in focus). 4777 // Setting focus to the body element does seem to be reliable in IE, but should only be used if we know that the current 4778 // element was focused already. 4779 if (!value && element[hasfocusLastValue]) { 4780 element.ownerDocument.body.focus(); 4781 } 4782 4783 // For IE, which doesn't reliably fire "focus" or "blur" events synchronously 4784 ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); 4785 } 4786 } 4787 }; 4788 ko.expressionRewriting.twoWayBindings['hasfocus'] = true; 4789 4790 ko.bindingHandlers['hasFocus'] = ko.bindingHandlers['hasfocus']; // Make "hasFocus" an alias 4791 ko.expressionRewriting.twoWayBindings['hasFocus'] = 'hasfocus'; 4792 ko.bindingHandlers['html'] = { 4793 'init': function () { 4794 // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications) 4795 return { 'controlsDescendantBindings': true }; 4796 }, 4797 'update': function (element, valueAccessor) { 4798 // setHtml will unwrap the value if needed 4799 ko.utils.setHtml(element, valueAccessor()); 4800 } 4801 }; 4802 (function () { 4803 4804 // Makes a binding like with or if 4805 function makeWithIfBinding(bindingKey, isWith, isNot) { 4806 ko.bindingHandlers[bindingKey] = { 4807 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) { 4808 var didDisplayOnLastUpdate, savedNodes, contextOptions = {}, completeOnRender, needAsyncContext, renderOnEveryChange; 4809 4810 if (isWith) { 4811 var as = allBindings.get('as'), noChildContext = allBindings.get('noChildContext'); 4812 renderOnEveryChange = !(as && noChildContext); 4813 contextOptions = { 'as': as, 'noChildContext': noChildContext, 'exportDependencies': renderOnEveryChange }; 4814 } 4815 4816 completeOnRender = allBindings.get("completeOn") == "render"; 4817 needAsyncContext = completeOnRender || allBindings['has'](ko.bindingEvent.descendantsComplete); 4818 4819 ko.computed(function () { 4820 var value = ko.utils.unwrapObservable(valueAccessor()), 4821 shouldDisplay = !isNot !== !value, // equivalent to isNot ? !value : !!value, 4822 isInitial = !savedNodes, 4823 childContext; 4824 4825 if (!renderOnEveryChange && shouldDisplay === didDisplayOnLastUpdate) { 4826 return; 4827 } 4828 4829 if (needAsyncContext) { 4830 bindingContext = ko.bindingEvent.startPossiblyAsyncContentBinding(element, bindingContext); 4831 } 4832 4833 if (shouldDisplay) { 4834 if (!isWith || renderOnEveryChange) { 4835 contextOptions['dataDependency'] = ko.computedContext.computed(); 4836 } 4837 4838 if (isWith) { 4839 childContext = bindingContext['createChildContext'](typeof value == "function" ? value : valueAccessor, contextOptions); 4840 } else if (ko.computedContext.getDependenciesCount()) { 4841 childContext = bindingContext['extend'](null, contextOptions); 4842 } else { 4843 childContext = bindingContext; 4844 } 4845 } 4846 4847 // Save a copy of the inner nodes on the initial update, but only if we have dependencies. 4848 if (isInitial && ko.computedContext.getDependenciesCount()) { 4849 savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */); 4850 } 4851 4852 if (shouldDisplay) { 4853 if (!isInitial) { 4854 ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes)); 4855 } 4856 4857 ko.applyBindingsToDescendants(childContext, element); 4858 } else { 4859 ko.virtualElements.emptyNode(element); 4860 4861 if (!completeOnRender) { 4862 ko.bindingEvent.notify(element, ko.bindingEvent.childrenComplete); 4863 } 4864 } 4865 4866 didDisplayOnLastUpdate = shouldDisplay; 4867 4868 }, null, { disposeWhenNodeIsRemoved: element }); 4869 4870 return { 'controlsDescendantBindings': true }; 4871 } 4872 }; 4873 ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings 4874 ko.virtualElements.allowedBindings[bindingKey] = true; 4875 } 4876 4877 // Construct the actual binding handlers 4878 makeWithIfBinding('if'); 4879 makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */); 4880 makeWithIfBinding('with', true /* isWith */); 4881 4882 })(); ko.bindingHandlers['let'] = { 4883 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) { 4884 // Make a modified binding context, with extra properties, and apply it to descendant elements 4885 var innerContext = bindingContext['extend'](valueAccessor); 4886 ko.applyBindingsToDescendants(innerContext, element); 4887 4888 return { 'controlsDescendantBindings': true }; 4889 } 4890 }; 4891 ko.virtualElements.allowedBindings['let'] = true; 4892 var captionPlaceholder = {}; 4893 ko.bindingHandlers['options'] = { 4894 'init': function (element) { 4895 if (ko.utils.tagNameLower(element) !== "select") 4896 throw new Error("options binding applies only to SELECT elements"); 4897 4898 // Remove all existing <option>s. 4899 while (element.length > 0) { 4900 element.remove(0); 4901 } 4902 4903 // Ensures that the binding processor doesn't try to bind the options 4904 return { 'controlsDescendantBindings': true }; 4905 }, 4906 'update': function (element, valueAccessor, allBindings) { 4907 function selectedOptions() { 4908 return ko.utils.arrayFilter(element.options, function (node) { return node.selected; }); 4909 } 4910 4911 var selectWasPreviouslyEmpty = element.length == 0, 4912 multiple = element.multiple, 4913 previousScrollTop = (!selectWasPreviouslyEmpty && multiple) ? element.scrollTop : null, 4914 unwrappedArray = ko.utils.unwrapObservable(valueAccessor()), 4915 valueAllowUnset = allBindings.get('valueAllowUnset') && allBindings['has']('value'), 4916 includeDestroyed = allBindings.get('optionsIncludeDestroyed'), 4917 arrayToDomNodeChildrenOptions = {}, 4918 captionValue, 4919 filteredArray, 4920 previousSelectedValues = []; 4921 4922 if (!valueAllowUnset) { 4923 if (multiple) { 4924 previousSelectedValues = ko.utils.arrayMap(selectedOptions(), ko.selectExtensions.readValue); 4925 } else if (element.selectedIndex >= 0) { 4926 previousSelectedValues.push(ko.selectExtensions.readValue(element.options[element.selectedIndex])); 4927 } 4928 } 4929 4930 if (unwrappedArray) { 4931 if (typeof unwrappedArray.length == "undefined") // Coerce single value into array 4932 unwrappedArray = [unwrappedArray]; 4933 4934 // Filter out any entries marked as destroyed 4935 filteredArray = ko.utils.arrayFilter(unwrappedArray, function (item) { 4936 return includeDestroyed || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']); 4937 }); 4938 4939 // If caption is included, add it to the array 4940 if (allBindings['has']('optionsCaption')) { 4941 captionValue = ko.utils.unwrapObservable(allBindings.get('optionsCaption')); 4942 // If caption value is null or undefined, don't show a caption 4943 if (captionValue !== null && captionValue !== undefined) { 4944 filteredArray.unshift(captionPlaceholder); 4945 } 4946 } 4947 } else { 4948 // If a falsy value is provided (e.g. null), we'll simply empty the select element 4949 } 4950 4951 function applyToObject(object, predicate, defaultValue) { 4952 var predicateType = typeof predicate; 4953 if (predicateType == "function") // Given a function; run it against the data value 4954 return predicate(object); 4955 else if (predicateType == "string") // Given a string; treat it as a property name on the data value 4956 return object[predicate]; 4957 else // Given no optionsText arg; use the data value itself 4958 return defaultValue; 4959 } 4960 4961 // The following functions can run at two different times: 4962 // The first is when the whole array is being updated directly from this binding handler. 4963 // The second is when an observable value for a specific array entry is updated. 4964 // oldOptions will be empty in the first case, but will be filled with the previously generated option in the second. 4965 var itemUpdate = false; 4966 function optionForArrayItem(arrayEntry, index, oldOptions) { 4967 if (oldOptions.length) { 4968 previousSelectedValues = !valueAllowUnset && oldOptions[0].selected ? [ko.selectExtensions.readValue(oldOptions[0])] : []; 4969 itemUpdate = true; 4970 } 4971 var option = element.ownerDocument.createElement("option"); 4972 if (arrayEntry === captionPlaceholder) { 4973 ko.utils.setTextContent(option, allBindings.get('optionsCaption')); 4974 ko.selectExtensions.writeValue(option, undefined); 4975 } else { 4976 // Apply a value to the option element 4977 var optionValue = applyToObject(arrayEntry, allBindings.get('optionsValue'), arrayEntry); 4978 ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue)); 4979 4980 // Apply some text to the option element 4981 var optionText = applyToObject(arrayEntry, allBindings.get('optionsText'), optionValue); 4982 ko.utils.setTextContent(option, optionText); 4983 } 4984 return [option]; 4985 } 4986 4987 // By using a beforeRemove callback, we delay the removal until after new items are added. This fixes a selection 4988 // problem in IE<=8 and Firefox. See https://github.com/knockout/knockout/issues/1208 4989 arrayToDomNodeChildrenOptions['beforeRemove'] = 4990 function (option) { 4991 element.removeChild(option); 4992 }; 4993 4994 function setSelectionCallback(arrayEntry, newOptions) { 4995 if (itemUpdate && valueAllowUnset) { 4996 // The model value is authoritative, so make sure its value is the one selected 4997 ko.bindingEvent.notify(element, ko.bindingEvent.childrenComplete); 4998 } else if (previousSelectedValues.length) { 4999 // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document. 5000 // That's why we first added them without selection. Now it's time to set the selection. 5001 var isSelected = ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[0])) >= 0; 5002 ko.utils.setOptionNodeSelectionState(newOptions[0], isSelected); 5003 5004 // If this option was changed from being selected during a single-item update, notify the change 5005 if (itemUpdate && !isSelected) { 5006 ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]); 5007 } 5008 } 5009 } 5010 5011 var callback = setSelectionCallback; 5012 if (allBindings['has']('optionsAfterRender') && typeof allBindings.get('optionsAfterRender') == "function") { 5013 callback = function (arrayEntry, newOptions) { 5014 setSelectionCallback(arrayEntry, newOptions); 5015 ko.dependencyDetection.ignore(allBindings.get('optionsAfterRender'), null, [newOptions[0], arrayEntry !== captionPlaceholder ? arrayEntry : undefined]); 5016 } 5017 } 5018 5019 ko.utils.setDomNodeChildrenFromArrayMapping(element, filteredArray, optionForArrayItem, arrayToDomNodeChildrenOptions, callback); 5020 5021 if (!valueAllowUnset) { 5022 // Determine if the selection has changed as a result of updating the options list 5023 var selectionChanged; 5024 if (multiple) { 5025 // For a multiple-select box, compare the new selection count to the previous one 5026 // But if nothing was selected before, the selection can't have changed 5027 selectionChanged = previousSelectedValues.length && selectedOptions().length < previousSelectedValues.length; 5028 } else { 5029 // For a single-select box, compare the current value to the previous value 5030 // But if nothing was selected before or nothing is selected now, just look for a change in selection 5031 selectionChanged = (previousSelectedValues.length && element.selectedIndex >= 0) 5032 ? (ko.selectExtensions.readValue(element.options[element.selectedIndex]) !== previousSelectedValues[0]) 5033 : (previousSelectedValues.length || element.selectedIndex >= 0); 5034 } 5035 5036 // Ensure consistency between model value and selected option. 5037 // If the dropdown was changed so that selection is no longer the same, 5038 // notify the value or selectedOptions binding. 5039 if (selectionChanged) { 5040 ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]); 5041 } 5042 } 5043 5044 if (valueAllowUnset || ko.computedContext.isInitial()) { 5045 ko.bindingEvent.notify(element, ko.bindingEvent.childrenComplete); 5046 } 5047 5048 // Workaround for IE bug 5049 ko.utils.ensureSelectElementIsRenderedCorrectly(element); 5050 5051 if (previousScrollTop && Math.abs(previousScrollTop - element.scrollTop) > 20) 5052 element.scrollTop = previousScrollTop; 5053 } 5054 }; 5055 ko.bindingHandlers['options'].optionValueDomDataKey = ko.utils.domData.nextKey(); 5056 ko.bindingHandlers['selectedOptions'] = { 5057 'init': function (element, valueAccessor, allBindings) { 5058 function updateFromView() { 5059 var value = valueAccessor(), valueToWrite = []; 5060 ko.utils.arrayForEach(element.getElementsByTagName("option"), function (node) { 5061 if (node.selected) 5062 valueToWrite.push(ko.selectExtensions.readValue(node)); 5063 }); 5064 ko.expressionRewriting.writeValueToProperty(value, allBindings, 'selectedOptions', valueToWrite); 5065 } 5066 5067 function updateFromModel() { 5068 var newValue = ko.utils.unwrapObservable(valueAccessor()), 5069 previousScrollTop = element.scrollTop; 5070 5071 if (newValue && typeof newValue.length == "number") { 5072 ko.utils.arrayForEach(element.getElementsByTagName("option"), function (node) { 5073 var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0; 5074 if (node.selected != isSelected) { // This check prevents flashing of the select element in IE 5075 ko.utils.setOptionNodeSelectionState(node, isSelected); 5076 } 5077 }); 5078 } 5079 5080 element.scrollTop = previousScrollTop; 5081 } 5082 5083 if (ko.utils.tagNameLower(element) != "select") { 5084 throw new Error("selectedOptions binding applies only to SELECT elements"); 5085 } 5086 5087 var updateFromModelComputed; 5088 ko.bindingEvent.subscribe(element, ko.bindingEvent.childrenComplete, function () { 5089 if (!updateFromModelComputed) { 5090 ko.utils.registerEventHandler(element, "change", updateFromView); 5091 updateFromModelComputed = ko.computed(updateFromModel, null, { disposeWhenNodeIsRemoved: element }); 5092 } else { 5093 updateFromView(); 5094 } 5095 }, null, { 'notifyImmediately': true }); 5096 }, 5097 'update': function () { } // Keep for backwards compatibility with code that may have wrapped binding 5098 }; 5099 ko.expressionRewriting.twoWayBindings['selectedOptions'] = true; 5100 ko.bindingHandlers['style'] = { 5101 'update': function (element, valueAccessor) { 5102 var value = ko.utils.unwrapObservable(valueAccessor() || {}); 5103 ko.utils.objectForEach(value, function (styleName, styleValue) { 5104 styleValue = ko.utils.unwrapObservable(styleValue); 5105 5106 if (styleValue === null || styleValue === undefined || styleValue === false) { 5107 // Empty string removes the value, whereas null/undefined have no effect 5108 styleValue = ""; 5109 } 5110 5111 if (jQueryInstance) { 5112 jQueryInstance(element)['css'](styleName, styleValue); 5113 } else if (/^--/.test(styleName)) { 5114 // Is styleName a custom CSS property? 5115 element.style.setProperty(styleName, styleValue); 5116 } else { 5117 styleName = styleName.replace(/-(\w)/g, function (all, letter) { 5118 return letter.toUpperCase(); 5119 }); 5120 5121 var previousStyle = element.style[styleName]; 5122 element.style[styleName] = styleValue; 5123 5124 if (styleValue !== previousStyle && element.style[styleName] == previousStyle && !isNaN(styleValue)) { 5125 element.style[styleName] = styleValue + "px"; 5126 } 5127 } 5128 }); 5129 } 5130 }; 5131 ko.bindingHandlers['submit'] = { 5132 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) { 5133 if (typeof valueAccessor() != "function") 5134 throw new Error("The value for a submit binding must be a function"); 5135 ko.utils.registerEventHandler(element, "submit", function (event) { 5136 var handlerReturnValue; 5137 var value = valueAccessor(); 5138 try { handlerReturnValue = value.call(bindingContext['$data'], element); } 5139 finally { 5140 if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true. 5141 if (event.preventDefault) 5142 event.preventDefault(); 5143 else 5144 event.returnValue = false; 5145 } 5146 } 5147 }); 5148 } 5149 }; 5150 ko.bindingHandlers['text'] = { 5151 'init': function () { 5152 // Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications). 5153 // It should also make things faster, as we no longer have to consider whether the text node might be bindable. 5154 return { 'controlsDescendantBindings': true }; 5155 }, 5156 'update': function (element, valueAccessor) { 5157 ko.utils.setTextContent(element, valueAccessor()); 5158 } 5159 }; 5160 ko.virtualElements.allowedBindings['text'] = true; 5161 (function () { 5162 5163 if (window && window.navigator) { 5164 var parseVersion = function (matches) { 5165 if (matches) { 5166 return parseFloat(matches[1]); 5167 } 5168 }; 5169 5170 // Detect various browser versions because some old versions don't fully support the 'input' event 5171 var userAgent = window.navigator.userAgent, 5172 operaVersion, chromeVersion, safariVersion, firefoxVersion, ieVersion, edgeVersion; 5173 5174 (operaVersion = window.opera && window.opera.version && parseInt(window.opera.version())) 5175 || (edgeVersion = parseVersion(userAgent.match(/Edge\/([^ ]+)$/))) 5176 || (chromeVersion = parseVersion(userAgent.match(/Chrome\/([^ ]+)/))) 5177 || (safariVersion = parseVersion(userAgent.match(/Version\/([^ ]+) Safari/))) 5178 || (firefoxVersion = parseVersion(userAgent.match(/Firefox\/([^ ]+)/))) 5179 || (ieVersion = ko.utils.ieVersion || parseVersion(userAgent.match(/MSIE ([^ ]+)/))) // Detects up to IE 10 5180 || (ieVersion = parseVersion(userAgent.match(/rv:([^ )]+)/))); // Detects IE 11 5181 } 5182 5183 // IE 8 and 9 have bugs that prevent the normal events from firing when the value changes. 5184 // But it does fire the 'selectionchange' event on many of those, presumably because the 5185 // cursor is moving and that counts as the selection changing. The 'selectionchange' event is 5186 // fired at the document level only and doesn't directly indicate which element changed. We 5187 // set up just one event handler for the document and use 'activeElement' to determine which 5188 // element was changed. 5189 if (ieVersion >= 8 && ieVersion < 10) { 5190 var selectionChangeRegisteredName = ko.utils.domData.nextKey(), 5191 selectionChangeHandlerName = ko.utils.domData.nextKey(); 5192 var selectionChangeHandler = function (event) { 5193 var target = this.activeElement, 5194 handler = target && ko.utils.domData.get(target, selectionChangeHandlerName); 5195 if (handler) { 5196 handler(event); 5197 } 5198 }; 5199 var registerForSelectionChangeEvent = function (element, handler) { 5200 var ownerDoc = element.ownerDocument; 5201 if (!ko.utils.domData.get(ownerDoc, selectionChangeRegisteredName)) { 5202 ko.utils.domData.set(ownerDoc, selectionChangeRegisteredName, true); 5203 ko.utils.registerEventHandler(ownerDoc, 'selectionchange', selectionChangeHandler); 5204 } 5205 ko.utils.domData.set(element, selectionChangeHandlerName, handler); 5206 }; 5207 } 5208 5209 ko.bindingHandlers['textInput'] = { 5210 'init': function (element, valueAccessor, allBindings) { 5211 5212 var previousElementValue = element.value, 5213 timeoutHandle, 5214 elementValueBeforeEvent; 5215 5216 var updateModel = function (event) { 5217 clearTimeout(timeoutHandle); 5218 elementValueBeforeEvent = timeoutHandle = undefined; 5219 5220 var elementValue = element.value; 5221 if (previousElementValue !== elementValue) { 5222 // Provide a way for tests to know exactly which event was processed 5223 if (DEBUG && event) element['_ko_textInputProcessedEvent'] = event.type; 5224 previousElementValue = elementValue; 5225 ko.expressionRewriting.writeValueToProperty(valueAccessor(), allBindings, 'textInput', elementValue); 5226 } 5227 }; 5228 5229 var deferUpdateModel = function (event) { 5230 if (!timeoutHandle) { 5231 // The elementValueBeforeEvent variable is set *only* during the brief gap between an 5232 // event firing and the updateModel function running. This allows us to ignore model 5233 // updates that are from the previous state of the element, usually due to techniques 5234 // such as rateLimit. Such updates, if not ignored, can cause keystrokes to be lost. 5235 elementValueBeforeEvent = element.value; 5236 var handler = DEBUG ? updateModel.bind(element, { type: event.type }) : updateModel; 5237 timeoutHandle = ko.utils.setTimeout(handler, 4); 5238 } 5239 }; 5240 5241 // IE9 will mess up the DOM if you handle events synchronously which results in DOM changes (such as other bindings); 5242 // so we'll make sure all updates are asynchronous 5243 var ieUpdateModel = ko.utils.ieVersion == 9 ? deferUpdateModel : updateModel, 5244 ourUpdate = false; 5245 5246 var updateView = function () { 5247 var modelValue = ko.utils.unwrapObservable(valueAccessor()); 5248 5249 if (modelValue === null || modelValue === undefined) { 5250 modelValue = ''; 5251 } 5252 5253 if (elementValueBeforeEvent !== undefined && modelValue === elementValueBeforeEvent) { 5254 ko.utils.setTimeout(updateView, 4); 5255 return; 5256 } 5257 5258 // Update the element only if the element and model are different. On some browsers, updating the value 5259 // will move the cursor to the end of the input, which would be bad while the user is typing. 5260 if (element.value !== modelValue) { 5261 ourUpdate = true; // Make sure we ignore events (propertychange) that result from updating the value 5262 element.value = modelValue; 5263 ourUpdate = false; 5264 previousElementValue = element.value; // In case the browser changes the value (see #2281) 5265 } 5266 }; 5267 5268 var onEvent = function (event, handler) { 5269 ko.utils.registerEventHandler(element, event, handler); 5270 }; 5271 5272 if (DEBUG && ko.bindingHandlers['textInput']['_forceUpdateOn']) { 5273 // Provide a way for tests to specify exactly which events are bound 5274 ko.utils.arrayForEach(ko.bindingHandlers['textInput']['_forceUpdateOn'], function (eventName) { 5275 if (eventName.slice(0, 5) == 'after') { 5276 onEvent(eventName.slice(5), deferUpdateModel); 5277 } else { 5278 onEvent(eventName, updateModel); 5279 } 5280 }); 5281 } else { 5282 if (ieVersion) { 5283 // All versions (including 11) of Internet Explorer have a bug that they don't generate an input or propertychange event when ESC is pressed 5284 onEvent('keypress', updateModel); 5285 } 5286 if (ieVersion < 11) { 5287 // Internet Explorer <= 8 doesn't support the 'input' event, but does include 'propertychange' that fires whenever 5288 // any property of an element changes. Unlike 'input', it also fires if a property is changed from JavaScript code, 5289 // but that's an acceptable compromise for this binding. IE 9 and 10 support 'input', but since they don't always 5290 // fire it when using autocomplete, we'll use 'propertychange' for them also. 5291 onEvent('propertychange', function (event) { 5292 if (!ourUpdate && event.propertyName === 'value') { 5293 ieUpdateModel(event); 5294 } 5295 }); 5296 } 5297 if (ieVersion == 8) { 5298 // IE 8 has a bug where it fails to fire 'propertychange' on the first update following a value change from 5299 // JavaScript code. It also doesn't fire if you clear the entire value. To fix this, we bind to the following 5300 // events too. 5301 onEvent('keyup', updateModel); // A single keystoke 5302 onEvent('keydown', updateModel); // The first character when a key is held down 5303 } 5304 if (registerForSelectionChangeEvent) { 5305 // Internet Explorer 9 doesn't fire the 'input' event when deleting text, including using 5306 // the backspace, delete, or ctrl-x keys, clicking the 'x' to clear the input, dragging text 5307 // out of the field, and cutting or deleting text using the context menu. 'selectionchange' 5308 // can detect all of those except dragging text out of the field, for which we use 'dragend'. 5309 // These are also needed in IE8 because of the bug described above. 5310 registerForSelectionChangeEvent(element, ieUpdateModel); // 'selectionchange' covers cut, paste, drop, delete, etc. 5311 onEvent('dragend', deferUpdateModel); 5312 } 5313 5314 if (!ieVersion || ieVersion >= 9) { 5315 // All other supported browsers support the 'input' event, which fires whenever the content of the element is changed 5316 // through the user interface. 5317 onEvent('input', ieUpdateModel); 5318 } 5319 5320 if (safariVersion < 5 && ko.utils.tagNameLower(element) === "textarea") { 5321 // Safari <5 doesn't fire the 'input' event for <textarea> elements (it does fire 'textInput' 5322 // but only when typing). So we'll just catch as much as we can with keydown, cut, and paste. 5323 onEvent('keydown', deferUpdateModel); 5324 onEvent('paste', deferUpdateModel); 5325 onEvent('cut', deferUpdateModel); 5326 } else if (operaVersion < 11) { 5327 // Opera 10 doesn't always fire the 'input' event for cut, paste, undo & drop operations. 5328 // We can try to catch some of those using 'keydown'. 5329 onEvent('keydown', deferUpdateModel); 5330 } else if (firefoxVersion < 4.0) { 5331 // Firefox <= 3.6 doesn't fire the 'input' event when text is filled in through autocomplete 5332 onEvent('DOMAutoComplete', updateModel); 5333 5334 // Firefox <=3.5 doesn't fire the 'input' event when text is dropped into the input. 5335 onEvent('dragdrop', updateModel); // <3.5 5336 onEvent('drop', updateModel); // 3.5 5337 } else if (edgeVersion && element.type === "number") { 5338 // Microsoft Edge doesn't fire 'input' or 'change' events for number inputs when 5339 // the value is changed via the up / down arrow keys 5340 onEvent('keydown', deferUpdateModel); 5341 } 5342 } 5343 5344 // Bind to the change event so that we can catch programmatic updates of the value that fire this event. 5345 onEvent('change', updateModel); 5346 5347 // To deal with browsers that don't notify any kind of event for some changes (IE, Safari, etc.) 5348 onEvent('blur', updateModel); 5349 5350 ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element }); 5351 } 5352 }; 5353 ko.expressionRewriting.twoWayBindings['textInput'] = true; 5354 5355 // textinput is an alias for textInput 5356 ko.bindingHandlers['textinput'] = { 5357 // preprocess is the only way to set up a full alias 5358 'preprocess': function (value, name, addBinding) { 5359 addBinding('textInput', value); 5360 } 5361 }; 5362 5363 })(); ko.bindingHandlers['uniqueName'] = { 5364 'init': function (element, valueAccessor) { 5365 if (valueAccessor()) { 5366 var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex); 5367 ko.utils.setElementName(element, name); 5368 } 5369 } 5370 }; 5371 ko.bindingHandlers['uniqueName'].currentIndex = 0; 5372 ko.bindingHandlers['using'] = { 5373 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) { 5374 var options; 5375 5376 if (allBindings['has']('as')) { 5377 options = { 'as': allBindings.get('as'), 'noChildContext': allBindings.get('noChildContext') }; 5378 } 5379 5380 var innerContext = bindingContext['createChildContext'](valueAccessor, options); 5381 ko.applyBindingsToDescendants(innerContext, element); 5382 5383 return { 'controlsDescendantBindings': true }; 5384 } 5385 }; 5386 ko.virtualElements.allowedBindings['using'] = true; 5387 ko.bindingHandlers['value'] = { 5388 'init': function (element, valueAccessor, allBindings) { 5389 var tagName = ko.utils.tagNameLower(element), 5390 isInputElement = tagName == "input"; 5391 5392 // If the value binding is placed on a radio/checkbox, then just pass through to checkedValue and quit 5393 if (isInputElement && (element.type == "checkbox" || element.type == "radio")) { 5394 ko.applyBindingAccessorsToNode(element, { 'checkedValue': valueAccessor }); 5395 return; 5396 } 5397 5398 var eventsToCatch = []; 5399 var requestedEventsToCatch = allBindings.get("valueUpdate"); 5400 var propertyChangedFired = false; 5401 var elementValueBeforeEvent = null; 5402 5403 if (requestedEventsToCatch) { 5404 // Allow both individual event names, and arrays of event names 5405 if (typeof requestedEventsToCatch == "string") { 5406 eventsToCatch = [requestedEventsToCatch]; 5407 } else { 5408 eventsToCatch = ko.utils.arrayGetDistinctValues(requestedEventsToCatch); 5409 } 5410 ko.utils.arrayRemoveItem(eventsToCatch, "change"); // We'll subscribe to "change" events later 5411 } 5412 5413 var valueUpdateHandler = function () { 5414 elementValueBeforeEvent = null; 5415 propertyChangedFired = false; 5416 var modelValue = valueAccessor(); 5417 var elementValue = ko.selectExtensions.readValue(element); 5418 ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'value', elementValue); 5419 } 5420 5421 // Workaround for https://github.com/SteveSanderson/knockout/issues/122 5422 // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list 5423 var ieAutoCompleteHackNeeded = ko.utils.ieVersion && isInputElement && element.type == "text" 5424 && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off"); 5425 if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) { 5426 ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true }); 5427 ko.utils.registerEventHandler(element, "focus", function () { propertyChangedFired = false }); 5428 ko.utils.registerEventHandler(element, "blur", function () { 5429 if (propertyChangedFired) { 5430 valueUpdateHandler(); 5431 } 5432 }); 5433 } 5434 5435 ko.utils.arrayForEach(eventsToCatch, function (eventName) { 5436 // The syntax "after<eventname>" means "run the handler asynchronously after the event" 5437 // This is useful, for example, to catch "keydown" events after the browser has updated the control 5438 // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event) 5439 var handler = valueUpdateHandler; 5440 if (ko.utils.stringStartsWith(eventName, "after")) { 5441 handler = function () { 5442 // The elementValueBeforeEvent variable is non-null *only* during the brief gap between 5443 // a keyX event firing and the valueUpdateHandler running, which is scheduled to happen 5444 // at the earliest asynchronous opportunity. We store this temporary information so that 5445 // if, between keyX and valueUpdateHandler, the underlying model value changes separately, 5446 // we can overwrite that model value change with the value the user just typed. Otherwise, 5447 // techniques like rateLimit can trigger model changes at critical moments that will 5448 // override the user's inputs, causing keystrokes to be lost. 5449 elementValueBeforeEvent = ko.selectExtensions.readValue(element); 5450 ko.utils.setTimeout(valueUpdateHandler, 0); 5451 }; 5452 eventName = eventName.substring("after".length); 5453 } 5454 ko.utils.registerEventHandler(element, eventName, handler); 5455 }); 5456 5457 var updateFromModel; 5458 5459 if (isInputElement && element.type == "file") { 5460 // For file input elements, can only write the empty string 5461 updateFromModel = function () { 5462 var newValue = ko.utils.unwrapObservable(valueAccessor()); 5463 if (newValue === null || newValue === undefined || newValue === "") { 5464 element.value = ""; 5465 } else { 5466 ko.dependencyDetection.ignore(valueUpdateHandler); // reset the model to match the element 5467 } 5468 } 5469 } else { 5470 updateFromModel = function () { 5471 var newValue = ko.utils.unwrapObservable(valueAccessor()); 5472 var elementValue = ko.selectExtensions.readValue(element); 5473 5474 if (elementValueBeforeEvent !== null && newValue === elementValueBeforeEvent) { 5475 ko.utils.setTimeout(updateFromModel, 0); 5476 return; 5477 } 5478 5479 var valueHasChanged = newValue !== elementValue; 5480 5481 if (valueHasChanged || elementValue === undefined) { 5482 if (tagName === "select") { 5483 var allowUnset = allBindings.get('valueAllowUnset'); 5484 ko.selectExtensions.writeValue(element, newValue, allowUnset); 5485 if (!allowUnset && newValue !== ko.selectExtensions.readValue(element)) { 5486 // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change, 5487 // because you're not allowed to have a model value that disagrees with a visible UI selection. 5488 ko.dependencyDetection.ignore(valueUpdateHandler); 5489 } 5490 } else { 5491 ko.selectExtensions.writeValue(element, newValue); 5492 } 5493 } 5494 }; 5495 } 5496 5497 if (tagName === "select") { 5498 var updateFromModelComputed; 5499 ko.bindingEvent.subscribe(element, ko.bindingEvent.childrenComplete, function () { 5500 if (!updateFromModelComputed) { 5501 ko.utils.registerEventHandler(element, "change", valueUpdateHandler); 5502 updateFromModelComputed = ko.computed(updateFromModel, null, { disposeWhenNodeIsRemoved: element }); 5503 } else if (allBindings.get('valueAllowUnset')) { 5504 updateFromModel(); 5505 } else { 5506 valueUpdateHandler(); 5507 } 5508 }, null, { 'notifyImmediately': true }); 5509 } else { 5510 ko.utils.registerEventHandler(element, "change", valueUpdateHandler); 5511 ko.computed(updateFromModel, null, { disposeWhenNodeIsRemoved: element }); 5512 } 5513 }, 5514 'update': function () { } // Keep for backwards compatibility with code that may have wrapped value binding 5515 }; 5516 ko.expressionRewriting.twoWayBindings['value'] = true; 5517 ko.bindingHandlers['visible'] = { 5518 'update': function (element, valueAccessor) { 5519 var value = ko.utils.unwrapObservable(valueAccessor()); 5520 var isCurrentlyVisible = !(element.style.display == "none"); 5521 if (value && !isCurrentlyVisible) 5522 element.style.display = ""; 5523 else if ((!value) && isCurrentlyVisible) 5524 element.style.display = "none"; 5525 } 5526 }; 5527 5528 ko.bindingHandlers['hidden'] = { 5529 'update': function (element, valueAccessor) { 5530 ko.bindingHandlers['visible']['update'](element, function () { return !ko.utils.unwrapObservable(valueAccessor()) }); 5531 } 5532 }; 5533 // 'click' is just a shorthand for the usual full-length event:{click:handler} 5534 makeEventHandlerShortcut('click'); 5535 // If you want to make a custom template engine, 5536 // 5537 // [1] Inherit from this class (like ko.nativeTemplateEngine does) 5538 // [2] Override 'renderTemplateSource', supplying a function with this signature: 5539 // 5540 // function (templateSource, bindingContext, options) { 5541 // // - templateSource.text() is the text of the template you should render 5542 // // - bindingContext.$data is the data you should pass into the template 5543 // // - you might also want to make bindingContext.$parent, bindingContext.$parents, 5544 // // and bindingContext.$root available in the template too 5545 // // - options gives you access to any other properties set on "data-bind: { template: options }" 5546 // // - templateDocument is the document object of the template 5547 // // 5548 // // Return value: an array of DOM nodes 5549 // } 5550 // 5551 // [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature: 5552 // 5553 // function (script) { 5554 // // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result" 5555 // // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }' 5556 // } 5557 // 5558 // This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables. 5559 // If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does) 5560 // and then you don't need to override 'createJavaScriptEvaluatorBlock'. 5561 5562 ko.templateEngine = function () { }; 5563 5564 ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options, templateDocument) { 5565 throw new Error("Override renderTemplateSource"); 5566 }; 5567 5568 ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) { 5569 throw new Error("Override createJavaScriptEvaluatorBlock"); 5570 }; 5571 5572 ko.templateEngine.prototype['makeTemplateSource'] = function (template, templateDocument) { 5573 // Named template 5574 if (typeof template == "string") { 5575 templateDocument = templateDocument || document; 5576 var elem = templateDocument.getElementById(template); 5577 if (!elem) 5578 throw new Error("Cannot find template with ID " + template); 5579 return new ko.templateSources.domElement(elem); 5580 } else if ((template.nodeType == 1) || (template.nodeType == 8)) { 5581 // Anonymous template 5582 return new ko.templateSources.anonymousTemplate(template); 5583 } else 5584 throw new Error("Unknown template type: " + template); 5585 }; 5586 5587 ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) { 5588 var templateSource = this['makeTemplateSource'](template, templateDocument); 5589 return this['renderTemplateSource'](templateSource, bindingContext, options, templateDocument); 5590 }; 5591 5592 ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) { 5593 // Skip rewriting if requested 5594 if (this['allowTemplateRewriting'] === false) 5595 return true; 5596 return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten"); 5597 }; 5598 5599 ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) { 5600 var templateSource = this['makeTemplateSource'](template, templateDocument); 5601 var rewritten = rewriterCallback(templateSource['text']()); 5602 templateSource['text'](rewritten); 5603 templateSource['data']("isRewritten", true); 5604 }; 5605 5606 ko.exportSymbol('templateEngine', ko.templateEngine); 5607 5608 ko.templateRewriting = (function () { 5609 var memoizeDataBindingAttributeSyntaxRegex = /(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'|[^>]*))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi; 5610 var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g; 5611 5612 function validateDataBindValuesForRewriting(keyValueArray) { 5613 var allValidators = ko.expressionRewriting.bindingRewriteValidators; 5614 for (var i = 0; i < keyValueArray.length; i++) { 5615 var key = keyValueArray[i]['key']; 5616 if (Object.prototype.hasOwnProperty.call(allValidators, key)) { 5617 var validator = allValidators[key]; 5618 5619 if (typeof validator === "function") { 5620 var possibleErrorMessage = validator(keyValueArray[i]['value']); 5621 if (possibleErrorMessage) 5622 throw new Error(possibleErrorMessage); 5623 } else if (!validator) { 5624 throw new Error("This template engine does not support the '" + key + "' binding within its templates"); 5625 } 5626 } 5627 } 5628 } 5629 5630 function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, nodeName, templateEngine) { 5631 var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue); 5632 validateDataBindValuesForRewriting(dataBindKeyValueArray); 5633 var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray, { 'valueAccessors': true }); 5634 5635 // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional 5636 // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this 5637 // extra indirection. 5638 var applyBindingsToNextSiblingScript = 5639 "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()},'" + nodeName.toLowerCase() + "')"; 5640 return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain; 5641 } 5642 5643 return { 5644 ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) { 5645 if (!templateEngine['isTemplateRewritten'](template, templateDocument)) 5646 templateEngine['rewriteTemplate'](template, function (htmlString) { 5647 return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine); 5648 }, templateDocument); 5649 }, 5650 5651 memoizeBindingAttributeSyntax: function (htmlString, templateEngine) { 5652 return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () { 5653 return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[4], /* tagToRetain: */ arguments[1], /* nodeName: */ arguments[2], templateEngine); 5654 }).replace(memoizeVirtualContainerBindingSyntaxRegex, function () { 5655 return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", /* nodeName: */ "#comment", templateEngine); 5656 }); 5657 }, 5658 5659 applyMemoizedBindingsToNextSibling: function (bindings, nodeName) { 5660 return ko.memoization.memoize(function (domNode, bindingContext) { 5661 var nodeToBind = domNode.nextSibling; 5662 if (nodeToBind && nodeToBind.nodeName.toLowerCase() === nodeName) { 5663 ko.applyBindingAccessorsToNode(nodeToBind, bindings, bindingContext); 5664 } 5665 }); 5666 } 5667 } 5668 })(); 5669 5670 5671 // Exported only because it has to be referenced by string lookup from within rewritten template 5672 ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling); 5673 (function () { 5674 // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving 5675 // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.) 5676 // 5677 // Two are provided by default: 5678 // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element 5679 // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but 5680 // without reading/writing the actual element text content, since it will be overwritten 5681 // with the rendered template output. 5682 // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements. 5683 // Template sources need to have the following functions: 5684 // text() - returns the template text from your storage location 5685 // text(value) - writes the supplied template text to your storage location 5686 // data(key) - reads values stored using data(key, value) - see below 5687 // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten". 5688 // 5689 // Optionally, template sources can also have the following functions: 5690 // nodes() - returns a DOM element containing the nodes of this template, where available 5691 // nodes(value) - writes the given DOM element to your storage location 5692 // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text() 5693 // for improved speed. However, all templateSources must supply text() even if they don't supply nodes(). 5694 // 5695 // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were 5696 // using and overriding "makeTemplateSource" to return an instance of your custom template source. 5697 5698 ko.templateSources = {}; 5699 5700 // ---- ko.templateSources.domElement ----- 5701 5702 // template types 5703 var templateScript = 1, 5704 templateTextArea = 2, 5705 templateTemplate = 3, 5706 templateElement = 4; 5707 5708 ko.templateSources.domElement = function (element) { 5709 this.domElement = element; 5710 5711 if (element) { 5712 var tagNameLower = ko.utils.tagNameLower(element); 5713 this.templateType = 5714 tagNameLower === "script" ? templateScript : 5715 tagNameLower === "textarea" ? templateTextArea : 5716 // For browsers with proper <template> element support, where the .content property gives a document fragment 5717 tagNameLower == "template" && element.content && element.content.nodeType === 11 ? templateTemplate : 5718 templateElement; 5719 } 5720 } 5721 5722 ko.templateSources.domElement.prototype['text'] = function (/* valueToWrite */) { 5723 var elemContentsProperty = this.templateType === templateScript ? "text" 5724 : this.templateType === templateTextArea ? "value" 5725 : "innerHTML"; 5726 5727 if (arguments.length == 0) { 5728 return this.domElement[elemContentsProperty]; 5729 } else { 5730 var valueToWrite = arguments[0]; 5731 if (elemContentsProperty === "innerHTML") 5732 ko.utils.setHtml(this.domElement, valueToWrite); 5733 else 5734 this.domElement[elemContentsProperty] = valueToWrite; 5735 } 5736 }; 5737 5738 var dataDomDataPrefix = ko.utils.domData.nextKey() + "_"; 5739 ko.templateSources.domElement.prototype['data'] = function (key /*, valueToWrite */) { 5740 if (arguments.length === 1) { 5741 return ko.utils.domData.get(this.domElement, dataDomDataPrefix + key); 5742 } else { 5743 ko.utils.domData.set(this.domElement, dataDomDataPrefix + key, arguments[1]); 5744 } 5745 }; 5746 5747 var templatesDomDataKey = ko.utils.domData.nextKey(); 5748 function getTemplateDomData(element) { 5749 return ko.utils.domData.get(element, templatesDomDataKey) || {}; 5750 } 5751 function setTemplateDomData(element, data) { 5752 ko.utils.domData.set(element, templatesDomDataKey, data); 5753 } 5754 5755 ko.templateSources.domElement.prototype['nodes'] = function (/* valueToWrite */) { 5756 var element = this.domElement; 5757 if (arguments.length == 0) { 5758 var templateData = getTemplateDomData(element), 5759 nodes = templateData.containerData || ( 5760 this.templateType === templateTemplate ? element.content : 5761 this.templateType === templateElement ? element : 5762 undefined); 5763 if (!nodes || templateData.alwaysCheckText) { 5764 // If the template is associated with an element that stores the template as text, 5765 // parse and cache the nodes whenever there's new text content available. This allows 5766 // the user to update the template content by updating the text of template node. 5767 var text = this['text'](); 5768 if (text && text !== templateData.textData) { 5769 nodes = ko.utils.parseHtmlForTemplateNodes(text, element.ownerDocument); 5770 setTemplateDomData(element, { containerData: nodes, textData: text, alwaysCheckText: true }); 5771 } 5772 } 5773 return nodes; 5774 } else { 5775 var valueToWrite = arguments[0]; 5776 if (this.templateType !== undefined) { 5777 this['text'](""); // clear the text from the node 5778 } 5779 setTemplateDomData(element, { containerData: valueToWrite }); 5780 } 5781 }; 5782 5783 // ---- ko.templateSources.anonymousTemplate ----- 5784 // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes". 5785 // For compatibility, you can also read "text"; it will be serialized from the nodes on demand. 5786 // Writing to "text" is still supported, but then the template data will not be available as DOM nodes. 5787 5788 ko.templateSources.anonymousTemplate = function (element) { 5789 this.domElement = element; 5790 } 5791 ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement(); 5792 ko.templateSources.anonymousTemplate.prototype.constructor = ko.templateSources.anonymousTemplate; 5793 ko.templateSources.anonymousTemplate.prototype['text'] = function (/* valueToWrite */) { 5794 if (arguments.length == 0) { 5795 var templateData = getTemplateDomData(this.domElement); 5796 if (templateData.textData === undefined && templateData.containerData) 5797 templateData.textData = templateData.containerData.innerHTML; 5798 return templateData.textData; 5799 } else { 5800 var valueToWrite = arguments[0]; 5801 setTemplateDomData(this.domElement, { textData: valueToWrite }); 5802 } 5803 }; 5804 5805 ko.exportSymbol('templateSources', ko.templateSources); 5806 ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement); 5807 ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate); 5808 })(); 5809 (function () { 5810 var _templateEngine; 5811 ko.setTemplateEngine = function (templateEngine) { 5812 if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine)) 5813 throw new Error("templateEngine must inherit from ko.templateEngine"); 5814 _templateEngine = templateEngine; 5815 } 5816 5817 function invokeForEachNodeInContinuousRange(firstNode, lastNode, action) { 5818 var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode); 5819 while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) { 5820 nextInQueue = ko.virtualElements.nextSibling(node); 5821 action(node, nextInQueue); 5822 } 5823 } 5824 5825 function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) { 5826 // To be used on any nodes that have been rendered by a template and have been inserted into some parent element 5827 // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because 5828 // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense, 5829 // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings 5830 // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting) 5831 5832 if (continuousNodeArray.length) { 5833 var firstNode = continuousNodeArray[0], 5834 lastNode = continuousNodeArray[continuousNodeArray.length - 1], 5835 parentNode = firstNode.parentNode, 5836 provider = ko.bindingProvider['instance'], 5837 preprocessNode = provider['preprocessNode']; 5838 5839 if (preprocessNode) { 5840 invokeForEachNodeInContinuousRange(firstNode, lastNode, function (node, nextNodeInRange) { 5841 var nodePreviousSibling = node.previousSibling; 5842 var newNodes = preprocessNode.call(provider, node); 5843 if (newNodes) { 5844 if (node === firstNode) 5845 firstNode = newNodes[0] || nextNodeInRange; 5846 if (node === lastNode) 5847 lastNode = newNodes[newNodes.length - 1] || nodePreviousSibling; 5848 } 5849 }); 5850 5851 // Because preprocessNode can change the nodes, including the first and last nodes, update continuousNodeArray to match. 5852 // We need the full set, including inner nodes, because the unmemoize step might remove the first node (and so the real 5853 // first node needs to be in the array). 5854 continuousNodeArray.length = 0; 5855 if (!firstNode) { // preprocessNode might have removed all the nodes, in which case there's nothing left to do 5856 return; 5857 } 5858 if (firstNode === lastNode) { 5859 continuousNodeArray.push(firstNode); 5860 } else { 5861 continuousNodeArray.push(firstNode, lastNode); 5862 ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode); 5863 } 5864 } 5865 5866 // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind) 5867 // whereas a regular applyBindings won't introduce new memoized nodes 5868 invokeForEachNodeInContinuousRange(firstNode, lastNode, function (node) { 5869 if (node.nodeType === 1 || node.nodeType === 8) 5870 ko.applyBindings(bindingContext, node); 5871 }); 5872 invokeForEachNodeInContinuousRange(firstNode, lastNode, function (node) { 5873 if (node.nodeType === 1 || node.nodeType === 8) 5874 ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]); 5875 }); 5876 5877 // Make sure any changes done by applyBindings or unmemoize are reflected in the array 5878 ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode); 5879 } 5880 } 5881 5882 function getFirstNodeFromPossibleArray(nodeOrNodeArray) { 5883 return nodeOrNodeArray.nodeType ? nodeOrNodeArray 5884 : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0] 5885 : null; 5886 } 5887 5888 function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) { 5889 options = options || {}; 5890 var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray); 5891 var templateDocument = (firstTargetNode || template || {}).ownerDocument; 5892 var templateEngineToUse = (options['templateEngine'] || _templateEngine); 5893 ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument); 5894 var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument); 5895 5896 // Loosely check result is an array of DOM nodes 5897 if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number")) 5898 throw new Error("Template engine must return an array of DOM nodes"); 5899 5900 var haveAddedNodesToParent = false; 5901 switch (renderMode) { 5902 case "replaceChildren": 5903 ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray); 5904 haveAddedNodesToParent = true; 5905 break; 5906 case "replaceNode": 5907 ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray); 5908 haveAddedNodesToParent = true; 5909 break; 5910 case "ignoreTargetNode": break; 5911 default: 5912 throw new Error("Unknown renderMode: " + renderMode); 5913 } 5914 5915 if (haveAddedNodesToParent) { 5916 activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext); 5917 if (options['afterRender']) { 5918 ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext[options['as'] || '$data']]); 5919 } 5920 if (renderMode == "replaceChildren") { 5921 ko.bindingEvent.notify(targetNodeOrNodeArray, ko.bindingEvent.childrenComplete); 5922 } 5923 } 5924 5925 return renderedNodesArray; 5926 } 5927 5928 function resolveTemplateName(template, data, context) { 5929 // The template can be specified as: 5930 if (ko.isObservable(template)) { 5931 // 1. An observable, with string value 5932 return template(); 5933 } else if (typeof template === 'function') { 5934 // 2. A function of (data, context) returning a string 5935 return template(data, context); 5936 } else { 5937 // 3. A string 5938 return template; 5939 } 5940 } 5941 5942 ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) { 5943 options = options || {}; 5944 if ((options['templateEngine'] || _templateEngine) == undefined) 5945 throw new Error("Set a template engine before calling renderTemplate"); 5946 renderMode = renderMode || "replaceChildren"; 5947 5948 if (targetNodeOrNodeArray) { 5949 var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray); 5950 5951 var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation) 5952 var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode; 5953 5954 return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes 5955 function () { 5956 // Ensure we've got a proper binding context to work with 5957 var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext)) 5958 ? dataOrBindingContext 5959 : new ko.bindingContext(dataOrBindingContext, null, null, null, { "exportDependencies": true }); 5960 5961 var templateName = resolveTemplateName(template, bindingContext['$data'], bindingContext), 5962 renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options); 5963 5964 if (renderMode == "replaceNode") { 5965 targetNodeOrNodeArray = renderedNodesArray; 5966 firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray); 5967 } 5968 }, 5969 null, 5970 { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved } 5971 ); 5972 } else { 5973 // 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 5974 return ko.memoization.memoize(function (domNode) { 5975 ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode"); 5976 }); 5977 } 5978 }; 5979 5980 ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) { 5981 // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then 5982 // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter. 5983 var arrayItemContext, asName = options['as']; 5984 5985 // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode 5986 var executeTemplateForArrayItem = function (arrayValue, index) { 5987 // Support selecting template as a function of the data being rendered 5988 arrayItemContext = parentBindingContext['createChildContext'](arrayValue, { 5989 'as': asName, 5990 'noChildContext': options['noChildContext'], 5991 'extend': function (context) { 5992 context['$index'] = index; 5993 if (asName) { 5994 context[asName + "Index"] = index; 5995 } 5996 } 5997 }); 5998 5999 var templateName = resolveTemplateName(template, arrayValue, arrayItemContext); 6000 return executeTemplate(targetNode, "ignoreTargetNode", templateName, arrayItemContext, options); 6001 }; 6002 6003 // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode 6004 var activateBindingsCallback = function (arrayValue, addedNodesArray, index) { 6005 activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext); 6006 if (options['afterRender']) 6007 options['afterRender'](addedNodesArray, arrayValue); 6008 6009 // release the "cache" variable, so that it can be collected by 6010 // the GC when its value isn't used from within the bindings anymore. 6011 arrayItemContext = null; 6012 }; 6013 6014 var setDomNodeChildrenFromArrayMapping = function (newArray, changeList) { 6015 // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function). 6016 // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping. 6017 ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, newArray, executeTemplateForArrayItem, options, activateBindingsCallback, changeList]); 6018 ko.bindingEvent.notify(targetNode, ko.bindingEvent.childrenComplete); 6019 }; 6020 6021 var shouldHideDestroyed = (options['includeDestroyed'] === false) || (ko.options['foreachHidesDestroyed'] && !options['includeDestroyed']); 6022 6023 if (!shouldHideDestroyed && !options['beforeRemove'] && ko.isObservableArray(arrayOrObservableArray)) { 6024 setDomNodeChildrenFromArrayMapping(arrayOrObservableArray.peek()); 6025 6026 var subscription = arrayOrObservableArray.subscribe(function (changeList) { 6027 setDomNodeChildrenFromArrayMapping(arrayOrObservableArray(), changeList); 6028 }, null, "arrayChange"); 6029 subscription.disposeWhenNodeIsRemoved(targetNode); 6030 6031 return subscription; 6032 } else { 6033 return ko.dependentObservable(function () { 6034 var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || []; 6035 if (typeof unwrappedArray.length == "undefined") // Coerce single value into array 6036 unwrappedArray = [unwrappedArray]; 6037 6038 if (shouldHideDestroyed) { 6039 // Filter out any entries marked as destroyed 6040 unwrappedArray = ko.utils.arrayFilter(unwrappedArray, function (item) { 6041 return item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']); 6042 }); 6043 } 6044 setDomNodeChildrenFromArrayMapping(unwrappedArray); 6045 6046 }, null, { disposeWhenNodeIsRemoved: targetNode }); 6047 } 6048 }; 6049 6050 var templateComputedDomDataKey = ko.utils.domData.nextKey(); 6051 function disposeOldComputedAndStoreNewOne(element, newComputed) { 6052 var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey); 6053 if (oldComputed && (typeof (oldComputed.dispose) == 'function')) 6054 oldComputed.dispose(); 6055 ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && (!newComputed.isActive || newComputed.isActive())) ? newComputed : undefined); 6056 } 6057 6058 var cleanContainerDomDataKey = ko.utils.domData.nextKey(); 6059 ko.bindingHandlers['template'] = { 6060 'init': function (element, valueAccessor) { 6061 // Support anonymous templates 6062 var bindingValue = ko.utils.unwrapObservable(valueAccessor()); 6063 if (typeof bindingValue == "string" || 'name' in bindingValue) { 6064 // It's a named template - clear the element 6065 ko.virtualElements.emptyNode(element); 6066 } else if ('nodes' in bindingValue) { 6067 // We've been given an array of DOM nodes. Save them as the template source. 6068 // There is no known use case for the node array being an observable array (if the output 6069 // varies, put that behavior *into* your template - that's what templates are for), and 6070 // the implementation would be a mess, so assert that it's not observable. 6071 var nodes = bindingValue['nodes'] || []; 6072 if (ko.isObservable(nodes)) { 6073 throw new Error('The "nodes" option must be a plain, non-observable array.'); 6074 } 6075 6076 // If the nodes are already attached to a KO-generated container, we reuse that container without moving the 6077 // elements to a new one (we check only the first node, as the nodes are always moved together) 6078 var container = nodes[0] && nodes[0].parentNode; 6079 if (!container || !ko.utils.domData.get(container, cleanContainerDomDataKey)) { 6080 container = ko.utils.moveCleanedNodesToContainerElement(nodes); 6081 ko.utils.domData.set(container, cleanContainerDomDataKey, true); 6082 } 6083 6084 new ko.templateSources.anonymousTemplate(element)['nodes'](container); 6085 } else { 6086 // It's an anonymous template - store the element contents, then clear the element 6087 var templateNodes = ko.virtualElements.childNodes(element); 6088 if (templateNodes.length > 0) { 6089 var container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent 6090 new ko.templateSources.anonymousTemplate(element)['nodes'](container); 6091 } else { 6092 throw new Error("Anonymous template defined, but no template content was provided"); 6093 } 6094 } 6095 return { 'controlsDescendantBindings': true }; 6096 }, 6097 'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) { 6098 var value = valueAccessor(), 6099 options = ko.utils.unwrapObservable(value), 6100 shouldDisplay = true, 6101 templateComputed = null, 6102 template; 6103 6104 if (typeof options == "string") { 6105 template = value; 6106 options = {}; 6107 } else { 6108 template = 'name' in options ? options['name'] : element; 6109 6110 // Support "if"/"ifnot" conditions 6111 if ('if' in options) 6112 shouldDisplay = ko.utils.unwrapObservable(options['if']); 6113 if (shouldDisplay && 'ifnot' in options) 6114 shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']); 6115 6116 // Don't show anything if an empty name is given (see #2446) 6117 if (shouldDisplay && !template) { 6118 shouldDisplay = false; 6119 } 6120 } 6121 6122 if ('foreach' in options) { 6123 // Render once for each data point (treating data set as empty if shouldDisplay==false) 6124 var dataArray = (shouldDisplay && options['foreach']) || []; 6125 templateComputed = ko.renderTemplateForEach(template, dataArray, options, element, bindingContext); 6126 } else if (!shouldDisplay) { 6127 ko.virtualElements.emptyNode(element); 6128 } else { 6129 // Render once for this single data point (or use the viewModel if no data was provided) 6130 var innerBindingContext = bindingContext; 6131 if ('data' in options) { 6132 innerBindingContext = bindingContext['createChildContext'](options['data'], { 6133 'as': options['as'], 6134 'noChildContext': options['noChildContext'], 6135 'exportDependencies': true 6136 }); 6137 } 6138 templateComputed = ko.renderTemplate(template, innerBindingContext, options, element); 6139 } 6140 6141 // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?) 6142 disposeOldComputedAndStoreNewOne(element, templateComputed); 6143 } 6144 }; 6145 6146 // Anonymous templates can't be rewritten. Give a nice error message if you try to do it. 6147 ko.expressionRewriting.bindingRewriteValidators['template'] = function (bindingValue) { 6148 var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue); 6149 6150 if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown']) 6151 return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting) 6152 6153 if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name")) 6154 return null; // Named templates can be rewritten, so return "no error" 6155 return "This template engine does not support anonymous templates nested within its templates"; 6156 }; 6157 6158 ko.virtualElements.allowedBindings['template'] = true; 6159 })(); 6160 6161 ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine); 6162 ko.exportSymbol('renderTemplate', ko.renderTemplate); 6163 // Go through the items that have been added and deleted and try to find matches between them. 6164 ko.utils.findMovesInArrayComparison = function (left, right, limitFailedCompares) { 6165 if (left.length && right.length) { 6166 var failedCompares, l, r, leftItem, rightItem; 6167 for (failedCompares = l = 0; (!limitFailedCompares || failedCompares < limitFailedCompares) && (leftItem = left[l]); ++l) { 6168 for (r = 0; rightItem = right[r]; ++r) { 6169 if (leftItem['value'] === rightItem['value']) { 6170 leftItem['moved'] = rightItem['index']; 6171 rightItem['moved'] = leftItem['index']; 6172 right.splice(r, 1); // This item is marked as moved; so remove it from right list 6173 failedCompares = r = 0; // Reset failed compares count because we're checking for consecutive failures 6174 break; 6175 } 6176 } 6177 failedCompares += r; 6178 } 6179 } 6180 }; 6181 6182 ko.utils.compareArrays = (function () { 6183 var statusNotInOld = 'added', statusNotInNew = 'deleted'; 6184 6185 // Simple calculation based on Levenshtein distance. 6186 function compareArrays(oldArray, newArray, options) { 6187 // For backward compatibility, if the third arg is actually a bool, interpret 6188 // it as the old parameter 'dontLimitMoves'. Newer code should use { dontLimitMoves: true }. 6189 options = (typeof options === 'boolean') ? { 'dontLimitMoves': options } : (options || {}); 6190 oldArray = oldArray || []; 6191 newArray = newArray || []; 6192 6193 if (oldArray.length < newArray.length) 6194 return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, options); 6195 else 6196 return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, options); 6197 } 6198 6199 function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, options) { 6200 var myMin = Math.min, 6201 myMax = Math.max, 6202 editDistanceMatrix = [], 6203 smlIndex, smlIndexMax = smlArray.length, 6204 bigIndex, bigIndexMax = bigArray.length, 6205 compareRange = (bigIndexMax - smlIndexMax) || 1, 6206 maxDistance = smlIndexMax + bigIndexMax + 1, 6207 thisRow, lastRow, 6208 bigIndexMaxForRow, bigIndexMinForRow; 6209 6210 for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) { 6211 lastRow = thisRow; 6212 editDistanceMatrix.push(thisRow = []); 6213 bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange); 6214 bigIndexMinForRow = myMax(0, smlIndex - 1); 6215 for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) { 6216 if (!bigIndex) 6217 thisRow[bigIndex] = smlIndex + 1; 6218 else if (!smlIndex) // Top row - transform empty array into new array via additions 6219 thisRow[bigIndex] = bigIndex + 1; 6220 else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1]) 6221 thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit) 6222 else { 6223 var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion) 6224 var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition) 6225 thisRow[bigIndex] = myMin(northDistance, westDistance) + 1; 6226 } 6227 } 6228 } 6229 6230 var editScript = [], meMinusOne, notInSml = [], notInBig = []; 6231 for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) { 6232 meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1; 6233 if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex - 1]) { 6234 notInSml.push(editScript[editScript.length] = { // added 6235 'status': statusNotInSml, 6236 'value': bigArray[--bigIndex], 6237 'index': bigIndex 6238 }); 6239 } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) { 6240 notInBig.push(editScript[editScript.length] = { // deleted 6241 'status': statusNotInBig, 6242 'value': smlArray[--smlIndex], 6243 'index': smlIndex 6244 }); 6245 } else { 6246 --bigIndex; 6247 --smlIndex; 6248 if (!options['sparse']) { 6249 editScript.push({ 6250 'status': "retained", 6251 'value': bigArray[bigIndex] 6252 }); 6253 } 6254 } 6255 } 6256 6257 // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of 6258 // smlIndexMax keeps the time complexity of this algorithm linear. 6259 ko.utils.findMovesInArrayComparison(notInBig, notInSml, !options['dontLimitMoves'] && smlIndexMax * 10); 6260 6261 return editScript.reverse(); 6262 } 6263 6264 return compareArrays; 6265 })(); 6266 6267 ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays); 6268 (function () { 6269 // Objective: 6270 // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes, 6271 // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node 6272 // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node 6273 // 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 6274 // previously mapped - retain those nodes, and just insert/delete other ones 6275 6276 // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node 6277 // You can use this, for example, to activate bindings on those nodes. 6278 6279 function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) { 6280 // Map this array value inside a dependentObservable so we re-map when any dependency changes 6281 var mappedNodes = []; 6282 var dependentObservable = ko.dependentObservable(function () { 6283 var newMappedNodes = mapping(valueToMap, index, ko.utils.fixUpContinuousNodeArray(mappedNodes, containerNode)) || []; 6284 6285 // On subsequent evaluations, just replace the previously-inserted DOM nodes 6286 if (mappedNodes.length > 0) { 6287 ko.utils.replaceDomNodes(mappedNodes, newMappedNodes); 6288 if (callbackAfterAddingNodes) 6289 ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]); 6290 } 6291 6292 // Replace the contents of the mappedNodes array, thereby updating the record 6293 // of which nodes would be deleted if valueToMap was itself later removed 6294 mappedNodes.length = 0; 6295 ko.utils.arrayPushAll(mappedNodes, newMappedNodes); 6296 }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function () { return !ko.utils.anyDomNodeIsAttachedToDocument(mappedNodes); } }); 6297 return { mappedNodes: mappedNodes, dependentObservable: (dependentObservable.isActive() ? dependentObservable : undefined) }; 6298 } 6299 6300 var lastMappingResultDomDataKey = ko.utils.domData.nextKey(), 6301 deletedItemDummyValue = ko.utils.domData.nextKey(); 6302 6303 ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes, editScript) { 6304 array = array || []; 6305 if (typeof array.length == "undefined") // Coerce single value into array 6306 array = [array]; 6307 6308 options = options || {}; 6309 var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey); 6310 var isFirstExecution = !lastMappingResult; 6311 6312 // Build the new mapping result 6313 var newMappingResult = []; 6314 var lastMappingResultIndex = 0; 6315 var currentArrayIndex = 0; 6316 6317 var nodesToDelete = []; 6318 var itemsToMoveFirstIndexes = []; 6319 var itemsForBeforeRemoveCallbacks = []; 6320 var itemsForMoveCallbacks = []; 6321 var itemsForAfterAddCallbacks = []; 6322 var mapData; 6323 var countWaitingForRemove = 0; 6324 6325 function itemAdded(value) { 6326 mapData = { arrayEntry: value, indexObservable: ko.observable(currentArrayIndex++) }; 6327 newMappingResult.push(mapData); 6328 if (!isFirstExecution) { 6329 itemsForAfterAddCallbacks.push(mapData); 6330 } 6331 } 6332 6333 function itemMovedOrRetained(oldPosition) { 6334 mapData = lastMappingResult[oldPosition]; 6335 if (currentArrayIndex !== mapData.indexObservable.peek()) 6336 itemsForMoveCallbacks.push(mapData); 6337 // Since updating the index might change the nodes, do so before calling fixUpContinuousNodeArray 6338 mapData.indexObservable(currentArrayIndex++); 6339 ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode); 6340 newMappingResult.push(mapData); 6341 } 6342 6343 function callCallback(callback, items) { 6344 if (callback) { 6345 for (var i = 0, n = items.length; i < n; i++) { 6346 ko.utils.arrayForEach(items[i].mappedNodes, function (node) { 6347 callback(node, i, items[i].arrayEntry); 6348 }); 6349 } 6350 } 6351 } 6352 6353 if (isFirstExecution) { 6354 ko.utils.arrayForEach(array, itemAdded); 6355 } else { 6356 if (!editScript || (lastMappingResult && lastMappingResult['_countWaitingForRemove'])) { 6357 // Compare the provided array against the previous one 6358 var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; }), 6359 compareOptions = { 6360 'dontLimitMoves': options['dontLimitMoves'], 6361 'sparse': true 6362 }; 6363 editScript = ko.utils.compareArrays(lastArray, array, compareOptions); 6364 } 6365 6366 for (var i = 0, editScriptItem, movedIndex, itemIndex; editScriptItem = editScript[i]; i++) { 6367 movedIndex = editScriptItem['moved']; 6368 itemIndex = editScriptItem['index']; 6369 switch (editScriptItem['status']) { 6370 case "deleted": 6371 while (lastMappingResultIndex < itemIndex) { 6372 itemMovedOrRetained(lastMappingResultIndex++); 6373 } 6374 if (movedIndex === undefined) { 6375 mapData = lastMappingResult[lastMappingResultIndex]; 6376 6377 // Stop tracking changes to the mapping for these nodes 6378 if (mapData.dependentObservable) { 6379 mapData.dependentObservable.dispose(); 6380 mapData.dependentObservable = undefined; 6381 } 6382 6383 // Queue these nodes for later removal 6384 if (ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode).length) { 6385 if (options['beforeRemove']) { 6386 newMappingResult.push(mapData); 6387 countWaitingForRemove++; 6388 if (mapData.arrayEntry === deletedItemDummyValue) { 6389 mapData = null; 6390 } else { 6391 itemsForBeforeRemoveCallbacks.push(mapData); 6392 } 6393 } 6394 if (mapData) { 6395 nodesToDelete.push.apply(nodesToDelete, mapData.mappedNodes); 6396 } 6397 } 6398 } 6399 lastMappingResultIndex++; 6400 break; 6401 6402 case "added": 6403 while (currentArrayIndex < itemIndex) { 6404 itemMovedOrRetained(lastMappingResultIndex++); 6405 } 6406 if (movedIndex !== undefined) { 6407 itemsToMoveFirstIndexes.push(newMappingResult.length); 6408 itemMovedOrRetained(movedIndex); 6409 } else { 6410 itemAdded(editScriptItem['value']); 6411 } 6412 break; 6413 } 6414 } 6415 6416 while (currentArrayIndex < array.length) { 6417 itemMovedOrRetained(lastMappingResultIndex++); 6418 } 6419 6420 // Record that the current view may still contain deleted items 6421 // because it means we won't be able to use a provided editScript. 6422 newMappingResult['_countWaitingForRemove'] = countWaitingForRemove; 6423 } 6424 6425 // Store a copy of the array items we just considered so we can difference it next time 6426 ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult); 6427 6428 // Call beforeMove first before any changes have been made to the DOM 6429 callCallback(options['beforeMove'], itemsForMoveCallbacks); 6430 6431 // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback) 6432 ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode); 6433 6434 var i, j, lastNode, nodeToInsert, mappedNodes, activeElement; 6435 6436 // Since most browsers remove the focus from an element when it's moved to another location, 6437 // save the focused element and try to restore it later. 6438 try { 6439 activeElement = domNode.ownerDocument.activeElement; 6440 } catch (e) { 6441 // IE9 throws if you access activeElement during page load (see issue #703) 6442 } 6443 6444 // Try to reduce overall moved nodes by first moving the ones that were marked as moved by the edit script 6445 if (itemsToMoveFirstIndexes.length) { 6446 while ((i = itemsToMoveFirstIndexes.shift()) != undefined) { 6447 mapData = newMappingResult[i]; 6448 for (lastNode = undefined; i;) { 6449 if ((mappedNodes = newMappingResult[--i].mappedNodes) && mappedNodes.length) { 6450 lastNode = mappedNodes[mappedNodes.length - 1]; 6451 break; 6452 } 6453 } 6454 for (j = 0; nodeToInsert = mapData.mappedNodes[j]; lastNode = nodeToInsert, j++) { 6455 ko.virtualElements.insertAfter(domNode, nodeToInsert, lastNode); 6456 } 6457 } 6458 } 6459 6460 // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback) 6461 for (i = 0; mapData = newMappingResult[i]; i++) { 6462 // Get nodes for newly added items 6463 if (!mapData.mappedNodes) 6464 ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable)); 6465 6466 // Put nodes in the right place if they aren't there already 6467 for (j = 0; nodeToInsert = mapData.mappedNodes[j]; lastNode = nodeToInsert, j++) { 6468 ko.virtualElements.insertAfter(domNode, nodeToInsert, lastNode); 6469 } 6470 6471 // Run the callbacks for newly added nodes (for example, to apply bindings, etc.) 6472 if (!mapData.initialized && callbackAfterAddingNodes) { 6473 callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable); 6474 mapData.initialized = true; 6475 lastNode = mapData.mappedNodes[mapData.mappedNodes.length - 1]; // get the last node again since it may have been changed by a preprocessor 6476 } 6477 } 6478 6479 // Restore the focused element if it had lost focus 6480 if (activeElement && domNode.ownerDocument.activeElement != activeElement) { 6481 activeElement.focus(); 6482 } 6483 6484 // If there's a beforeRemove callback, call it after reordering. 6485 // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using 6486 // some sort of animation, which is why we first reorder the nodes that will be removed. If the 6487 // callback instead removes the nodes right away, it would be more efficient to skip reordering them. 6488 // Perhaps we'll make that change in the future if this scenario becomes more common. 6489 callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks); 6490 6491 // Replace the stored values of deleted items with a dummy value. This provides two benefits: it marks this item 6492 // as already "removed" so we won't call beforeRemove for it again, and it ensures that the item won't match up 6493 // with an actual item in the array and appear as "retained" or "moved". 6494 for (i = 0; i < itemsForBeforeRemoveCallbacks.length; ++i) { 6495 itemsForBeforeRemoveCallbacks[i].arrayEntry = deletedItemDummyValue; 6496 } 6497 6498 // Finally call afterMove and afterAdd callbacks 6499 callCallback(options['afterMove'], itemsForMoveCallbacks); 6500 callCallback(options['afterAdd'], itemsForAfterAddCallbacks); 6501 } 6502 })(); 6503 6504 ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping); 6505 ko.nativeTemplateEngine = function () { 6506 this['allowTemplateRewriting'] = false; 6507 } 6508 6509 ko.nativeTemplateEngine.prototype = new ko.templateEngine(); 6510 ko.nativeTemplateEngine.prototype.constructor = ko.nativeTemplateEngine; 6511 ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options, templateDocument) { 6512 var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly 6513 templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null, 6514 templateNodes = templateNodesFunc ? templateSource['nodes']() : null; 6515 6516 if (templateNodes) { 6517 return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes); 6518 } else { 6519 var templateText = templateSource['text'](); 6520 return ko.utils.parseHtmlFragment(templateText, templateDocument); 6521 } 6522 }; 6523 6524 ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine(); 6525 ko.setTemplateEngine(ko.nativeTemplateEngine.instance); 6526 6527 ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine); 6528 (function () { 6529 ko.jqueryTmplTemplateEngine = function () { 6530 // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl 6531 // doesn't expose a version number, so we have to infer it. 6532 // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later, 6533 // which KO internally refers to as version "2", so older versions are no longer detected. 6534 var jQueryTmplVersion = this.jQueryTmplVersion = (function () { 6535 if (!jQueryInstance || !(jQueryInstance['tmpl'])) 6536 return 0; 6537 // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves. 6538 try { 6539 if (jQueryInstance['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) { 6540 // Since 1.0.0pre, custom tags should append markup to an array called "__" 6541 return 2; // Final version of jquery.tmpl 6542 } 6543 } catch (ex) { /* Apparently not the version we were looking for */ } 6544 6545 return 1; // Any older version that we don't support 6546 })(); 6547 6548 function ensureHasReferencedJQueryTemplates() { 6549 if (jQueryTmplVersion < 2) 6550 throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later."); 6551 } 6552 6553 function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) { 6554 return jQueryInstance['tmpl'](compiledTemplate, data, jQueryTemplateOptions); 6555 } 6556 6557 this['renderTemplateSource'] = function (templateSource, bindingContext, options, templateDocument) { 6558 templateDocument = templateDocument || document; 6559 options = options || {}; 6560 ensureHasReferencedJQueryTemplates(); 6561 6562 // Ensure we have stored a precompiled version of this template (don't want to reparse on every render) 6563 var precompiled = templateSource['data']('precompiled'); 6564 if (!precompiled) { 6565 var templateText = templateSource['text']() || ""; 6566 // Wrap in "with($whatever.koBindingContext) { ... }" 6567 templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}"; 6568 6569 precompiled = jQueryInstance['template'](null, templateText); 6570 templateSource['data']('precompiled', precompiled); 6571 } 6572 6573 var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays 6574 var jQueryTemplateOptions = jQueryInstance['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']); 6575 6576 var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions); 6577 resultNodes['appendTo'](templateDocument.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work 6578 6579 jQueryInstance['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders 6580 return resultNodes; 6581 }; 6582 6583 this['createJavaScriptEvaluatorBlock'] = function (script) { 6584 return "{{ko_code ((function() { return " + script + " })()) }}"; 6585 }; 6586 6587 this['addTemplate'] = function (templateName, templateMarkup) { 6588 document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "<" + "/script>"); 6589 }; 6590 6591 if (jQueryTmplVersion > 0) { 6592 jQueryInstance['tmpl']['tag']['ko_code'] = { 6593 open: "__.push($1 || '');" 6594 }; 6595 jQueryInstance['tmpl']['tag']['ko_with'] = { 6596 open: "with($1) {", 6597 close: "} " 6598 }; 6599 } 6600 }; 6601 6602 ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine(); 6603 ko.jqueryTmplTemplateEngine.prototype.constructor = ko.jqueryTmplTemplateEngine; 6604 6605 // Use this one by default *only if jquery.tmpl is referenced* 6606 var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine(); 6607 if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0) 6608 ko.setTemplateEngine(jqueryTmplTemplateEngineInstance); 6609 6610 ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine); 6611 })(); 6612 })); 6613 }()); 6614})();
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.