1 // Knockout JavaScript library v2.2.1
2 // (c) Steven Sanderson - http://knockoutjs.com/
3 // License: MIT (http://www.opensource.org/licenses/mit-license.php)
7 (function(window,document,navigator,jQuery,undefined){
9 // Support three module loading scenarios
10 if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
11 // [1] CommonJS/Node.js
12 var target = module['exports'] || exports; // module.exports is for Node.js
14 } else if (typeof define === 'function' && define['amd']) {
15 // [2] AMD anonymous module
16 define(['exports'], factory);
18 // [3] No module loader (plain <script> tag) - put directly in global namespace
19 factory(window['ko'] = {});
21 }(function(koExports){
22 // Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
23 // In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
24 var ko = typeof koExports !== 'undefined' ? koExports : {};
25 // Google Closure Compiler helpers (used only to make the minified file smaller)
26 ko.exportSymbol = function(koPath, object) {
27 var tokens = koPath.split(".");
29 // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
30 // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
33 for (var i = 0; i < tokens.length - 1; i++)
34 target = target[tokens[i]];
35 target[tokens[tokens.length - 1]] = object;
37 ko.exportProperty = function(owner, publicName, object) {
38 owner[publicName] = object;
42 ko.exportSymbol('version', ko.version);
43 ko.utils = new (function () {
44 var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
46 // 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)
47 var knownEvents = {}, knownEventTypesByEventName = {};
48 var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';
49 knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
50 knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
51 for (var eventType in knownEvents) {
52 var knownEventsForType = knownEvents[eventType];
53 if (knownEventsForType.length) {
54 for (var i = 0, j = knownEventsForType.length; i < j; i++)
55 knownEventTypesByEventName[knownEventsForType[i]] = eventType;
58 var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
60 // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
61 // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
62 // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
63 // If there is a future need to detect specific versions of IE10+, we will amend this.
64 var ieVersion = (function() {
65 var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
67 // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
69 div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
72 return version > 4 ? version : undefined;
74 var isIe6 = ieVersion === 6,
75 isIe7 = ieVersion === 7;
77 function isClickOnCheckableElement(element, eventType) {
78 if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
79 if (eventType.toLowerCase() != "click") return false;
80 var inputType = element.type;
81 return (inputType == "checkbox") || (inputType == "radio");
85 fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
87 arrayForEach: function (array, action) {
88 for (var i = 0, j = array.length; i < j; i++)
92 arrayIndexOf: function (array, item) {
93 if (typeof Array.prototype.indexOf == "function")
94 return Array.prototype.indexOf.call(array, item);
95 for (var i = 0, j = array.length; i < j; i++)
96 if (array[i] === item)
101 arrayFirst: function (array, predicate, predicateOwner) {
102 for (var i = 0, j = array.length; i < j; i++)
103 if (predicate.call(predicateOwner, array[i]))
108 arrayRemoveItem: function (array, itemToRemove) {
109 var index = ko.utils.arrayIndexOf(array, itemToRemove);
111 array.splice(index, 1);
114 arrayGetDistinctValues: function (array) {
117 for (var i = 0, j = array.length; i < j; i++) {
118 if (ko.utils.arrayIndexOf(result, array[i]) < 0)
119 result.push(array[i]);
124 arrayMap: function (array, mapping) {
127 for (var i = 0, j = array.length; i < j; i++)
128 result.push(mapping(array[i]));
132 arrayFilter: function (array, predicate) {
135 for (var i = 0, j = array.length; i < j; i++)
136 if (predicate(array[i]))
137 result.push(array[i]);
141 arrayPushAll: function (array, valuesToPush) {
142 if (valuesToPush instanceof Array)
143 array.push.apply(array, valuesToPush);
145 for (var i = 0, j = valuesToPush.length; i < j; i++)
146 array.push(valuesToPush[i]);
150 extend: function (target, source) {
152 for(var prop in source) {
153 if(source.hasOwnProperty(prop)) {
154 target[prop] = source[prop];
161 emptyDomNode: function (domNode) {
162 while (domNode.firstChild) {
163 ko.removeNode(domNode.firstChild);
167 moveCleanedNodesToContainerElement: function(nodes) {
168 // Ensure it's a real array, as we're about to reparent the nodes and
169 // we don't want the underlying collection to change while we're doing that.
170 var nodesArray = ko.utils.makeArray(nodes);
172 var container = document.createElement('div');
173 for (var i = 0, j = nodesArray.length; i < j; i++) {
174 container.appendChild(ko.cleanNode(nodesArray[i]));
179 cloneNodes: function (nodesArray, shouldCleanNodes) {
180 for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
181 var clonedNode = nodesArray[i].cloneNode(true);
182 newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
184 return newNodesArray;
187 setDomNodeChildren: function (domNode, childNodes) {
188 ko.utils.emptyDomNode(domNode);
190 for (var i = 0, j = childNodes.length; i < j; i++)
191 domNode.appendChild(childNodes[i]);
195 replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
196 var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
197 if (nodesToReplaceArray.length > 0) {
198 var insertionPoint = nodesToReplaceArray[0];
199 var parent = insertionPoint.parentNode;
200 for (var i = 0, j = newNodesArray.length; i < j; i++)
201 parent.insertBefore(newNodesArray[i], insertionPoint);
202 for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
203 ko.removeNode(nodesToReplaceArray[i]);
208 setOptionNodeSelectionState: function (optionNode, isSelected) {
209 // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
211 optionNode.setAttribute("selected", isSelected);
213 optionNode.selected = isSelected;
216 stringTrim: function (string) {
217 return (string || "").replace(stringTrimRegex, "");
220 stringTokenize: function (string, delimiter) {
222 var tokens = (string || "").split(delimiter);
223 for (var i = 0, j = tokens.length; i < j; i++) {
224 var trimmed = ko.utils.stringTrim(tokens[i]);
226 result.push(trimmed);
231 stringStartsWith: function (string, startsWith) {
232 string = string || "";
233 if (startsWith.length > string.length)
235 return string.substring(0, startsWith.length) === startsWith;
238 domNodeIsContainedBy: function (node, containedByNode) {
239 if (containedByNode.compareDocumentPosition)
240 return (containedByNode.compareDocumentPosition(node) & 16) == 16;
241 while (node != null) {
242 if (node == containedByNode)
244 node = node.parentNode;
249 domNodeIsAttachedToDocument: function (node) {
250 return ko.utils.domNodeIsContainedBy(node, node.ownerDocument);
253 tagNameLower: function(element) {
254 // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
255 // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
256 // we don't need to do the .toLowerCase() as it will always be lower case anyway.
257 return element && element.tagName && element.tagName.toLowerCase();
260 registerEventHandler: function (element, eventType, handler) {
261 var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
262 if (!mustUseAttachEvent && typeof jQuery != "undefined") {
263 if (isClickOnCheckableElement(element, eventType)) {
264 // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
265 // it toggles the element checked state *after* the click event handlers run, whereas native
266 // click events toggle the checked state *before* the event handler.
267 // Fix this by intecepting the handler and applying the correct checkedness before it runs.
268 var originalHandler = handler;
269 handler = function(event, eventData) {
270 var jQuerySuppliedCheckedState = this.checked;
272 this.checked = eventData.checkedStateBeforeEvent !== true;
273 originalHandler.call(this, event);
274 this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
277 jQuery(element)['bind'](eventType, handler);
278 } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
279 element.addEventListener(eventType, handler, false);
280 else if (typeof element.attachEvent != "undefined")
281 element.attachEvent("on" + eventType, function (event) {
282 handler.call(element, event);
285 throw new Error("Browser doesn't support addEventListener or attachEvent");
288 triggerEvent: function (element, eventType) {
289 if (!(element && element.nodeType))
290 throw new Error("element must be a DOM node when calling triggerEvent");
292 if (typeof jQuery != "undefined") {
294 if (isClickOnCheckableElement(element, eventType)) {
295 // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
296 eventData.push({ checkedStateBeforeEvent: element.checked });
298 jQuery(element)['trigger'](eventType, eventData);
299 } else if (typeof document.createEvent == "function") {
300 if (typeof element.dispatchEvent == "function") {
301 var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
302 var event = document.createEvent(eventCategory);
303 event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
304 element.dispatchEvent(event);
307 throw new Error("The supplied element doesn't support dispatchEvent");
308 } else if (typeof element.fireEvent != "undefined") {
309 // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
310 // so to make it consistent, we'll do it manually here
311 if (isClickOnCheckableElement(element, eventType))
312 element.checked = element.checked !== true;
313 element.fireEvent("on" + eventType);
316 throw new Error("Browser doesn't support triggering events");
319 unwrapObservable: function (value) {
320 return ko.isObservable(value) ? value() : value;
323 peekObservable: function (value) {
324 return ko.isObservable(value) ? value.peek() : value;
327 toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
329 var cssClassNameRegex = /[\w-]+/g,
330 currentClassNames = node.className.match(cssClassNameRegex) || [];
331 ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
332 var indexOfClass = ko.utils.arrayIndexOf(currentClassNames, className);
333 if (indexOfClass >= 0) {
334 if (!shouldHaveClass)
335 currentClassNames.splice(indexOfClass, 1);
338 currentClassNames.push(className);
341 node.className = currentClassNames.join(" ");
345 setTextContent: function(element, textContent) {
346 var value = ko.utils.unwrapObservable(textContent);
347 if ((value === null) || (value === undefined))
350 if (element.nodeType === 3) {
351 element.data = value;
353 // We need there to be exactly one child: a text node.
354 // If there are no children, more than one, or if it's not a text node,
355 // we'll clear everything and create a single text node.
356 var innerTextNode = ko.virtualElements.firstChild(element);
357 if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
358 ko.virtualElements.setDomNodeChildren(element, [document.createTextNode(value)]);
360 innerTextNode.data = value;
363 ko.utils.forceRefresh(element);
367 setElementName: function(element, name) {
370 // Workaround IE 6/7 issue
371 // - https://github.com/SteveSanderson/knockout/issues/197
372 // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
373 if (ieVersion <= 7) {
375 element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
377 catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
381 forceRefresh: function(node) {
382 // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
383 if (ieVersion >= 9) {
384 // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
385 var elem = node.nodeType == 1 ? node : node.parentNode;
387 elem.style.zoom = elem.style.zoom;
391 ensureSelectElementIsRenderedCorrectly: function(selectElement) {
392 // 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.
393 // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
394 if (ieVersion >= 9) {
395 var originalWidth = selectElement.style.width;
396 selectElement.style.width = 0;
397 selectElement.style.width = originalWidth;
401 range: function (min, max) {
402 min = ko.utils.unwrapObservable(min);
403 max = ko.utils.unwrapObservable(max);
405 for (var i = min; i <= max; i++)
410 makeArray: function(arrayLikeObject) {
412 for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
413 result.push(arrayLikeObject[i]);
420 ieVersion : ieVersion,
422 getFormFields: function(form, fieldName) {
423 var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
424 var isMatchingField = (typeof fieldName == 'string')
425 ? function(field) { return field.name === fieldName }
426 : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
428 for (var i = fields.length - 1; i >= 0; i--) {
429 if (isMatchingField(fields[i]))
430 matches.push(fields[i]);
435 parseJson: function (jsonString) {
436 if (typeof jsonString == "string") {
437 jsonString = ko.utils.stringTrim(jsonString);
439 if (window.JSON && window.JSON.parse) // Use native parsing where available
440 return window.JSON.parse(jsonString);
441 return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
447 stringifyJson: function (data, replacer, space) { // replacer and space are optional
448 if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
449 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");
450 return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
453 postJson: function (urlOrForm, data, options) {
454 options = options || {};
455 var params = options['params'] || {};
456 var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
459 // If we were given a form, use its 'action' URL and pick out any requested field values
460 if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
461 var originalForm = urlOrForm;
462 url = originalForm.action;
463 for (var i = includeFields.length - 1; i >= 0; i--) {
464 var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
465 for (var j = fields.length - 1; j >= 0; j--)
466 params[fields[j].name] = fields[j].value;
470 data = ko.utils.unwrapObservable(data);
471 var form = document.createElement("form");
472 form.style.display = "none";
474 form.method = "post";
475 for (var key in data) {
476 var input = document.createElement("input");
478 input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
479 form.appendChild(input);
481 for (var key in params) {
482 var input = document.createElement("input");
484 input.value = params[key];
485 form.appendChild(input);
487 document.body.appendChild(form);
488 options['submitter'] ? options['submitter'](form) : form.submit();
489 setTimeout(function () { form.parentNode.removeChild(form); }, 0);
494 ko.exportSymbol('utils', ko.utils);
495 ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
496 ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
497 ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
498 ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
499 ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
500 ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
501 ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
502 ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
503 ko.exportSymbol('utils.extend', ko.utils.extend);
504 ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
505 ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
506 ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
507 ko.exportSymbol('utils.postJson', ko.utils.postJson);
508 ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
509 ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
510 ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
511 ko.exportSymbol('utils.range', ko.utils.range);
512 ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
513 ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
514 ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
516 if (!Function.prototype['bind']) {
517 // 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)
518 // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
519 Function.prototype['bind'] = function (object) {
520 var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
522 return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
527 ko.utils.domData = new (function () {
529 var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
532 get: function (node, key) {
533 var allDataForNode = ko.utils.domData.getAll(node, false);
534 return allDataForNode === undefined ? undefined : allDataForNode[key];
536 set: function (node, key, value) {
537 if (value === undefined) {
538 // Make sure we don't actually create a new domData key if we are actually deleting a value
539 if (ko.utils.domData.getAll(node, false) === undefined)
542 var allDataForNode = ko.utils.domData.getAll(node, true);
543 allDataForNode[key] = value;
545 getAll: function (node, createIfNotFound) {
546 var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
547 var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
548 if (!hasExistingDataStore) {
549 if (!createIfNotFound)
551 dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
552 dataStore[dataStoreKey] = {};
554 return dataStore[dataStoreKey];
556 clear: function (node) {
557 var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
559 delete dataStore[dataStoreKey];
560 node[dataStoreKeyExpandoPropertyName] = null;
561 return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
568 ko.exportSymbol('utils.domData', ko.utils.domData);
569 ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
571 ko.utils.domNodeDisposal = new (function () {
572 var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();
573 var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
574 var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
576 function getDisposeCallbacksCollection(node, createIfNotFound) {
577 var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
578 if ((allDisposeCallbacks === undefined) && createIfNotFound) {
579 allDisposeCallbacks = [];
580 ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
582 return allDisposeCallbacks;
584 function destroyCallbacksCollection(node) {
585 ko.utils.domData.set(node, domDataKey, undefined);
588 function cleanSingleNode(node) {
589 // Run all the dispose callbacks
590 var callbacks = getDisposeCallbacksCollection(node, false);
592 callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
593 for (var i = 0; i < callbacks.length; i++)
597 // Also erase the DOM data
598 ko.utils.domData.clear(node);
600 // Special support for jQuery here because it's so commonly used.
601 // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
602 // so notify it to tear down any resources associated with the node & descendants here.
603 if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
604 jQuery['cleanData']([node]);
606 // Also clear any immediate-child comment nodes, as these wouldn't have been found by
607 // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
608 if (cleanableNodeTypesWithDescendants[node.nodeType])
609 cleanImmediateCommentTypeChildren(node);
612 function cleanImmediateCommentTypeChildren(nodeWithChildren) {
613 var child, nextChild = nodeWithChildren.firstChild;
614 while (child = nextChild) {
615 nextChild = child.nextSibling;
616 if (child.nodeType === 8)
617 cleanSingleNode(child);
622 addDisposeCallback : function(node, callback) {
623 if (typeof callback != "function")
624 throw new Error("Callback must be a function");
625 getDisposeCallbacksCollection(node, true).push(callback);
628 removeDisposeCallback : function(node, callback) {
629 var callbacksCollection = getDisposeCallbacksCollection(node, false);
630 if (callbacksCollection) {
631 ko.utils.arrayRemoveItem(callbacksCollection, callback);
632 if (callbacksCollection.length == 0)
633 destroyCallbacksCollection(node);
637 cleanNode : function(node) {
638 // First clean this node, where applicable
639 if (cleanableNodeTypes[node.nodeType]) {
640 cleanSingleNode(node);
642 // ... then its descendants, where applicable
643 if (cleanableNodeTypesWithDescendants[node.nodeType]) {
644 // Clone the descendants list in case it changes during iteration
645 var descendants = [];
646 ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
647 for (var i = 0, j = descendants.length; i < j; i++)
648 cleanSingleNode(descendants[i]);
654 removeNode : function(node) {
657 node.parentNode.removeChild(node);
661 ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
662 ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
663 ko.exportSymbol('cleanNode', ko.cleanNode);
664 ko.exportSymbol('removeNode', ko.removeNode);
665 ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
666 ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
667 ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
669 var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
671 function simpleHtmlParse(html) {
672 // Based on jQuery's "clean" function, but only accounting for table-related elements.
673 // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
675 // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
676 // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
677 // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
678 // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
680 // Trim whitespace, otherwise indexOf won't work as expected
681 var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
683 // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
684 var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
685 !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
686 (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
687 /* anything else */ [0, "", ""];
689 // Go to html and back, then peel off extra wrappers
690 // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
691 var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
692 if (typeof window['innerShiv'] == "function") {
693 div.appendChild(window['innerShiv'](markup));
695 div.innerHTML = markup;
698 // Move to the right depth
702 return ko.utils.makeArray(div.lastChild.childNodes);
705 function jQueryHtmlParse(html) {
706 // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
707 if (jQuery['parseHTML']) {
708 return jQuery['parseHTML'](html);
710 // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
711 var elems = jQuery['clean']([html]);
713 // 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.
714 // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
715 // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
716 if (elems && elems[0]) {
717 // Find the top-most parent element that's a direct child of a document fragment
719 while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
720 elem = elem.parentNode;
721 // ... then detach it
723 elem.parentNode.removeChild(elem);
730 ko.utils.parseHtmlFragment = function(html) {
731 return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
732 : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
735 ko.utils.setHtml = function(node, html) {
736 ko.utils.emptyDomNode(node);
738 // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
739 html = ko.utils.unwrapObservable(html);
741 if ((html !== null) && (html !== undefined)) {
742 if (typeof html != 'string')
743 html = html.toString();
745 // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
746 // for example <tr> elements which are not normally allowed to exist on their own.
747 // If you've referenced jQuery we'll use that rather than duplicating its code.
748 if (typeof jQuery != 'undefined') {
749 jQuery(node)['html'](html);
751 // ... otherwise, use KO's own parsing logic.
752 var parsedNodes = ko.utils.parseHtmlFragment(html);
753 for (var i = 0; i < parsedNodes.length; i++)
754 node.appendChild(parsedNodes[i]);
760 ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
761 ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
763 ko.memoization = (function () {
766 function randomMax8HexChars() {
767 return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
769 function generateRandomId() {
770 return randomMax8HexChars() + randomMax8HexChars();
772 function findMemoNodes(rootNode, appendToArray) {
775 if (rootNode.nodeType == 8) {
776 var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
778 appendToArray.push({ domNode: rootNode, memoId: memoId });
779 } else if (rootNode.nodeType == 1) {
780 for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
781 findMemoNodes(childNodes[i], appendToArray);
786 memoize: function (callback) {
787 if (typeof callback != "function")
788 throw new Error("You can only pass a function to ko.memoization.memoize()");
789 var memoId = generateRandomId();
790 memos[memoId] = callback;
791 return "<!--[ko_memo:" + memoId + "]-->";
794 unmemoize: function (memoId, callbackParams) {
795 var callback = memos[memoId];
796 if (callback === undefined)
797 throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
799 callback.apply(null, callbackParams || []);
802 finally { delete memos[memoId]; }
805 unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
807 findMemoNodes(domNode, memos);
808 for (var i = 0, j = memos.length; i < j; i++) {
809 var node = memos[i].domNode;
810 var combinedParams = [node];
811 if (extraCallbackParamsArray)
812 ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
813 ko.memoization.unmemoize(memos[i].memoId, combinedParams);
814 node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
816 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)
820 parseMemoText: function (memoText) {
821 var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
822 return match ? match[1] : null;
827 ko.exportSymbol('memoization', ko.memoization);
828 ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
829 ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
830 ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
831 ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
833 'throttle': function(target, timeout) {
834 // Throttling means two things:
836 // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
837 // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
838 target['throttleEvaluation'] = timeout;
840 // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
841 // so the target cannot change value synchronously or faster than a certain rate
842 var writeTimeoutInstance = null;
843 return ko.dependentObservable({
845 'write': function(value) {
846 clearTimeout(writeTimeoutInstance);
847 writeTimeoutInstance = setTimeout(function() {
854 'notify': function(target, notifyWhen) {
855 target["equalityComparer"] = notifyWhen == "always"
856 ? function() { return false } // Treat all values as not equal
857 : ko.observable["fn"]["equalityComparer"];
862 function applyExtenders(requestedExtenders) {
864 if (requestedExtenders) {
865 for (var key in requestedExtenders) {
866 var extenderHandler = ko.extenders[key];
867 if (typeof extenderHandler == 'function') {
868 target = extenderHandler(target, requestedExtenders[key]);
875 ko.exportSymbol('extenders', ko.extenders);
877 ko.subscription = function (target, callback, disposeCallback) {
878 this.target = target;
879 this.callback = callback;
880 this.disposeCallback = disposeCallback;
881 ko.exportProperty(this, 'dispose', this.dispose);
883 ko.subscription.prototype.dispose = function () {
884 this.isDisposed = true;
885 this.disposeCallback();
888 ko.subscribable = function () {
889 this._subscriptions = {};
891 ko.utils.extend(this, ko.subscribable['fn']);
892 ko.exportProperty(this, 'subscribe', this.subscribe);
893 ko.exportProperty(this, 'extend', this.extend);
894 ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
897 var defaultEvent = "change";
899 ko.subscribable['fn'] = {
900 subscribe: function (callback, callbackTarget, event) {
901 event = event || defaultEvent;
902 var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
904 var subscription = new ko.subscription(this, boundCallback, function () {
905 ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
908 if (!this._subscriptions[event])
909 this._subscriptions[event] = [];
910 this._subscriptions[event].push(subscription);
914 "notifySubscribers": function (valueToNotify, event) {
915 event = event || defaultEvent;
916 if (this._subscriptions[event]) {
917 ko.dependencyDetection.ignore(function() {
918 ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
919 // In case a subscription was disposed during the arrayForEach cycle, check
920 // for isDisposed on each subscription before invoking its callback
921 if (subscription && (subscription.isDisposed !== true))
922 subscription.callback(valueToNotify);
928 getSubscriptionsCount: function () {
930 for (var eventName in this._subscriptions) {
931 if (this._subscriptions.hasOwnProperty(eventName))
932 total += this._subscriptions[eventName].length;
937 extend: applyExtenders
941 ko.isSubscribable = function (instance) {
942 return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
945 ko.exportSymbol('subscribable', ko.subscribable);
946 ko.exportSymbol('isSubscribable', ko.isSubscribable);
948 ko.dependencyDetection = (function () {
952 begin: function (callback) {
953 _frames.push({ callback: callback, distinctDependencies:[] });
960 registerDependency: function (subscribable) {
961 if (!ko.isSubscribable(subscribable))
962 throw new Error("Only subscribable things can act as dependencies");
963 if (_frames.length > 0) {
964 var topFrame = _frames[_frames.length - 1];
965 if (!topFrame || ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
967 topFrame.distinctDependencies.push(subscribable);
968 topFrame.callback(subscribable);
972 ignore: function(callback, callbackTarget, callbackArgs) {
975 return callback.apply(callbackTarget, callbackArgs || []);
982 var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };
984 ko.observable = function (initialValue) {
985 var _latestValue = initialValue;
987 function observable() {
988 if (arguments.length > 0) {
991 // Ignore writes if the value hasn't changed
992 if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
993 observable.valueWillMutate();
994 _latestValue = arguments[0];
995 if (DEBUG) observable._latestValue = _latestValue;
996 observable.valueHasMutated();
998 return this; // Permits chained assignments
1002 ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
1003 return _latestValue;
1006 if (DEBUG) observable._latestValue = _latestValue;
1007 ko.subscribable.call(observable);
1008 observable.peek = function() { return _latestValue };
1009 observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
1010 observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
1011 ko.utils.extend(observable, ko.observable['fn']);
1013 ko.exportProperty(observable, 'peek', observable.peek);
1014 ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
1015 ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
1020 ko.observable['fn'] = {
1021 "equalityComparer": function valuesArePrimitiveAndEqual(a, b) {
1022 var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
1023 return oldValueIsPrimitive ? (a === b) : false;
1027 var protoProperty = ko.observable.protoProperty = "__ko_proto__";
1028 ko.observable['fn'][protoProperty] = ko.observable;
1030 ko.hasPrototype = function(instance, prototype) {
1031 if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
1032 if (instance[protoProperty] === prototype) return true;
1033 return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
1036 ko.isObservable = function (instance) {
1037 return ko.hasPrototype(instance, ko.observable);
1039 ko.isWriteableObservable = function (instance) {
1041 if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
1043 // Writeable dependent observable
1044 if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
1051 ko.exportSymbol('observable', ko.observable);
1052 ko.exportSymbol('isObservable', ko.isObservable);
1053 ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
1054 ko.observableArray = function (initialValues) {
1055 if (arguments.length == 0) {
1056 // Zero-parameter constructor initializes to empty array
1059 if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
1060 throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
1062 var result = ko.observable(initialValues);
1063 ko.utils.extend(result, ko.observableArray['fn']);
1067 ko.observableArray['fn'] = {
1068 'remove': function (valueOrPredicate) {
1069 var underlyingArray = this.peek();
1070 var removedValues = [];
1071 var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
1072 for (var i = 0; i < underlyingArray.length; i++) {
1073 var value = underlyingArray[i];
1074 if (predicate(value)) {
1075 if (removedValues.length === 0) {
1076 this.valueWillMutate();
1078 removedValues.push(value);
1079 underlyingArray.splice(i, 1);
1083 if (removedValues.length) {
1084 this.valueHasMutated();
1086 return removedValues;
1089 'removeAll': function (arrayOfValues) {
1090 // If you passed zero args, we remove everything
1091 if (arrayOfValues === undefined) {
1092 var underlyingArray = this.peek();
1093 var allValues = underlyingArray.slice(0);
1094 this.valueWillMutate();
1095 underlyingArray.splice(0, underlyingArray.length);
1096 this.valueHasMutated();
1099 // If you passed an arg, we interpret it as an array of entries to remove
1102 return this['remove'](function (value) {
1103 return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
1107 'destroy': function (valueOrPredicate) {
1108 var underlyingArray = this.peek();
1109 var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
1110 this.valueWillMutate();
1111 for (var i = underlyingArray.length - 1; i >= 0; i--) {
1112 var value = underlyingArray[i];
1113 if (predicate(value))
1114 underlyingArray[i]["_destroy"] = true;
1116 this.valueHasMutated();
1119 'destroyAll': function (arrayOfValues) {
1120 // If you passed zero args, we destroy everything
1121 if (arrayOfValues === undefined)
1122 return this['destroy'](function() { return true });
1124 // If you passed an arg, we interpret it as an array of entries to destroy
1127 return this['destroy'](function (value) {
1128 return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
1132 'indexOf': function (item) {
1133 var underlyingArray = this();
1134 return ko.utils.arrayIndexOf(underlyingArray, item);
1137 'replace': function(oldItem, newItem) {
1138 var index = this['indexOf'](oldItem);
1140 this.valueWillMutate();
1141 this.peek()[index] = newItem;
1142 this.valueHasMutated();
1147 // Populate ko.observableArray.fn with read/write functions from native arrays
1148 // Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
1149 // because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
1150 ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
1151 ko.observableArray['fn'][methodName] = function () {
1152 // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
1153 // (for consistency with mutating regular observables)
1154 var underlyingArray = this.peek();
1155 this.valueWillMutate();
1156 var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
1157 this.valueHasMutated();
1158 return methodCallResult;
1162 // Populate ko.observableArray.fn with read-only functions from native arrays
1163 ko.utils.arrayForEach(["slice"], function (methodName) {
1164 ko.observableArray['fn'][methodName] = function () {
1165 var underlyingArray = this();
1166 return underlyingArray[methodName].apply(underlyingArray, arguments);
1170 ko.exportSymbol('observableArray', ko.observableArray);
1171 ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
1173 _hasBeenEvaluated = false,
1174 _isBeingEvaluated = false,
1175 readFunction = evaluatorFunctionOrOptions;
1177 if (readFunction && typeof readFunction == "object") {
1178 // Single-parameter syntax - everything is on this "options" param
1179 options = readFunction;
1180 readFunction = options["read"];
1182 // Multi-parameter syntax - construct the options according to the params passed
1183 options = options || {};
1185 readFunction = options["read"];
1187 if (typeof readFunction != "function")
1188 throw new Error("Pass a function that returns the value of the ko.computed");
1190 function addSubscriptionToDependency(subscribable) {
1191 _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync));
1194 function disposeAllSubscriptionsToDependencies() {
1195 ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
1196 subscription.dispose();
1198 _subscriptionsToDependencies = [];
1201 function evaluatePossiblyAsync() {
1202 var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
1203 if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
1204 clearTimeout(evaluationTimeoutInstance);
1205 evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
1207 evaluateImmediate();
1210 function evaluateImmediate() {
1211 if (_isBeingEvaluated) {
1212 // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
1213 // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
1214 // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
1215 // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
1219 // Don't dispose on first evaluation, because the "disposeWhen" callback might
1220 // e.g., dispose when the associated DOM element isn't in the doc, and it's not
1221 // going to be in the doc until *after* the first evaluation
1222 if (_hasBeenEvaluated && disposeWhen()) {
1227 _isBeingEvaluated = true;
1229 // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
1230 // Then, during evaluation, we cross off any that are in fact still being used.
1231 var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
1233 ko.dependencyDetection.begin(function(subscribable) {
1235 if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
1236 disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
1238 addSubscriptionToDependency(subscribable); // Brand new subscription - add it
1241 var newValue = readFunction.call(evaluatorFunctionTarget);
1243 // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
1244 for (var i = disposalCandidates.length - 1; i >= 0; i--) {
1245 if (disposalCandidates[i])
1246 _subscriptionsToDependencies.splice(i, 1)[0].dispose();
1248 _hasBeenEvaluated = true;
1250 dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
1251 _latestValue = newValue;
1252 if (DEBUG) dependentObservable._latestValue = _latestValue;
1254 ko.dependencyDetection.end();
1257 dependentObservable["notifySubscribers"](_latestValue);
1258 _isBeingEvaluated = false;
1259 if (!_subscriptionsToDependencies.length)
1263 function dependentObservable() {
1264 if (arguments.length > 0) {
1265 if (typeof writeFunction === "function") {
1267 writeFunction.apply(evaluatorFunctionTarget, arguments);
1269 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.");
1271 return this; // Permits chained assignments
1273 // Reading the value
1274 if (!_hasBeenEvaluated)
1275 evaluateImmediate();
1276 ko.dependencyDetection.registerDependency(dependentObservable);
1277 return _latestValue;
1282 if (!_hasBeenEvaluated)
1283 evaluateImmediate();
1284 return _latestValue;
1287 function isActive() {
1288 return !_hasBeenEvaluated || _subscriptionsToDependencies.length > 0;
1291 // By here, "options" is always non-null
1292 var writeFunction = options["write"],
1293 disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
1294 disposeWhen = options["disposeWhen"] || options.disposeWhen || function() { return false; },
1295 dispose = disposeAllSubscriptionsToDependencies,
1296 _subscriptionsToDependencies = [],
1297 evaluationTimeoutInstance = null;
1299 if (!evaluatorFunctionTarget)
1300 evaluatorFunctionTarget = options["owner"];
1302 dependentObservable.peek = peek;
1303 dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
1304 dependentObservable.hasWriteFunction = typeof options["write"] === "function";
1305 dependentObservable.dispose = function () { dispose(); };
1306 dependentObservable.isActive = isActive;
1307 dependentObservable.valueHasMutated = function() {
1308 _hasBeenEvaluated = false;
1309 evaluateImmediate();
1312 ko.subscribable.call(dependentObservable);
1313 ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
1315 ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
1316 ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
1317 ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
1318 ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
1320 // Evaluate, unless deferEvaluation is true
1321 if (options['deferEvaluation'] !== true)
1322 evaluateImmediate();
1324 // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values.
1325 // But skip if isActive is false (there will never be any dependencies to dispose).
1326 // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
1327 // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
1328 if (disposeWhenNodeIsRemoved && isActive()) {
1329 dispose = function() {
1330 ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
1331 disposeAllSubscriptionsToDependencies();
1333 ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
1334 var existingDisposeWhenFunction = disposeWhen;
1335 disposeWhen = function () {
1336 return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
1340 return dependentObservable;
1343 ko.isComputed = function(instance) {
1344 return ko.hasPrototype(instance, ko.dependentObservable);
1347 var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
1348 ko.dependentObservable[protoProp] = ko.observable;
1350 ko.dependentObservable['fn'] = {};
1351 ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
1353 ko.exportSymbol('dependentObservable', ko.dependentObservable);
1354 ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
1355 ko.exportSymbol('isComputed', ko.isComputed);
1358 var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
1360 ko.toJS = function(rootObject) {
1361 if (arguments.length == 0)
1362 throw new Error("When calling ko.toJS, pass the object you want to convert.");
1364 // We just unwrap everything at every level in the object graph
1365 return mapJsObjectGraph(rootObject, function(valueToMap) {
1366 // Loop because an observable's value might in turn be another observable wrapper
1367 for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
1368 valueToMap = valueToMap();
1373 ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
1374 var plainJavaScriptObject = ko.toJS(rootObject);
1375 return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
1378 function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
1379 visitedObjects = visitedObjects || new objectLookup();
1381 rootObject = mapInputCallback(rootObject);
1382 var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
1383 if (!canHaveProperties)
1386 var outputProperties = rootObject instanceof Array ? [] : {};
1387 visitedObjects.save(rootObject, outputProperties);
1389 visitPropertiesOrArrayEntries(rootObject, function(indexer) {
1390 var propertyValue = mapInputCallback(rootObject[indexer]);
1392 switch (typeof propertyValue) {
1397 outputProperties[indexer] = propertyValue;
1401 var previouslyMappedValue = visitedObjects.get(propertyValue);
1402 outputProperties[indexer] = (previouslyMappedValue !== undefined)
1403 ? previouslyMappedValue
1404 : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
1409 return outputProperties;
1412 function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
1413 if (rootObject instanceof Array) {
1414 for (var i = 0; i < rootObject.length; i++)
1417 // For arrays, also respect toJSON property for custom mappings (fixes #278)
1418 if (typeof rootObject['toJSON'] == 'function')
1419 visitorCallback('toJSON');
1421 for (var propertyName in rootObject)
1422 visitorCallback(propertyName);
1426 function objectLookup() {
1429 this.save = function(key, value) {
1430 var existingIndex = ko.utils.arrayIndexOf(keys, key);
1431 if (existingIndex >= 0)
1432 values[existingIndex] = value;
1438 this.get = function(key) {
1439 var existingIndex = ko.utils.arrayIndexOf(keys, key);
1440 return (existingIndex >= 0) ? values[existingIndex] : undefined;
1445 ko.exportSymbol('toJS', ko.toJS);
1446 ko.exportSymbol('toJSON', ko.toJSON);
1448 var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
1450 // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
1451 // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
1452 // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
1453 ko.selectExtensions = {
1454 readValue : function(element) {
1455 switch (ko.utils.tagNameLower(element)) {
1457 if (element[hasDomDataExpandoProperty] === true)
1458 return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
1459 return ko.utils.ieVersion <= 7
1460 ? (element.getAttributeNode('value').specified ? element.value : element.text)
1463 return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
1465 return element.value;
1469 writeValue: function(element, value) {
1470 switch (ko.utils.tagNameLower(element)) {
1472 switch(typeof value) {
1474 ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
1475 if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
1476 delete element[hasDomDataExpandoProperty];
1478 element.value = value;
1481 // Store arbitrary object using DomData
1482 ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
1483 element[hasDomDataExpandoProperty] = true;
1485 // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
1486 element.value = typeof value === "number" ? value : "";
1491 for (var i = element.options.length - 1; i >= 0; i--) {
1492 if (ko.selectExtensions.readValue(element.options[i]) == value) {
1493 element.selectedIndex = i;
1499 if ((value === null) || (value === undefined))
1501 element.value = value;
1508 ko.exportSymbol('selectExtensions', ko.selectExtensions);
1509 ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
1510 ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
1511 ko.expressionRewriting = (function () {
1512 var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
1513 var javaScriptReservedWords = ["true", "false"];
1515 // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
1516 // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
1517 var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
1519 function restoreTokens(string, tokens) {
1520 var prevValue = null;
1521 while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
1523 string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
1524 return tokens[tokenIndex];
1530 function getWriteableValue(expression) {
1531 if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
1533 var match = expression.match(javaScriptAssignmentTarget);
1534 return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
1537 function ensureQuoted(key) {
1538 var trimmedKey = ko.utils.stringTrim(key);
1539 switch (trimmedKey.length && trimmedKey.charAt(0)) {
1544 return "'" + trimmedKey + "'";
1549 bindingRewriteValidators: [],
1551 parseObjectLiteral: function(objectLiteralString) {
1552 // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
1553 // that is sufficient just to split an object literal string into a set of top-level key-value pairs
1555 var str = ko.utils.stringTrim(objectLiteralString);
1558 if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
1559 str = str.substring(1, str.length - 1);
1561 // Pull out any string literals and regex literals
1563 var tokenStart = null, tokenEndChar;
1564 for (var position = 0; position < str.length; position++) {
1565 var c = str.charAt(position);
1566 if (tokenStart === null) {
1571 tokenStart = position;
1575 } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
1576 var token = str.substring(tokenStart, position + 1);
1578 var replacement = "@ko_token_" + (tokens.length - 1) + "@";
1579 str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
1580 position -= (token.length - replacement.length);
1585 // Next pull out balanced paren, brace, and bracket blocks
1587 tokenEndChar = null;
1588 var tokenDepth = 0, tokenStartChar = null;
1589 for (var position = 0; position < str.length; position++) {
1590 var c = str.charAt(position);
1591 if (tokenStart === null) {
1593 case "{": tokenStart = position; tokenStartChar = c;
1596 case "(": tokenStart = position; tokenStartChar = c;
1599 case "[": tokenStart = position; tokenStartChar = c;
1605 if (c === tokenStartChar)
1607 else if (c === tokenEndChar) {
1609 if (tokenDepth === 0) {
1610 var token = str.substring(tokenStart, position + 1);
1612 var replacement = "@ko_token_" + (tokens.length - 1) + "@";
1613 str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
1614 position -= (token.length - replacement.length);
1620 // Now we can safely split on commas to get the key/value pairs
1622 var keyValuePairs = str.split(",");
1623 for (var i = 0, j = keyValuePairs.length; i < j; i++) {
1624 var pair = keyValuePairs[i];
1625 var colonPos = pair.indexOf(":");
1626 if ((colonPos > 0) && (colonPos < pair.length - 1)) {
1627 var key = pair.substring(0, colonPos);
1628 var value = pair.substring(colonPos + 1);
1629 result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
1631 result.push({ 'unknown': restoreTokens(pair, tokens) });
1637 preProcessBindings: function (objectLiteralStringOrKeyValueArray) {
1638 var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
1639 ? ko.expressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
1640 : objectLiteralStringOrKeyValueArray;
1641 var resultStrings = [], propertyAccessorResultStrings = [];
1644 for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
1645 if (resultStrings.length > 0)
1646 resultStrings.push(",");
1648 if (keyValueEntry['key']) {
1649 var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
1650 resultStrings.push(quotedKey);
1651 resultStrings.push(":");
1652 resultStrings.push(val);
1654 if (val = getWriteableValue(ko.utils.stringTrim(val))) {
1655 if (propertyAccessorResultStrings.length > 0)
1656 propertyAccessorResultStrings.push(", ");
1657 propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
1659 } else if (keyValueEntry['unknown']) {
1660 resultStrings.push(keyValueEntry['unknown']);
1664 var combinedResult = resultStrings.join("");
1665 if (propertyAccessorResultStrings.length > 0) {
1666 var allPropertyAccessors = propertyAccessorResultStrings.join("");
1667 combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
1670 return combinedResult;
1673 keyValueArrayContainsKey: function(keyValueArray, key) {
1674 for (var i = 0; i < keyValueArray.length; i++)
1675 if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
1680 // Internal, private KO utility for updating model properties from within bindings
1681 // property: If the property being updated is (or might be) an observable, pass it here
1682 // If it turns out to be a writable observable, it will be written to directly
1683 // allBindingsAccessor: All bindings in the current execution context.
1684 // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
1685 // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
1686 // value: The value to be written
1687 // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
1688 // it is !== existing value on that writable observable
1689 writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
1690 if (!property || !ko.isWriteableObservable(property)) {
1691 var propWriters = allBindingsAccessor()['_ko_property_writers'];
1692 if (propWriters && propWriters[key])
1693 propWriters[key](value);
1694 } else if (!checkIfDifferent || property.peek() !== value) {
1701 ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
1702 ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
1703 ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
1704 ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
1706 // For backward compatibility, define the following aliases. (Previously, these function names were misleading because
1707 // they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
1708 ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
1709 ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);(function() {
1710 // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
1711 // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
1712 // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
1713 // of that virtual hierarchy
1715 // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
1716 // without having to scatter special cases all over the binding and templating code.
1718 // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
1719 // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
1720 // So, use node.text where available, and node.nodeValue elsewhere
1721 var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
1723 var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*-->$/ : /^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/;
1724 var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
1725 var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
1727 function isStartComment(node) {
1728 return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
1731 function isEndComment(node) {
1732 return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
1735 function getVirtualChildren(startComment, allowUnbalanced) {
1736 var currentNode = startComment;
1739 while (currentNode = currentNode.nextSibling) {
1740 if (isEndComment(currentNode)) {
1746 children.push(currentNode);
1748 if (isStartComment(currentNode))
1751 if (!allowUnbalanced)
1752 throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
1756 function getMatchingEndComment(startComment, allowUnbalanced) {
1757 var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
1758 if (allVirtualChildren) {
1759 if (allVirtualChildren.length > 0)
1760 return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
1761 return startComment.nextSibling;
1763 return null; // Must have no matching end comment, and allowUnbalanced is true
1766 function getUnbalancedChildTags(node) {
1767 // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
1768 // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
1769 var childNode = node.firstChild, captureRemaining = null;
1772 if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
1773 captureRemaining.push(childNode);
1774 else if (isStartComment(childNode)) {
1775 var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
1776 if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
1777 childNode = matchingEndComment;
1779 captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
1780 } else if (isEndComment(childNode)) {
1781 captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
1783 } while (childNode = childNode.nextSibling);
1785 return captureRemaining;
1788 ko.virtualElements = {
1789 allowedBindings: {},
1791 childNodes: function(node) {
1792 return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
1795 emptyNode: function(node) {
1796 if (!isStartComment(node))
1797 ko.utils.emptyDomNode(node);
1799 var virtualChildren = ko.virtualElements.childNodes(node);
1800 for (var i = 0, j = virtualChildren.length; i < j; i++)
1801 ko.removeNode(virtualChildren[i]);
1805 setDomNodeChildren: function(node, childNodes) {
1806 if (!isStartComment(node))
1807 ko.utils.setDomNodeChildren(node, childNodes);
1809 ko.virtualElements.emptyNode(node);
1810 var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
1811 for (var i = 0, j = childNodes.length; i < j; i++)
1812 endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
1816 prepend: function(containerNode, nodeToPrepend) {
1817 if (!isStartComment(containerNode)) {
1818 if (containerNode.firstChild)
1819 containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
1821 containerNode.appendChild(nodeToPrepend);
1823 // Start comments must always have a parent and at least one following sibling (the end comment)
1824 containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
1828 insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
1829 if (!insertAfterNode) {
1830 ko.virtualElements.prepend(containerNode, nodeToInsert);
1831 } else if (!isStartComment(containerNode)) {
1832 // Insert after insertion point
1833 if (insertAfterNode.nextSibling)
1834 containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
1836 containerNode.appendChild(nodeToInsert);
1838 // Children of start comments must always have a parent and at least one following sibling (the end comment)
1839 containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
1843 firstChild: function(node) {
1844 if (!isStartComment(node))
1845 return node.firstChild;
1846 if (!node.nextSibling || isEndComment(node.nextSibling))
1848 return node.nextSibling;
1851 nextSibling: function(node) {
1852 if (isStartComment(node))
1853 node = getMatchingEndComment(node);
1854 if (node.nextSibling && isEndComment(node.nextSibling))
1856 return node.nextSibling;
1859 virtualNodeBindingValue: function(node) {
1860 var regexMatch = isStartComment(node);
1861 return regexMatch ? regexMatch[1] : null;
1864 normaliseVirtualElementDomStructure: function(elementVerified) {
1865 // Workaround for https://github.com/SteveSanderson/knockout/issues/155
1866 // (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
1867 // that are direct descendants of <ul> into the preceding <li>)
1868 if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
1871 // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
1872 // must be intended to appear *after* that child, so move them there.
1873 var childNode = elementVerified.firstChild;
1876 if (childNode.nodeType === 1) {
1877 var unbalancedTags = getUnbalancedChildTags(childNode);
1878 if (unbalancedTags) {
1879 // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
1880 var nodeToInsertBefore = childNode.nextSibling;
1881 for (var i = 0; i < unbalancedTags.length; i++) {
1882 if (nodeToInsertBefore)
1883 elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
1885 elementVerified.appendChild(unbalancedTags[i]);
1889 } while (childNode = childNode.nextSibling);
1894 ko.exportSymbol('virtualElements', ko.virtualElements);
1895 ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
1896 ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
1897 //ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
1898 ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
1899 //ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
1900 ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
1901 ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
1903 var defaultBindingAttributeName = "data-bind";
1905 ko.bindingProvider = function() {
1906 this.bindingCache = {};
1909 ko.utils.extend(ko.bindingProvider.prototype, {
1910 'nodeHasBindings': function(node) {
1911 switch (node.nodeType) {
1912 case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
1913 case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
1914 default: return false;
1918 'getBindings': function(node, bindingContext) {
1919 var bindingsString = this['getBindingsString'](node, bindingContext);
1920 return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
1923 // The following function is only used internally by this default provider.
1924 // It's not part of the interface definition for a general binding provider.
1925 'getBindingsString': function(node, bindingContext) {
1926 switch (node.nodeType) {
1927 case 1: return node.getAttribute(defaultBindingAttributeName); // Element
1928 case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
1929 default: return null;
1933 // The following function is only used internally by this default provider.
1934 // It's not part of the interface definition for a general binding provider.
1935 'parseBindingsString': function(bindingsString, bindingContext, node) {
1937 var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
1938 return bindingFunction(bindingContext, node);
1940 throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
1945 ko.bindingProvider['instance'] = new ko.bindingProvider();
1947 function createBindingsStringEvaluatorViaCache(bindingsString, cache) {
1948 var cacheKey = bindingsString;
1949 return cache[cacheKey]
1950 || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString));
1953 function createBindingsStringEvaluator(bindingsString) {
1954 // Build the source for a function that evaluates "expression"
1955 // For each scope variable, add an extra level of "with" nesting
1956 // Example result: with(sc1) { with(sc0) { return (expression) } }
1957 var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString),
1958 functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
1959 return new Function("$context", "$element", functionBody);
1963 ko.exportSymbol('bindingProvider', ko.bindingProvider);
1965 ko.bindingHandlers = {};
1967 ko.bindingContext = function(dataItem, parentBindingContext, dataItemAlias) {
1968 if (parentBindingContext) {
1969 ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
1970 this['$parentContext'] = parentBindingContext;
1971 this['$parent'] = parentBindingContext['$data'];
1972 this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
1973 this['$parents'].unshift(this['$parent']);
1975 this['$parents'] = [];
1976 this['$root'] = dataItem;
1977 // Export 'ko' in the binding context so it will be available in bindings and templates
1978 // even if 'ko' isn't exported as a global, such as when using an AMD loader.
1979 // See https://github.com/SteveSanderson/knockout/issues/490
1982 this['$data'] = dataItem;
1984 this[dataItemAlias] = dataItem;
1986 ko.bindingContext.prototype['createChildContext'] = function (dataItem, dataItemAlias) {
1987 return new ko.bindingContext(dataItem, this, dataItemAlias);
1989 ko.bindingContext.prototype['extend'] = function(properties) {
1990 var clone = ko.utils.extend(new ko.bindingContext(), this);
1991 return ko.utils.extend(clone, properties);
1994 function validateThatBindingIsAllowedForVirtualElements(bindingName) {
1995 var validator = ko.virtualElements.allowedBindings[bindingName];
1997 throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
2000 function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
2001 var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
2002 while (currentChild = nextInQueue) {
2003 // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
2004 nextInQueue = ko.virtualElements.nextSibling(currentChild);
2005 applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
2009 function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
2010 var shouldBindDescendants = true;
2012 // Perf optimisation: Apply bindings only if...
2013 // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
2014 // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
2015 // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
2016 var isElement = (nodeVerified.nodeType === 1);
2017 if (isElement) // Workaround IE <= 8 HTML parsing weirdness
2018 ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
2020 var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
2021 || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
2022 if (shouldApplyBindings)
2023 shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
2025 if (shouldBindDescendants) {
2026 // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
2027 // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
2028 // hence bindingContextsMayDifferFromDomParentElement is false
2029 // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
2030 // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
2031 // hence bindingContextsMayDifferFromDomParentElement is true
2032 applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
2036 function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
2037 // Need to be sure that inits are only run once, and updates never run until all the inits have been run
2038 var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
2040 // Each time the dependentObservable is evaluated (after data changes),
2041 // the binding attribute is reparsed so that it can pick out the correct
2042 // model properties in the context of the changed data.
2043 // DOM event callbacks need to be able to access this changed data,
2044 // so we need a single parsedBindings variable (shared by all callbacks
2045 // associated with this node's bindings) that all the closures can access.
2047 function makeValueAccessor(bindingKey) {
2048 return function () { return parsedBindings[bindingKey] }
2050 function parsedBindingsAccessor() {
2051 return parsedBindings;
2054 var bindingHandlerThatControlsDescendantBindings;
2055 ko.dependentObservable(
2057 // Ensure we have a nonnull binding context to work with
2058 var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
2059 ? viewModelOrBindingContext
2060 : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
2061 var viewModel = bindingContextInstance['$data'];
2063 // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
2064 // we can easily recover it just by scanning up the node's ancestors in the DOM
2065 // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
2066 if (bindingContextMayDifferFromDomParentElement)
2067 ko.storedBindingContextForNode(node, bindingContextInstance);
2069 // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
2070 var evaluatedBindings = (typeof bindings == "function") ? bindings(bindingContextInstance, node) : bindings;
2071 parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
2073 if (parsedBindings) {
2074 // First run all the inits, so bindings can register for notification on changes
2075 if (initPhase === 0) {
2077 for (var bindingKey in parsedBindings) {
2078 var binding = ko.bindingHandlers[bindingKey];
2079 if (binding && node.nodeType === 8)
2080 validateThatBindingIsAllowedForVirtualElements(bindingKey);
2082 if (binding && typeof binding["init"] == "function") {
2083 var handlerInitFn = binding["init"];
2084 var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
2086 // If this binding handler claims to control descendant bindings, make a note of this
2087 if (initResult && initResult['controlsDescendantBindings']) {
2088 if (bindingHandlerThatControlsDescendantBindings !== undefined)
2089 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.");
2090 bindingHandlerThatControlsDescendantBindings = bindingKey;
2097 // ... then run all the updates, which might trigger changes even on the first evaluation
2098 if (initPhase === 2) {
2099 for (var bindingKey in parsedBindings) {
2100 var binding = ko.bindingHandlers[bindingKey];
2101 if (binding && typeof binding["update"] == "function") {
2102 var handlerUpdateFn = binding["update"];
2103 handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
2110 { disposeWhenNodeIsRemoved : node }
2114 shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
2118 var storedBindingContextDomDataKey = "__ko_bindingContext__";
2119 ko.storedBindingContextForNode = function (node, bindingContext) {
2120 if (arguments.length == 2)
2121 ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
2123 return ko.utils.domData.get(node, storedBindingContextDomDataKey);
2126 ko.applyBindingsToNode = function (node, bindings, viewModel) {
2127 if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
2128 ko.virtualElements.normaliseVirtualElementDomStructure(node);
2129 return applyBindingsToNodeInternal(node, bindings, viewModel, true);
2132 ko.applyBindingsToDescendants = function(viewModel, rootNode) {
2133 if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
2134 applyBindingsToDescendantsInternal(viewModel, rootNode, true);
2137 ko.applyBindings = function (viewModel, rootNode) {
2138 if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
2139 throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
2140 rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
2142 applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
2145 // Retrieving binding context from arbitrary nodes
2146 ko.contextFor = function(node) {
2147 // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
2148 switch (node.nodeType) {
2151 var context = ko.storedBindingContextForNode(node);
2152 if (context) return context;
2153 if (node.parentNode) return ko.contextFor(node.parentNode);
2158 ko.dataFor = function(node) {
2159 var context = ko.contextFor(node);
2160 return context ? context['$data'] : undefined;
2163 ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
2164 ko.exportSymbol('applyBindings', ko.applyBindings);
2165 ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
2166 ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
2167 ko.exportSymbol('contextFor', ko.contextFor);
2168 ko.exportSymbol('dataFor', ko.dataFor);
2170 var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
2171 ko.bindingHandlers['attr'] = {
2172 'update': function(element, valueAccessor, allBindingsAccessor) {
2173 var value = ko.utils.unwrapObservable(valueAccessor()) || {};
2174 for (var attrName in value) {
2175 if (typeof attrName == "string") {
2176 var attrValue = ko.utils.unwrapObservable(value[attrName]);
2178 // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
2179 // when someProp is a "no value"-like value (strictly null, false, or undefined)
2180 // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
2181 var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
2183 element.removeAttribute(attrName);
2185 // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
2186 // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
2187 // but instead of figuring out the mode, we'll just set the attribute through the Javascript
2188 // property for IE <= 8.
2189 if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
2190 attrName = attrHtmlToJavascriptMap[attrName];
2192 element.removeAttribute(attrName);
2194 element[attrName] = attrValue;
2195 } else if (!toRemove) {
2197 element.setAttribute(attrName, attrValue.toString());
2201 console.log("Can't set attribute " + attrName + " to " + attrValue + " error: " + err);
2206 // Treat "name" specially - although you can think of it as an attribute, it also needs
2207 // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
2208 // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
2209 // entirely, and there's no strong reason to allow for such casing in HTML.
2210 if (attrName === "name") {
2211 ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
2217 ko.bindingHandlers['checked'] = {
2218 'init': function (element, valueAccessor, allBindingsAccessor) {
2219 var updateHandler = function() {
2221 if (element.type == "checkbox") {
2222 valueToWrite = element.checked;
2223 } else if ((element.type == "radio") && (element.checked)) {
2224 valueToWrite = element.value;
2226 return; // "checked" binding only responds to checkboxes and selected radio buttons
2229 var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
2230 if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
2231 // For checkboxes bound to an array, we add/remove the checkbox value to that array
2232 // This works for both observable and non-observable arrays
2233 var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
2234 if (element.checked && (existingEntryIndex < 0))
2235 modelValue.push(element.value);
2236 else if ((!element.checked) && (existingEntryIndex >= 0))
2237 modelValue.splice(existingEntryIndex, 1);
2239 ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
2242 ko.utils.registerEventHandler(element, "click", updateHandler);
2244 // IE 6 won't allow radio buttons to be selected unless they have a name
2245 if ((element.type == "radio") && !element.name)
2246 ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
2248 'update': function (element, valueAccessor) {
2249 var value = ko.utils.unwrapObservable(valueAccessor());
2251 if (element.type == "checkbox") {
2252 if (value instanceof Array) {
2253 // When bound to an array, the checkbox being checked represents its value being present in that array
2254 element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
2256 // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
2257 element.checked = value;
2259 } else if (element.type == "radio") {
2260 element.checked = (element.value == value);
2264 var classesWrittenByBindingKey = '__ko__cssValue';
2265 ko.bindingHandlers['css'] = {
2266 'update': function (element, valueAccessor) {
2267 var value = ko.utils.unwrapObservable(valueAccessor());
2268 if (typeof value == "object") {
2269 for (var className in value) {
2270 var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
2271 ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
2274 value = String(value || ''); // Make sure we don't try to store or set a non-string value
2275 ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
2276 element[classesWrittenByBindingKey] = value;
2277 ko.utils.toggleDomNodeCssClass(element, value, true);
2281 ko.bindingHandlers['enable'] = {
2282 'update': function (element, valueAccessor) {
2283 var value = ko.utils.unwrapObservable(valueAccessor());
2284 if (value && element.disabled)
2285 element.removeAttribute("disabled");
2286 else if ((!value) && (!element.disabled))
2287 element.disabled = true;
2291 ko.bindingHandlers['disable'] = {
2292 'update': function (element, valueAccessor) {
2293 ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
2296 // For certain common events (currently just 'click'), allow a simplified data-binding syntax
2297 // e.g. click:handler instead of the usual full-length event:{click:handler}
2298 function makeEventHandlerShortcut(eventName) {
2299 ko.bindingHandlers[eventName] = {
2300 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
2301 var newValueAccessor = function () {
2303 result[eventName] = valueAccessor();
2306 return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
2311 ko.bindingHandlers['event'] = {
2312 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
2313 var eventsToHandle = valueAccessor() || {};
2314 for(var eventNameOutsideClosure in eventsToHandle) {
2316 var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
2317 if (typeof eventName == "string") {
2318 ko.utils.registerEventHandler(element, eventName, function (event) {
2319 var handlerReturnValue;
2320 var handlerFunction = valueAccessor()[eventName];
2321 if (!handlerFunction)
2323 var allBindings = allBindingsAccessor();
2326 // Take all the event args, and prefix with the viewmodel
2327 var argsForHandler = ko.utils.makeArray(arguments);
2328 argsForHandler.unshift(viewModel);
2329 handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
2331 if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
2332 if (event.preventDefault)
2333 event.preventDefault();
2335 event.returnValue = false;
2339 var bubble = allBindings[eventName + 'Bubble'] !== false;
2341 event.cancelBubble = true;
2342 if (event.stopPropagation)
2343 event.stopPropagation();
2351 // "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
2352 // "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
2353 ko.bindingHandlers['foreach'] = {
2354 makeTemplateValueAccessor: function(valueAccessor) {
2356 var modelValue = valueAccessor(),
2357 unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
2359 // If unwrappedValue is the array, pass in the wrapped value on its own
2360 // The value will be unwrapped and tracked within the template binding
2361 // (See https://github.com/SteveSanderson/knockout/issues/523)
2362 if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
2363 return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
2365 // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
2366 ko.utils.unwrapObservable(modelValue);
2368 'foreach': unwrappedValue['data'],
2369 'as': unwrappedValue['as'],
2370 'includeDestroyed': unwrappedValue['includeDestroyed'],
2371 'afterAdd': unwrappedValue['afterAdd'],
2372 'beforeRemove': unwrappedValue['beforeRemove'],
2373 'afterRender': unwrappedValue['afterRender'],
2374 'beforeMove': unwrappedValue['beforeMove'],
2375 'afterMove': unwrappedValue['afterMove'],
2376 'templateEngine': ko.nativeTemplateEngine.instance
2380 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2381 return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
2383 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2384 return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
2387 ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
2388 ko.virtualElements.allowedBindings['foreach'] = true;
2389 var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
2390 ko.bindingHandlers['hasfocus'] = {
2391 'init': function(element, valueAccessor, allBindingsAccessor) {
2392 var handleElementFocusChange = function(isFocused) {
2393 // Where possible, ignore which event was raised and determine focus state using activeElement,
2394 // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
2395 // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
2396 // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
2397 // from calling 'blur()' on the element when it loses focus.
2398 // Discussion at https://github.com/SteveSanderson/knockout/pull/352
2399 element[hasfocusUpdatingProperty] = true;
2400 var ownerDoc = element.ownerDocument;
2401 if ("activeElement" in ownerDoc) {
2402 isFocused = (ownerDoc.activeElement === element);
2404 var modelValue = valueAccessor();
2405 ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true);
2406 element[hasfocusUpdatingProperty] = false;
2408 var handleElementFocusIn = handleElementFocusChange.bind(null, true);
2409 var handleElementFocusOut = handleElementFocusChange.bind(null, false);
2411 ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
2412 ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
2413 ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
2414 ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
2416 'update': function(element, valueAccessor) {
2417 var value = ko.utils.unwrapObservable(valueAccessor());
2418 if (!element[hasfocusUpdatingProperty]) {
2419 value ? element.focus() : element.blur();
2420 ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
2424 ko.bindingHandlers['html'] = {
2425 'init': function() {
2426 // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
2427 return { 'controlsDescendantBindings': true };
2429 'update': function (element, valueAccessor) {
2430 // setHtml will unwrap the value if needed
2431 ko.utils.setHtml(element, valueAccessor());
2434 var withIfDomDataKey = '__ko_withIfBindingData';
2435 // Makes a binding like with or if
2436 function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
2437 ko.bindingHandlers[bindingKey] = {
2438 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2439 ko.utils.domData.set(element, withIfDomDataKey, {});
2440 return { 'controlsDescendantBindings': true };
2442 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
2443 var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
2444 dataValue = ko.utils.unwrapObservable(valueAccessor()),
2445 shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
2446 isFirstRender = !withIfData.savedNodes,
2447 needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
2450 if (isFirstRender) {
2451 withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
2454 if (shouldDisplay) {
2455 if (!isFirstRender) {
2456 ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
2458 ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
2460 ko.virtualElements.emptyNode(element);
2463 withIfData.didDisplayOnLastUpdate = shouldDisplay;
2467 ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
2468 ko.virtualElements.allowedBindings[bindingKey] = true;
2471 // Construct the actual binding handlers
2472 makeWithIfBinding('if');
2473 makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
2474 makeWithIfBinding('with', true /* isWith */, false /* isNot */,
2475 function(bindingContext, dataValue) {
2476 return bindingContext['createChildContext'](dataValue);
2479 function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
2480 if (preferModelValue) {
2481 if (modelValue !== ko.selectExtensions.readValue(element))
2482 ko.selectExtensions.writeValue(element, modelValue);
2485 // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
2486 // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
2487 // change the model value to match the dropdown.
2488 if (modelValue !== ko.selectExtensions.readValue(element))
2489 ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
2492 ko.bindingHandlers['options'] = {
2493 'update': function (element, valueAccessor, allBindingsAccessor) {
2494 if (ko.utils.tagNameLower(element) !== "select")
2495 throw new Error("options binding applies only to SELECT elements");
2497 var selectWasPreviouslyEmpty = element.length == 0;
2498 var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
2499 return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
2500 }), function (node) {
2501 return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
2503 var previousScrollTop = element.scrollTop;
2505 var value = ko.utils.unwrapObservable(valueAccessor());
2506 var selectedValue = element.value;
2508 // Remove all existing <option>s.
2509 // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
2510 while (element.length > 0) {
2511 ko.cleanNode(element.options[0]);
2516 var allBindings = allBindingsAccessor(),
2517 includeDestroyed = allBindings['optionsIncludeDestroyed'];
2519 if (typeof value.length != "number")
2521 if (allBindings['optionsCaption']) {
2522 var option = document.createElement("option");
2523 ko.utils.setHtml(option, allBindings['optionsCaption']);
2524 ko.selectExtensions.writeValue(option, undefined);
2525 element.appendChild(option);
2528 for (var i = 0, j = value.length; i < j; i++) {
2529 // Skip destroyed items
2530 var arrayEntry = value[i];
2531 if (arrayEntry && arrayEntry['_destroy'] && !includeDestroyed)
2534 var option = document.createElement("option");
2536 function applyToObject(object, predicate, defaultValue) {
2537 var predicateType = typeof predicate;
2538 if (predicateType == "function") // Given a function; run it against the data value
2539 return predicate(object);
2540 else if (predicateType == "string") // Given a string; treat it as a property name on the data value
2541 return object[predicate];
2542 else // Given no optionsText arg; use the data value itself
2543 return defaultValue;
2546 // Apply a value to the option element
2547 var optionValue = applyToObject(arrayEntry, allBindings['optionsValue'], arrayEntry);
2548 ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
2550 // Apply some text to the option element
2551 var optionText = applyToObject(arrayEntry, allBindings['optionsText'], optionValue);
2552 ko.utils.setTextContent(option, optionText);
2554 element.appendChild(option);
2557 // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
2558 // That's why we first added them without selection. Now it's time to set the selection.
2559 var newOptions = element.getElementsByTagName("option");
2560 var countSelectionsRetained = 0;
2561 for (var i = 0, j = newOptions.length; i < j; i++) {
2562 if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
2563 ko.utils.setOptionNodeSelectionState(newOptions[i], true);
2564 countSelectionsRetained++;
2568 element.scrollTop = previousScrollTop;
2570 if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
2571 // Ensure consistency between model value and selected option.
2572 // If the dropdown is being populated for the first time here (or was otherwise previously empty),
2573 // the dropdown selection state is meaningless, so we preserve the model value.
2574 ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.peekObservable(allBindings['value']), /* preferModelValue */ true);
2577 // Workaround for IE9 bug
2578 ko.utils.ensureSelectElementIsRenderedCorrectly(element);
2582 ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
2583 ko.bindingHandlers['selectedOptions'] = {
2584 'init': function (element, valueAccessor, allBindingsAccessor) {
2585 ko.utils.registerEventHandler(element, "change", function () {
2586 var value = valueAccessor(), valueToWrite = [];
2587 ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
2589 valueToWrite.push(ko.selectExtensions.readValue(node));
2591 ko.expressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
2594 'update': function (element, valueAccessor) {
2595 if (ko.utils.tagNameLower(element) != "select")
2596 throw new Error("values binding applies only to SELECT elements");
2598 var newValue = ko.utils.unwrapObservable(valueAccessor());
2599 if (newValue && typeof newValue.length == "number") {
2600 ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
2601 var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
2602 ko.utils.setOptionNodeSelectionState(node, isSelected);
2607 ko.bindingHandlers['style'] = {
2608 'update': function (element, valueAccessor) {
2609 var value = ko.utils.unwrapObservable(valueAccessor() || {});
2610 for (var styleName in value) {
2611 if (typeof styleName == "string") {
2612 var styleValue = ko.utils.unwrapObservable(value[styleName]);
2613 element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
2618 ko.bindingHandlers['submit'] = {
2619 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
2620 if (typeof valueAccessor() != "function")
2621 throw new Error("The value for a submit binding must be a function");
2622 ko.utils.registerEventHandler(element, "submit", function (event) {
2623 var handlerReturnValue;
2624 var value = valueAccessor();
2625 try { handlerReturnValue = value.call(viewModel, element); }
2627 if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
2628 if (event.preventDefault)
2629 event.preventDefault();
2631 event.returnValue = false;
2637 ko.bindingHandlers['text'] = {
2638 'update': function (element, valueAccessor) {
2639 ko.utils.setTextContent(element, valueAccessor());
2642 ko.virtualElements.allowedBindings['text'] = true;
2643 ko.bindingHandlers['uniqueName'] = {
2644 'init': function (element, valueAccessor) {
2645 if (valueAccessor()) {
2646 var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
2647 ko.utils.setElementName(element, name);
2651 ko.bindingHandlers['uniqueName'].currentIndex = 0;
2652 ko.bindingHandlers['value'] = {
2653 'init': function (element, valueAccessor, allBindingsAccessor) {
2654 // Always catch "change" event; possibly other events too if asked
2655 var eventsToCatch = ["change"];
2656 var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
2657 var propertyChangedFired = false;
2658 if (requestedEventsToCatch) {
2659 if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
2660 requestedEventsToCatch = [requestedEventsToCatch];
2661 ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
2662 eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
2665 var valueUpdateHandler = function() {
2666 propertyChangedFired = false;
2667 var modelValue = valueAccessor();
2668 var elementValue = ko.selectExtensions.readValue(element);
2669 ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
2672 // Workaround for https://github.com/SteveSanderson/knockout/issues/122
2673 // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
2674 var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
2675 && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
2676 if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
2677 ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
2678 ko.utils.registerEventHandler(element, "blur", function() {
2679 if (propertyChangedFired) {
2680 valueUpdateHandler();
2685 ko.utils.arrayForEach(eventsToCatch, function(eventName) {
2686 // The syntax "after<eventname>" means "run the handler asynchronously after the event"
2687 // This is useful, for example, to catch "keydown" events after the browser has updated the control
2688 // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
2689 var handler = valueUpdateHandler;
2690 if (ko.utils.stringStartsWith(eventName, "after")) {
2691 handler = function() { setTimeout(valueUpdateHandler, 0) };
2692 eventName = eventName.substring("after".length);
2694 ko.utils.registerEventHandler(element, eventName, handler);
2697 'update': function (element, valueAccessor) {
2698 var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
2699 var newValue = ko.utils.unwrapObservable(valueAccessor());
2700 var elementValue = ko.selectExtensions.readValue(element);
2701 var valueHasChanged = (newValue != elementValue);
2703 // JavaScript's 0 == "" behavious is unfortunate here as it prevents writing 0 to an empty text box (loose equality suggests the values are the same).
2704 // We don't want to do a strict equality comparison as that is more confusing for developers in certain cases, so we specifically special case 0 != "" here.
2705 if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
2706 valueHasChanged = true;
2708 if (valueHasChanged) {
2709 var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
2712 // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
2713 // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
2714 // to apply the value as well.
2715 var alsoApplyAsynchronously = valueIsSelectOption;
2716 if (alsoApplyAsynchronously)
2717 setTimeout(applyValueAction, 0);
2720 // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
2721 // because you're not allowed to have a model value that disagrees with a visible UI selection.
2722 if (valueIsSelectOption && (element.length > 0))
2723 ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
2726 ko.bindingHandlers['visible'] = {
2727 'update': function (element, valueAccessor) {
2728 var value = ko.utils.unwrapObservable(valueAccessor());
2729 var isCurrentlyVisible = !(element.style.display == "none");
2730 if (value && !isCurrentlyVisible)
2731 element.style.display = "";
2732 else if ((!value) && isCurrentlyVisible)
2733 element.style.display = "none";
2736 // 'click' is just a shorthand for the usual full-length event:{click:handler}
2737 makeEventHandlerShortcut('click');
2738 // If you want to make a custom template engine,
2740 // [1] Inherit from this class (like ko.nativeTemplateEngine does)
2741 // [2] Override 'renderTemplateSource', supplying a function with this signature:
2743 // function (templateSource, bindingContext, options) {
2744 // // - templateSource.text() is the text of the template you should render
2745 // // - bindingContext.$data is the data you should pass into the template
2746 // // - you might also want to make bindingContext.$parent, bindingContext.$parents,
2747 // // and bindingContext.$root available in the template too
2748 // // - options gives you access to any other properties set on "data-bind: { template: options }"
2750 // // Return value: an array of DOM nodes
2753 // [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
2755 // function (script) {
2756 // // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
2757 // // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
2760 // This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
2761 // If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
2762 // and then you don't need to override 'createJavaScriptEvaluatorBlock'.
2764 ko.templateEngine = function () { };
2766 ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
2767 throw new Error("Override renderTemplateSource");
2770 ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
2771 throw new Error("Override createJavaScriptEvaluatorBlock");
2774 ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
2776 if (typeof template == "string") {
2777 templateDocument = templateDocument || document;
2778 var elem = templateDocument.getElementById(template);
2780 throw new Error("Cannot find template with ID " + template);
2781 return new ko.templateSources.domElement(elem);
2782 } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
2783 // Anonymous template
2784 return new ko.templateSources.anonymousTemplate(template);
2786 throw new Error("Unknown template type: " + template);
2789 ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
2790 var templateSource = this['makeTemplateSource'](template, templateDocument);
2791 return this['renderTemplateSource'](templateSource, bindingContext, options);
2794 ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
2795 // Skip rewriting if requested
2796 if (this['allowTemplateRewriting'] === false)
2798 return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
2801 ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
2802 var templateSource = this['makeTemplateSource'](template, templateDocument);
2803 var rewritten = rewriterCallback(templateSource['text']());
2804 templateSource['text'](rewritten);
2805 templateSource['data']("isRewritten", true);
2808 ko.exportSymbol('templateEngine', ko.templateEngine);
2810 ko.templateRewriting = (function () {
2811 var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
2812 var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
2814 function validateDataBindValuesForRewriting(keyValueArray) {
2815 var allValidators = ko.expressionRewriting.bindingRewriteValidators;
2816 for (var i = 0; i < keyValueArray.length; i++) {
2817 var key = keyValueArray[i]['key'];
2818 if (allValidators.hasOwnProperty(key)) {
2819 var validator = allValidators[key];
2821 if (typeof validator === "function") {
2822 var possibleErrorMessage = validator(keyValueArray[i]['value']);
2823 if (possibleErrorMessage)
2824 throw new Error(possibleErrorMessage);
2825 } else if (!validator) {
2826 throw new Error("This template engine does not support the '" + key + "' binding within its templates");
2832 function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
2833 var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
2834 validateDataBindValuesForRewriting(dataBindKeyValueArray);
2835 var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray);
2837 // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
2838 // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
2839 // extra indirection.
2840 var applyBindingsToNextSiblingScript =
2841 "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()})";
2842 return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
2846 ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
2847 if (!templateEngine['isTemplateRewritten'](template, templateDocument))
2848 templateEngine['rewriteTemplate'](template, function (htmlString) {
2849 return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
2850 }, templateDocument);
2853 memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
2854 return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
2855 return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
2856 }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
2857 return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
2861 applyMemoizedBindingsToNextSibling: function (bindings) {
2862 return ko.memoization.memoize(function (domNode, bindingContext) {
2863 if (domNode.nextSibling)
2864 ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
2871 // Exported only because it has to be referenced by string lookup from within rewritten template
2872 ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
2874 // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
2875 // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
2877 // Two are provided by default:
2878 // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
2879 // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
2880 // without reading/writing the actual element text content, since it will be overwritten
2881 // with the rendered template output.
2882 // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
2883 // Template sources need to have the following functions:
2884 // text() - returns the template text from your storage location
2885 // text(value) - writes the supplied template text to your storage location
2886 // data(key) - reads values stored using data(key, value) - see below
2887 // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
2889 // Optionally, template sources can also have the following functions:
2890 // nodes() - returns a DOM element containing the nodes of this template, where available
2891 // nodes(value) - writes the given DOM element to your storage location
2892 // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
2893 // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
2895 // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
2896 // using and overriding "makeTemplateSource" to return an instance of your custom template source.
2898 ko.templateSources = {};
2900 // ---- ko.templateSources.domElement -----
2902 ko.templateSources.domElement = function(element) {
2903 this.domElement = element;
2906 ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
2907 var tagNameLower = ko.utils.tagNameLower(this.domElement),
2908 elemContentsProperty = tagNameLower === "script" ? "text"
2909 : tagNameLower === "textarea" ? "value"
2912 if (arguments.length == 0) {
2913 return this.domElement[elemContentsProperty];
2915 var valueToWrite = arguments[0];
2916 if (elemContentsProperty === "innerHTML")
2917 ko.utils.setHtml(this.domElement, valueToWrite);
2919 this.domElement[elemContentsProperty] = valueToWrite;
2923 ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
2924 if (arguments.length === 1) {
2925 return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
2927 ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
2931 // ---- ko.templateSources.anonymousTemplate -----
2932 // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
2933 // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
2934 // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
2936 var anonymousTemplatesDomDataKey = "__ko_anon_template__";
2937 ko.templateSources.anonymousTemplate = function(element) {
2938 this.domElement = element;
2940 ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
2941 ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
2942 if (arguments.length == 0) {
2943 var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
2944 if (templateData.textData === undefined && templateData.containerData)
2945 templateData.textData = templateData.containerData.innerHTML;
2946 return templateData.textData;
2948 var valueToWrite = arguments[0];
2949 ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
2952 ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
2953 if (arguments.length == 0) {
2954 var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
2955 return templateData.containerData;
2957 var valueToWrite = arguments[0];
2958 ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
2962 ko.exportSymbol('templateSources', ko.templateSources);
2963 ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
2964 ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
2967 var _templateEngine;
2968 ko.setTemplateEngine = function (templateEngine) {
2969 if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
2970 throw new Error("templateEngine must inherit from ko.templateEngine");
2971 _templateEngine = templateEngine;
2974 function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
2975 var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
2976 while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
2977 nextInQueue = ko.virtualElements.nextSibling(node);
2978 if (node.nodeType === 1 || node.nodeType === 8)
2983 function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
2984 // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
2985 // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
2986 // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
2987 // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
2988 // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
2990 if (continuousNodeArray.length) {
2991 var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
2993 // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
2994 // whereas a regular applyBindings won't introduce new memoized nodes
2995 invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
2996 ko.applyBindings(bindingContext, node);
2998 invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
2999 ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
3004 function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
3005 return nodeOrNodeArray.nodeType ? nodeOrNodeArray
3006 : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
3010 function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
3011 options = options || {};
3012 var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
3013 var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
3014 var templateEngineToUse = (options['templateEngine'] || _templateEngine);
3015 ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
3016 var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
3018 // Loosely check result is an array of DOM nodes
3019 if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
3020 throw new Error("Template engine must return an array of DOM nodes");
3022 var haveAddedNodesToParent = false;
3023 switch (renderMode) {
3024 case "replaceChildren":
3025 ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
3026 haveAddedNodesToParent = true;
3029 ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
3030 haveAddedNodesToParent = true;
3032 case "ignoreTargetNode": break;
3034 throw new Error("Unknown renderMode: " + renderMode);
3037 if (haveAddedNodesToParent) {
3038 activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
3039 if (options['afterRender'])
3040 ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
3043 return renderedNodesArray;
3046 ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
3047 options = options || {};
3048 if ((options['templateEngine'] || _templateEngine) == undefined)
3049 throw new Error("Set a template engine before calling renderTemplate");
3050 renderMode = renderMode || "replaceChildren";
3052 if (targetNodeOrNodeArray) {
3053 var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
3055 var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
3056 var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
3058 return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
3060 // Ensure we've got a proper binding context to work with
3061 var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
3062 ? dataOrBindingContext
3063 : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
3065 // Support selecting template as a function of the data being rendered
3066 var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
3068 var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
3069 if (renderMode == "replaceNode") {
3070 targetNodeOrNodeArray = renderedNodesArray;
3071 firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
3075 { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
3078 // 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
3079 return ko.memoization.memoize(function (domNode) {
3080 ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
3085 ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
3086 // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
3087 // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
3088 var arrayItemContext;
3090 // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
3091 var executeTemplateForArrayItem = function (arrayValue, index) {
3092 // Support selecting template as a function of the data being rendered
3093 arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue), options['as']);
3094 arrayItemContext['$index'] = index;
3095 var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
3096 return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
3099 // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
3100 var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
3101 activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
3102 if (options['afterRender'])
3103 options['afterRender'](addedNodesArray, arrayValue);
3106 return ko.dependentObservable(function () {
3107 var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
3108 if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
3109 unwrappedArray = [unwrappedArray];
3111 // Filter out any entries marked as destroyed
3112 var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
3113 return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
3116 // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
3117 // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
3118 ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
3120 }, null, { disposeWhenNodeIsRemoved: targetNode });
3123 var templateComputedDomDataKey = '__ko__templateComputedDomDataKey__';
3124 function disposeOldComputedAndStoreNewOne(element, newComputed) {
3125 var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
3126 if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
3127 oldComputed.dispose();
3128 ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
3131 ko.bindingHandlers['template'] = {
3132 'init': function(element, valueAccessor) {
3133 // Support anonymous templates
3134 var bindingValue = ko.utils.unwrapObservable(valueAccessor());
3135 if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
3136 // It's an anonymous template - store the element contents, then clear the element
3137 var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
3138 container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
3139 new ko.templateSources.anonymousTemplate(element)['nodes'](container);
3141 return { 'controlsDescendantBindings': true };
3143 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
3144 var templateName = ko.utils.unwrapObservable(valueAccessor()),
3146 shouldDisplay = true,
3148 templateComputed = null;
3150 if (typeof templateName != "string") {
3151 options = templateName;
3152 templateName = options['name'];
3154 // Support "if"/"ifnot" conditions
3155 if ('if' in options)
3156 shouldDisplay = ko.utils.unwrapObservable(options['if']);
3157 if (shouldDisplay && 'ifnot' in options)
3158 shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
3160 dataValue = ko.utils.unwrapObservable(options['data']);
3163 if ('foreach' in options) {
3164 // Render once for each data point (treating data set as empty if shouldDisplay==false)
3165 var dataArray = (shouldDisplay && options['foreach']) || [];
3166 templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
3167 } else if (!shouldDisplay) {
3168 ko.virtualElements.emptyNode(element);
3170 // Render once for this single data point (or use the viewModel if no data was provided)
3171 var innerBindingContext = ('data' in options) ?
3172 bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
3173 bindingContext; // Given no explicit 'data' value, we retain the same binding context
3174 templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
3177 // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
3178 disposeOldComputedAndStoreNewOne(element, templateComputed);
3182 // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
3183 ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
3184 var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
3186 if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
3187 return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
3189 if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
3190 return null; // Named templates can be rewritten, so return "no error"
3191 return "This template engine does not support anonymous templates nested within its templates";
3194 ko.virtualElements.allowedBindings['template'] = true;
3197 ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
3198 ko.exportSymbol('renderTemplate', ko.renderTemplate);
3200 ko.utils.compareArrays = (function () {
3201 var statusNotInOld = 'added', statusNotInNew = 'deleted';
3203 // Simple calculation based on Levenshtein distance.
3204 function compareArrays(oldArray, newArray, dontLimitMoves) {
3205 oldArray = oldArray || [];
3206 newArray = newArray || [];
3208 if (oldArray.length <= newArray.length)
3209 return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, dontLimitMoves);
3211 return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, dontLimitMoves);
3214 function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, dontLimitMoves) {
3215 var myMin = Math.min,
3217 editDistanceMatrix = [],
3218 smlIndex, smlIndexMax = smlArray.length,
3219 bigIndex, bigIndexMax = bigArray.length,
3220 compareRange = (bigIndexMax - smlIndexMax) || 1,
3221 maxDistance = smlIndexMax + bigIndexMax + 1,
3223 bigIndexMaxForRow, bigIndexMinForRow;
3225 for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
3227 editDistanceMatrix.push(thisRow = []);
3228 bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
3229 bigIndexMinForRow = myMax(0, smlIndex - 1);
3230 for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
3232 thisRow[bigIndex] = smlIndex + 1;
3233 else if (!smlIndex) // Top row - transform empty array into new array via additions
3234 thisRow[bigIndex] = bigIndex + 1;
3235 else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
3236 thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
3238 var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
3239 var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
3240 thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
3245 var editScript = [], meMinusOne, notInSml = [], notInBig = [];
3246 for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
3247 meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
3248 if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
3249 notInSml.push(editScript[editScript.length] = { // added
3250 'status': statusNotInSml,
3251 'value': bigArray[--bigIndex],
3252 'index': bigIndex });
3253 } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
3254 notInBig.push(editScript[editScript.length] = { // deleted
3255 'status': statusNotInBig,
3256 'value': smlArray[--smlIndex],
3257 'index': smlIndex });
3260 'status': "retained",
3261 'value': bigArray[--bigIndex] });
3266 if (notInSml.length && notInBig.length) {
3267 // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
3268 // smlIndexMax keeps the time complexity of this algorithm linear.
3269 var limitFailedCompares = smlIndexMax * 10, failedCompares,
3270 a, d, notInSmlItem, notInBigItem;
3271 // Go through the items that have been added and deleted and try to find matches between them.
3272 for (failedCompares = a = 0; (dontLimitMoves || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
3273 for (d = 0; notInBigItem = notInBig[d]; d++) {
3274 if (notInSmlItem['value'] === notInBigItem['value']) {
3275 notInSmlItem['moved'] = notInBigItem['index'];
3276 notInBigItem['moved'] = notInSmlItem['index'];
3277 notInBig.splice(d,1); // This item is marked as moved; so remove it from notInBig list
3278 failedCompares = d = 0; // Reset failed compares count because we're checking for consecutive failures
3282 failedCompares += d;
3285 return editScript.reverse();
3288 return compareArrays;
3291 ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
3295 // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
3296 // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
3297 // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
3298 // 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
3299 // previously mapped - retain those nodes, and just insert/delete other ones
3301 // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
3302 // You can use this, for example, to activate bindings on those nodes.
3304 function fixUpNodesToBeMovedOrRemoved(contiguousNodeArray) {
3305 // Before moving, deleting, or replacing a set of nodes that were previously outputted by the "map" function, we have to reconcile
3306 // them against what is in the DOM right now. It may be that some of the nodes have already been removed from the document,
3307 // or that new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
3308 // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
3309 // So, this function translates the old "map" output array into its best guess of what set of current DOM nodes should be removed.
3312 // [A] Any leading nodes that aren't in the document any more should be ignored
3313 // These most likely correspond to memoization nodes that were already removed during binding
3314 // See https://github.com/SteveSanderson/knockout/pull/440
3315 // [B] We want to output a contiguous series of nodes that are still in the document. So, ignore any nodes that
3316 // have already been removed, and include any nodes that have been inserted among the previous collection
3319 while (contiguousNodeArray.length && !ko.utils.domNodeIsAttachedToDocument(contiguousNodeArray[0]))
3320 contiguousNodeArray.splice(0, 1);
3323 if (contiguousNodeArray.length > 1) {
3324 // Build up the actual new contiguous node set
3325 var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
3326 while (current !== last) {
3327 current = current.nextSibling;
3328 if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
3330 newContiguousSet.push(current);
3333 // ... then mutate the input array to match this.
3334 // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
3335 Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
3337 return contiguousNodeArray;
3340 function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
3341 // Map this array value inside a dependentObservable so we re-map when any dependency changes
3342 var mappedNodes = [];
3343 var dependentObservable = ko.dependentObservable(function() {
3344 var newMappedNodes = mapping(valueToMap, index) || [];
3346 // On subsequent evaluations, just replace the previously-inserted DOM nodes
3347 if (mappedNodes.length > 0) {
3348 ko.utils.replaceDomNodes(fixUpNodesToBeMovedOrRemoved(mappedNodes), newMappedNodes);
3349 if (callbackAfterAddingNodes)
3350 ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
3353 // Replace the contents of the mappedNodes array, thereby updating the record
3354 // of which nodes would be deleted if valueToMap was itself later removed
3355 mappedNodes.splice(0, mappedNodes.length);
3356 ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
3357 }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
3358 return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
3361 var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
3363 ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
3364 // Compare the provided array against the previous one
3365 array = array || [];
3366 options = options || {};
3367 var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
3368 var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
3369 var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
3370 var editScript = ko.utils.compareArrays(lastArray, array);
3372 // Build the new mapping result
3373 var newMappingResult = [];
3374 var lastMappingResultIndex = 0;
3375 var newMappingResultIndex = 0;
3377 var nodesToDelete = [];
3378 var itemsToProcess = [];
3379 var itemsForBeforeRemoveCallbacks = [];
3380 var itemsForMoveCallbacks = [];
3381 var itemsForAfterAddCallbacks = [];
3384 function itemMovedOrRetained(editScriptIndex, oldPosition) {
3385 mapData = lastMappingResult[oldPosition];
3386 if (newMappingResultIndex !== oldPosition)
3387 itemsForMoveCallbacks[editScriptIndex] = mapData;
3388 // Since updating the index might change the nodes, do so before calling fixUpNodesToBeMovedOrRemoved
3389 mapData.indexObservable(newMappingResultIndex++);
3390 fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes);
3391 newMappingResult.push(mapData);
3392 itemsToProcess.push(mapData);
3395 function callCallback(callback, items) {
3397 for (var i = 0, n = items.length; i < n; i++) {
3399 ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
3400 callback(node, i, items[i].arrayEntry);
3407 for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
3408 movedIndex = editScriptItem['moved'];
3409 switch (editScriptItem['status']) {
3411 if (movedIndex === undefined) {
3412 mapData = lastMappingResult[lastMappingResultIndex];
3414 // Stop tracking changes to the mapping for these nodes
3415 if (mapData.dependentObservable)
3416 mapData.dependentObservable.dispose();
3418 // Queue these nodes for later removal
3419 nodesToDelete.push.apply(nodesToDelete, fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes));
3420 if (options['beforeRemove']) {
3421 itemsForBeforeRemoveCallbacks[i] = mapData;
3422 itemsToProcess.push(mapData);
3425 lastMappingResultIndex++;
3429 itemMovedOrRetained(i, lastMappingResultIndex++);
3433 if (movedIndex !== undefined) {
3434 itemMovedOrRetained(i, movedIndex);
3436 mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
3437 newMappingResult.push(mapData);
3438 itemsToProcess.push(mapData);
3439 if (!isFirstExecution)
3440 itemsForAfterAddCallbacks[i] = mapData;
3446 // Call beforeMove first before any changes have been made to the DOM
3447 callCallback(options['beforeMove'], itemsForMoveCallbacks);
3449 // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
3450 ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
3452 // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
3453 for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
3454 // Get nodes for newly added items
3455 if (!mapData.mappedNodes)
3456 ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
3458 // Put nodes in the right place if they aren't there already
3459 for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
3460 if (node !== nextNode)
3461 ko.virtualElements.insertAfter(domNode, node, lastNode);
3464 // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
3465 if (!mapData.initialized && callbackAfterAddingNodes) {
3466 callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
3467 mapData.initialized = true;
3471 // If there's a beforeRemove callback, call it after reordering.
3472 // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
3473 // some sort of animation, which is why we first reorder the nodes that will be removed. If the
3474 // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
3475 // Perhaps we'll make that change in the future if this scenario becomes more common.
3476 callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
3478 // Finally call afterMove and afterAdd callbacks
3479 callCallback(options['afterMove'], itemsForMoveCallbacks);
3480 callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
3482 // Store a copy of the array items we just considered so we can difference it next time
3483 ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
3487 ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
3488 ko.nativeTemplateEngine = function () {
3489 this['allowTemplateRewriting'] = false;
3492 ko.nativeTemplateEngine.prototype = new ko.templateEngine();
3493 ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
3494 var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
3495 templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
3496 templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
3498 if (templateNodes) {
3499 return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
3501 var templateText = templateSource['text']();
3502 return ko.utils.parseHtmlFragment(templateText);
3506 ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
3507 ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
3509 ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
3511 ko.jqueryTmplTemplateEngine = function () {
3512 // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
3513 // doesn't expose a version number, so we have to infer it.
3514 // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
3515 // which KO internally refers to as version "2", so older versions are no longer detected.
3516 var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
3517 if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
3519 // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
3521 if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
3522 // Since 1.0.0pre, custom tags should append markup to an array called "__"
3523 return 2; // Final version of jquery.tmpl
3525 } catch(ex) { /* Apparently not the version we were looking for */ }
3527 return 1; // Any older version that we don't support
3530 function ensureHasReferencedJQueryTemplates() {
3531 if (jQueryTmplVersion < 2)
3532 throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
3535 function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
3536 return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
3539 this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
3540 options = options || {};
3541 ensureHasReferencedJQueryTemplates();
3543 // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
3544 var precompiled = templateSource['data']('precompiled');
3546 var templateText = templateSource['text']() || "";
3547 // Wrap in "with($whatever.koBindingContext) { ... }"
3548 templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
3550 precompiled = jQuery['template'](null, templateText);
3551 templateSource['data']('precompiled', precompiled);
3554 var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
3555 var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
3557 var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
3558 resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
3560 jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
3564 this['createJavaScriptEvaluatorBlock'] = function(script) {
3565 return "{{ko_code ((function() { return " + script + " })()) }}";
3568 this['addTemplate'] = function(templateName, templateMarkup) {
3569 document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
3572 if (jQueryTmplVersion > 0) {
3573 jQuery['tmpl']['tag']['ko_code'] = {
3574 open: "__.push($1 || '');"
3576 jQuery['tmpl']['tag']['ko_with'] = {
3583 ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
3585 // Use this one by default *only if jquery.tmpl is referenced*
3586 var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
3587 if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
3588 ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
3590 ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
3593 })(window,document,navigator,window["jQuery"]);