--- /dev/null
+// Knockout JavaScript library v2.0.0\r
+// (c) Steven Sanderson - http://knockoutjs.com/\r
+// License: MIT (http://www.opensource.org/licenses/mit-license.php)\r
+\r
+(function(window,undefined){ \r
+var ko = window["ko"] = {};\r
+// Google Closure Compiler helpers (used only to make the minified file smaller)\r
+ko.exportSymbol = function(publicPath, object) {\r
+ var tokens = publicPath.split(".");\r
+ var target = window;\r
+ for (var i = 0; i < tokens.length - 1; i++)\r
+ target = target[tokens[i]];\r
+ target[tokens[tokens.length - 1]] = object;\r
+};\r
+ko.exportProperty = function(owner, publicName, object) {\r
+ owner[publicName] = object;\r
+};\r
+ko.utils = new (function () {\r
+ var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;\r
+ \r
+ // 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)\r
+ var knownEvents = {}, knownEventTypesByEventName = {};\r
+ var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';\r
+ knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];\r
+ knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave']; \r
+ for (var eventType in knownEvents) {\r
+ var knownEventsForType = knownEvents[eventType];\r
+ if (knownEventsForType.length) {\r
+ for (var i = 0, j = knownEventsForType.length; i < j; i++)\r
+ knownEventTypesByEventName[knownEventsForType[i]] = eventType;\r
+ }\r
+ }\r
+\r
+ // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)\r
+ var ieVersion = (function() {\r
+ var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');\r
+ \r
+ // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment\r
+ while (\r
+ div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',\r
+ iElems[0]\r
+ ); \r
+ return version > 4 ? version : undefined; \r
+ }());\r
+ var isIe6 = ieVersion === 6,\r
+ isIe7 = ieVersion === 7;\r
+\r
+ function isClickOnCheckableElement(element, eventType) {\r
+ if ((element.tagName != "INPUT") || !element.type) return false;\r
+ if (eventType.toLowerCase() != "click") return false;\r
+ var inputType = element.type.toLowerCase();\r
+ return (inputType == "checkbox") || (inputType == "radio");\r
+ }\r
+ \r
+ return {\r
+ fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],\r
+ \r
+ arrayForEach: function (array, action) {\r
+ for (var i = 0, j = array.length; i < j; i++)\r
+ action(array[i]);\r
+ },\r
+\r
+ arrayIndexOf: function (array, item) {\r
+ if (typeof Array.prototype.indexOf == "function")\r
+ return Array.prototype.indexOf.call(array, item);\r
+ for (var i = 0, j = array.length; i < j; i++)\r
+ if (array[i] === item)\r
+ return i;\r
+ return -1;\r
+ },\r
+\r
+ arrayFirst: function (array, predicate, predicateOwner) {\r
+ for (var i = 0, j = array.length; i < j; i++)\r
+ if (predicate.call(predicateOwner, array[i]))\r
+ return array[i];\r
+ return null;\r
+ },\r
+\r
+ arrayRemoveItem: function (array, itemToRemove) {\r
+ var index = ko.utils.arrayIndexOf(array, itemToRemove);\r
+ if (index >= 0)\r
+ array.splice(index, 1);\r
+ },\r
+\r
+ arrayGetDistinctValues: function (array) {\r
+ array = array || [];\r
+ var result = [];\r
+ for (var i = 0, j = array.length; i < j; i++) {\r
+ if (ko.utils.arrayIndexOf(result, array[i]) < 0)\r
+ result.push(array[i]);\r
+ }\r
+ return result;\r
+ }, \r
+\r
+ arrayMap: function (array, mapping) {\r
+ array = array || [];\r
+ var result = [];\r
+ for (var i = 0, j = array.length; i < j; i++)\r
+ result.push(mapping(array[i]));\r
+ return result;\r
+ },\r
+\r
+ arrayFilter: function (array, predicate) {\r
+ array = array || [];\r
+ var result = [];\r
+ for (var i = 0, j = array.length; i < j; i++)\r
+ if (predicate(array[i]))\r
+ result.push(array[i]);\r
+ return result;\r
+ },\r
+ \r
+ arrayPushAll: function (array, valuesToPush) {\r
+ for (var i = 0, j = valuesToPush.length; i < j; i++)\r
+ array.push(valuesToPush[i]); \r
+ return array;\r
+ },\r
+\r
+ extend: function (target, source) {\r
+ for(var prop in source) {\r
+ if(source.hasOwnProperty(prop)) {\r
+ target[prop] = source[prop];\r
+ }\r
+ }\r
+ return target;\r
+ },\r
+\r
+ emptyDomNode: function (domNode) {\r
+ while (domNode.firstChild) {\r
+ ko.removeNode(domNode.firstChild);\r
+ }\r
+ },\r
+\r
+ setDomNodeChildren: function (domNode, childNodes) {\r
+ ko.utils.emptyDomNode(domNode);\r
+ if (childNodes) {\r
+ ko.utils.arrayForEach(childNodes, function (childNode) {\r
+ domNode.appendChild(childNode);\r
+ });\r
+ }\r
+ },\r
+\r
+ replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {\r
+ var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;\r
+ if (nodesToReplaceArray.length > 0) {\r
+ var insertionPoint = nodesToReplaceArray[0];\r
+ var parent = insertionPoint.parentNode;\r
+ for (var i = 0, j = newNodesArray.length; i < j; i++)\r
+ parent.insertBefore(newNodesArray[i], insertionPoint);\r
+ for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {\r
+ ko.removeNode(nodesToReplaceArray[i]);\r
+ }\r
+ }\r
+ },\r
+\r
+ setOptionNodeSelectionState: function (optionNode, isSelected) {\r
+ // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.\r
+ if (navigator.userAgent.indexOf("MSIE 6") >= 0)\r
+ optionNode.setAttribute("selected", isSelected);\r
+ else\r
+ optionNode.selected = isSelected;\r
+ },\r
+ \r
+ stringTrim: function (string) {\r
+ return (string || "").replace(stringTrimRegex, "");\r
+ },\r
+\r
+ stringTokenize: function (string, delimiter) {\r
+ var result = [];\r
+ var tokens = (string || "").split(delimiter);\r
+ for (var i = 0, j = tokens.length; i < j; i++) {\r
+ var trimmed = ko.utils.stringTrim(tokens[i]);\r
+ if (trimmed !== "")\r
+ result.push(trimmed);\r
+ }\r
+ return result;\r
+ },\r
+ \r
+ stringStartsWith: function (string, startsWith) { \r
+ string = string || "";\r
+ if (startsWith.length > string.length)\r
+ return false;\r
+ return string.substring(0, startsWith.length) === startsWith;\r
+ },\r
+\r
+ evalWithinScope: function (expression /*, scope1, scope2, scope3... */) {\r
+ // Build the source for a function that evaluates "expression"\r
+ // For each scope variable, add an extra level of "with" nesting\r
+ // Example result: with(sc[1]) { with(sc[0]) { return (expression) } }\r
+ var scopes = Array.prototype.slice.call(arguments, 1);\r
+ var functionBody = "return (" + expression + ")";\r
+ for (var i = 0; i < scopes.length; i++) {\r
+ if (scopes[i] && typeof scopes[i] == "object")\r
+ functionBody = "with(sc[" + i + "]) { " + functionBody + " } ";\r
+ }\r
+ return (new Function("sc", functionBody))(scopes);\r
+ },\r
+\r
+ domNodeIsContainedBy: function (node, containedByNode) {\r
+ if (containedByNode.compareDocumentPosition)\r
+ return (containedByNode.compareDocumentPosition(node) & 16) == 16;\r
+ while (node != null) {\r
+ if (node == containedByNode)\r
+ return true;\r
+ node = node.parentNode;\r
+ }\r
+ return false;\r
+ },\r
+\r
+ domNodeIsAttachedToDocument: function (node) {\r
+ return ko.utils.domNodeIsContainedBy(node, document);\r
+ },\r
+\r
+ registerEventHandler: function (element, eventType, handler) {\r
+ if (typeof jQuery != "undefined") {\r
+ if (isClickOnCheckableElement(element, eventType)) {\r
+ // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:\r
+ // it toggles the element checked state *after* the click event handlers run, whereas native\r
+ // click events toggle the checked state *before* the event handler. \r
+ // Fix this by intecepting the handler and applying the correct checkedness before it runs. \r
+ var originalHandler = handler;\r
+ handler = function(event, eventData) {\r
+ var jQuerySuppliedCheckedState = this.checked;\r
+ if (eventData)\r
+ this.checked = eventData.checkedStateBeforeEvent !== true;\r
+ originalHandler.call(this, event);\r
+ this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied\r
+ }; \r
+ }\r
+ jQuery(element)['bind'](eventType, handler);\r
+ } else if (typeof element.addEventListener == "function")\r
+ element.addEventListener(eventType, handler, false);\r
+ else if (typeof element.attachEvent != "undefined")\r
+ element.attachEvent("on" + eventType, function (event) {\r
+ handler.call(element, event);\r
+ });\r
+ else\r
+ throw new Error("Browser doesn't support addEventListener or attachEvent");\r
+ },\r
+\r
+ triggerEvent: function (element, eventType) {\r
+ if (!(element && element.nodeType))\r
+ throw new Error("element must be a DOM node when calling triggerEvent");\r
+\r
+ if (typeof jQuery != "undefined") {\r
+ var eventData = [];\r
+ if (isClickOnCheckableElement(element, eventType)) {\r
+ // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler\r
+ eventData.push({ checkedStateBeforeEvent: element.checked });\r
+ }\r
+ jQuery(element)['trigger'](eventType, eventData);\r
+ } else if (typeof document.createEvent == "function") {\r
+ if (typeof element.dispatchEvent == "function") {\r
+ var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";\r
+ var event = document.createEvent(eventCategory);\r
+ event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);\r
+ element.dispatchEvent(event);\r
+ }\r
+ else\r
+ throw new Error("The supplied element doesn't support dispatchEvent");\r
+ } else if (typeof element.fireEvent != "undefined") {\r
+ // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event\r
+ // so to make it consistent, we'll do it manually here\r
+ if (eventType == "click") {\r
+ if ((element.tagName == "INPUT") && ((element.type.toLowerCase() == "checkbox") || (element.type.toLowerCase() == "radio")))\r
+ element.checked = element.checked !== true;\r
+ }\r
+ element.fireEvent("on" + eventType);\r
+ }\r
+ else\r
+ throw new Error("Browser doesn't support triggering events");\r
+ },\r
+\r
+ unwrapObservable: function (value) {\r
+ return ko.isObservable(value) ? value() : value;\r
+ },\r
+\r
+ domNodeHasCssClass: function (node, className) {\r
+ var currentClassNames = (node.className || "").split(/\s+/);\r
+ return ko.utils.arrayIndexOf(currentClassNames, className) >= 0;\r
+ },\r
+\r
+ toggleDomNodeCssClass: function (node, className, shouldHaveClass) {\r
+ var hasClass = ko.utils.domNodeHasCssClass(node, className);\r
+ if (shouldHaveClass && !hasClass) {\r
+ node.className = (node.className || "") + " " + className;\r
+ } else if (hasClass && !shouldHaveClass) {\r
+ var currentClassNames = (node.className || "").split(/\s+/);\r
+ var newClassName = "";\r
+ for (var i = 0; i < currentClassNames.length; i++)\r
+ if (currentClassNames[i] != className)\r
+ newClassName += currentClassNames[i] + " ";\r
+ node.className = ko.utils.stringTrim(newClassName);\r
+ }\r
+ },\r
+\r
+ outerHTML: function(node) {\r
+ // For Chrome on non-text nodes\r
+ // (Although IE supports outerHTML, the way it formats HTML is inconsistent - sometimes closing </li> tags are omitted, sometimes not. That caused https://github.com/SteveSanderson/knockout/issues/212.)\r
+ if (ieVersion === undefined) {\r
+ var nativeOuterHtml = node.outerHTML;\r
+ if (typeof nativeOuterHtml == "string")\r
+ return nativeOuterHtml;\r
+ }\r
+\r
+ // Other browsers\r
+ var dummyContainer = window.document.createElement("div");\r
+ dummyContainer.appendChild(node.cloneNode(true));\r
+ return dummyContainer.innerHTML;\r
+ },\r
+\r
+ setTextContent: function(element, textContent) {\r
+ var value = ko.utils.unwrapObservable(textContent);\r
+ if ((value === null) || (value === undefined))\r
+ value = "";\r
+\r
+ 'innerText' in element ? element.innerText = value\r
+ : element.textContent = value;\r
+ \r
+ if (ieVersion >= 9) {\r
+ // Believe it or not, this actually fixes an IE9 rendering bug. Insane. https://github.com/SteveSanderson/knockout/issues/209\r
+ element.innerHTML = element.innerHTML;\r
+ }\r
+ },\r
+\r
+ range: function (min, max) {\r
+ min = ko.utils.unwrapObservable(min);\r
+ max = ko.utils.unwrapObservable(max);\r
+ var result = [];\r
+ for (var i = min; i <= max; i++)\r
+ result.push(i);\r
+ return result;\r
+ },\r
+ \r
+ makeArray: function(arrayLikeObject) {\r
+ var result = [];\r
+ for (var i = 0, j = arrayLikeObject.length; i < j; i++) {\r
+ result.push(arrayLikeObject[i]);\r
+ };\r
+ return result;\r
+ },\r
+ \r
+ isIe6 : isIe6,\r
+ isIe7 : isIe7,\r
+ \r
+ getFormFields: function(form, fieldName) {\r
+ var fields = ko.utils.makeArray(form.getElementsByTagName("INPUT")).concat(ko.utils.makeArray(form.getElementsByTagName("TEXTAREA")));\r
+ var isMatchingField = (typeof fieldName == 'string') \r
+ ? function(field) { return field.name === fieldName }\r
+ : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate\r
+ var matches = [];\r
+ for (var i = fields.length - 1; i >= 0; i--) {\r
+ if (isMatchingField(fields[i]))\r
+ matches.push(fields[i]);\r
+ };\r
+ return matches;\r
+ },\r
+ \r
+ parseJson: function (jsonString) {\r
+ if (typeof jsonString == "string") {\r
+ jsonString = ko.utils.stringTrim(jsonString);\r
+ if (jsonString) {\r
+ if (window.JSON && window.JSON.parse) // Use native parsing where available\r
+ return window.JSON.parse(jsonString);\r
+ return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers\r
+ }\r
+ } \r
+ return null;\r
+ },\r
+\r
+ stringifyJson: function (data) {\r
+ if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))\r
+ 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");\r
+ return JSON.stringify(ko.utils.unwrapObservable(data));\r
+ },\r
+\r
+ postJson: function (urlOrForm, data, options) {\r
+ options = options || {};\r
+ var params = options['params'] || {};\r
+ var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;\r
+ var url = urlOrForm;\r
+ \r
+ // If we were given a form, use its 'action' URL and pick out any requested field values \r
+ if((typeof urlOrForm == 'object') && (urlOrForm.tagName == "FORM")) {\r
+ var originalForm = urlOrForm;\r
+ url = originalForm.action;\r
+ for (var i = includeFields.length - 1; i >= 0; i--) {\r
+ var fields = ko.utils.getFormFields(originalForm, includeFields[i]);\r
+ for (var j = fields.length - 1; j >= 0; j--) \r
+ params[fields[j].name] = fields[j].value;\r
+ }\r
+ } \r
+ \r
+ data = ko.utils.unwrapObservable(data);\r
+ var form = document.createElement("FORM");\r
+ form.style.display = "none";\r
+ form.action = url;\r
+ form.method = "post";\r
+ for (var key in data) {\r
+ var input = document.createElement("INPUT");\r
+ input.name = key;\r
+ input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));\r
+ form.appendChild(input);\r
+ }\r
+ for (var key in params) {\r
+ var input = document.createElement("INPUT");\r
+ input.name = key;\r
+ input.value = params[key];\r
+ form.appendChild(input);\r
+ } \r
+ document.body.appendChild(form);\r
+ options['submitter'] ? options['submitter'](form) : form.submit();\r
+ setTimeout(function () { form.parentNode.removeChild(form); }, 0);\r
+ }\r
+ }\r
+})();\r
+\r
+ko.exportSymbol('ko.utils', ko.utils);\r
+ko.utils.arrayForEach([\r
+ ['arrayForEach', ko.utils.arrayForEach],\r
+ ['arrayFirst', ko.utils.arrayFirst],\r
+ ['arrayFilter', ko.utils.arrayFilter],\r
+ ['arrayGetDistinctValues', ko.utils.arrayGetDistinctValues],\r
+ ['arrayIndexOf', ko.utils.arrayIndexOf],\r
+ ['arrayMap', ko.utils.arrayMap],\r
+ ['arrayPushAll', ko.utils.arrayPushAll],\r
+ ['arrayRemoveItem', ko.utils.arrayRemoveItem],\r
+ ['extend', ko.utils.extend],\r
+ ['fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost],\r
+ ['getFormFields', ko.utils.getFormFields],\r
+ ['postJson', ko.utils.postJson],\r
+ ['parseJson', ko.utils.parseJson],\r
+ ['registerEventHandler', ko.utils.registerEventHandler],\r
+ ['stringifyJson', ko.utils.stringifyJson],\r
+ ['range', ko.utils.range],\r
+ ['toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass],\r
+ ['triggerEvent', ko.utils.triggerEvent],\r
+ ['unwrapObservable', ko.utils.unwrapObservable]\r
+], function(item) {\r
+ ko.exportSymbol('ko.utils.' + item[0], item[1]);\r
+});\r
+\r
+if (!Function.prototype['bind']) {\r
+ // 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)\r
+ // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js\r
+ Function.prototype['bind'] = function (object) {\r
+ var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();\r
+ return function () {\r
+ return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));\r
+ }; \r
+ };\r
+}\r
+ko.utils.domData = new (function () {\r
+ var uniqueId = 0;\r
+ var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();\r
+ var dataStore = {};\r
+ return {\r
+ get: function (node, key) {\r
+ var allDataForNode = ko.utils.domData.getAll(node, false);\r
+ return allDataForNode === undefined ? undefined : allDataForNode[key];\r
+ },\r
+ set: function (node, key, value) {\r
+ if (value === undefined) {\r
+ // Make sure we don't actually create a new domData key if we are actually deleting a value\r
+ if (ko.utils.domData.getAll(node, false) === undefined)\r
+ return;\r
+ }\r
+ var allDataForNode = ko.utils.domData.getAll(node, true);\r
+ allDataForNode[key] = value;\r
+ },\r
+ getAll: function (node, createIfNotFound) {\r
+ var dataStoreKey = node[dataStoreKeyExpandoPropertyName];\r
+ var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null");\r
+ if (!hasExistingDataStore) {\r
+ if (!createIfNotFound)\r
+ return undefined;\r
+ dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;\r
+ dataStore[dataStoreKey] = {};\r
+ }\r
+ return dataStore[dataStoreKey];\r
+ },\r
+ clear: function (node) {\r
+ var dataStoreKey = node[dataStoreKeyExpandoPropertyName];\r
+ if (dataStoreKey) {\r
+ delete dataStore[dataStoreKey];\r
+ node[dataStoreKeyExpandoPropertyName] = null;\r
+ }\r
+ }\r
+ }\r
+})();\r
+\r
+ko.exportSymbol('ko.utils.domData', ko.utils.domData);\r
+ko.exportSymbol('ko.utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully\r
+ko.utils.domNodeDisposal = new (function () {\r
+ var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();\r
+ \r
+ function getDisposeCallbacksCollection(node, createIfNotFound) {\r
+ var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);\r
+ if ((allDisposeCallbacks === undefined) && createIfNotFound) {\r
+ allDisposeCallbacks = [];\r
+ ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);\r
+ }\r
+ return allDisposeCallbacks;\r
+ }\r
+ function destroyCallbacksCollection(node) {\r
+ ko.utils.domData.set(node, domDataKey, undefined);\r
+ }\r
+ \r
+ function cleanSingleNode(node) {\r
+ // Run all the dispose callbacks\r
+ var callbacks = getDisposeCallbacksCollection(node, false);\r
+ if (callbacks) {\r
+ callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)\r
+ for (var i = 0; i < callbacks.length; i++)\r
+ callbacks[i](node);\r
+ } \r
+ \r
+ // Also erase the DOM data\r
+ ko.utils.domData.clear(node); \r
+ \r
+ // Special support for jQuery here because it's so commonly used.\r
+ // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData\r
+ // so notify it to tear down any resources associated with the node & descendants here.\r
+ if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))\r
+ jQuery['cleanData']([node]); \r
+ }\r
+ \r
+ return {\r
+ addDisposeCallback : function(node, callback) {\r
+ if (typeof callback != "function")\r
+ throw new Error("Callback must be a function");\r
+ getDisposeCallbacksCollection(node, true).push(callback);\r
+ },\r
+ \r
+ removeDisposeCallback : function(node, callback) {\r
+ var callbacksCollection = getDisposeCallbacksCollection(node, false);\r
+ if (callbacksCollection) {\r
+ ko.utils.arrayRemoveItem(callbacksCollection, callback);\r
+ if (callbacksCollection.length == 0)\r
+ destroyCallbacksCollection(node);\r
+ }\r
+ },\r
+ \r
+ cleanNode : function(node) {\r
+ if ((node.nodeType != 1) && (node.nodeType != 9))\r
+ return;\r
+ cleanSingleNode(node);\r
+ \r
+ // Clone the descendants list in case it changes during iteration\r
+ var descendants = [];\r
+ ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));\r
+ for (var i = 0, j = descendants.length; i < j; i++)\r
+ cleanSingleNode(descendants[i]);\r
+ },\r
+ \r
+ removeNode : function(node) {\r
+ ko.cleanNode(node);\r
+ if (node.parentNode)\r
+ node.parentNode.removeChild(node);\r
+ }\r
+ }\r
+})();\r
+ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience\r
+ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience\r
+ko.exportSymbol('ko.cleanNode', ko.cleanNode); \r
+ko.exportSymbol('ko.removeNode', ko.removeNode);\r
+ko.exportSymbol('ko.utils.domNodeDisposal', ko.utils.domNodeDisposal);\r
+ko.exportSymbol('ko.utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);\r
+ko.exportSymbol('ko.utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);(function () {\r
+ var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;\r
+\r
+ function simpleHtmlParse(html) {\r
+ // Based on jQuery's "clean" function, but only accounting for table-related elements.\r
+ // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly\r
+\r
+ // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of\r
+ // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"\r
+ // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node\r
+ // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.\r
+ \r
+ // Trim whitespace, otherwise indexOf won't work as expected\r
+ var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");\r
+\r
+ // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column\r
+ var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||\r
+ !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||\r
+ (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||\r
+ /* anything else */ [0, "", ""];\r
+\r
+ // Go to html and back, then peel off extra wrappers\r
+ // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.\r
+ var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";\r
+ if (typeof window['innerShiv'] == "function") {\r
+ div.appendChild(window['innerShiv'](markup));\r
+ } else {\r
+ div.innerHTML = markup;\r
+ }\r
+\r
+ // Move to the right depth\r
+ while (wrap[0]--)\r
+ div = div.lastChild;\r
+\r
+ return ko.utils.makeArray(div.lastChild.childNodes);\r
+ }\r
+\r
+ function jQueryHtmlParse(html) {\r
+ var elems = jQuery['clean']([html]);\r
+\r
+ // 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.\r
+ // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.\r
+ // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.\r
+ if (elems && elems[0]) {\r
+ // Find the top-most parent element that's a direct child of a document fragment\r
+ var elem = elems[0];\r
+ while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)\r
+ elem = elem.parentNode;\r
+ // ... then detach it\r
+ if (elem.parentNode)\r
+ elem.parentNode.removeChild(elem);\r
+ }\r
+ \r
+ return elems;\r
+ }\r
+ \r
+ ko.utils.parseHtmlFragment = function(html) {\r
+ return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible\r
+ : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.\r
+ };\r
+ \r
+ ko.utils.setHtml = function(node, html) {\r
+ ko.utils.emptyDomNode(node);\r
+ \r
+ if ((html !== null) && (html !== undefined)) {\r
+ if (typeof html != 'string')\r
+ html = html.toString();\r
+ \r
+ // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,\r
+ // for example <tr> elements which are not normally allowed to exist on their own.\r
+ // If you've referenced jQuery we'll use that rather than duplicating its code.\r
+ if (typeof jQuery != 'undefined') {\r
+ jQuery(node)['html'](html);\r
+ } else {\r
+ // ... otherwise, use KO's own parsing logic.\r
+ var parsedNodes = ko.utils.parseHtmlFragment(html);\r
+ for (var i = 0; i < parsedNodes.length; i++)\r
+ node.appendChild(parsedNodes[i]);\r
+ } \r
+ } \r
+ };\r
+})();\r
+\r
+ko.exportSymbol('ko.utils.parseHtmlFragment', ko.utils.parseHtmlFragment);\r
+ko.exportSymbol('ko.utils.setHtml', ko.utils.setHtml);\r
+ko.memoization = (function () {\r
+ var memos = {};\r
+\r
+ function randomMax8HexChars() {\r
+ return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);\r
+ }\r
+ function generateRandomId() {\r
+ return randomMax8HexChars() + randomMax8HexChars();\r
+ }\r
+ function findMemoNodes(rootNode, appendToArray) {\r
+ if (!rootNode)\r
+ return;\r
+ if (rootNode.nodeType == 8) {\r
+ var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);\r
+ if (memoId != null)\r
+ appendToArray.push({ domNode: rootNode, memoId: memoId });\r
+ } else if (rootNode.nodeType == 1) {\r
+ for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)\r
+ findMemoNodes(childNodes[i], appendToArray);\r
+ }\r
+ }\r
+\r
+ return {\r
+ memoize: function (callback) {\r
+ if (typeof callback != "function")\r
+ throw new Error("You can only pass a function to ko.memoization.memoize()");\r
+ var memoId = generateRandomId();\r
+ memos[memoId] = callback;\r
+ return "<!--[ko_memo:" + memoId + "]-->";\r
+ },\r
+\r
+ unmemoize: function (memoId, callbackParams) {\r
+ var callback = memos[memoId];\r
+ if (callback === undefined)\r
+ throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");\r
+ try {\r
+ callback.apply(null, callbackParams || []);\r
+ return true;\r
+ }\r
+ finally { delete memos[memoId]; }\r
+ },\r
+\r
+ unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {\r
+ var memos = [];\r
+ findMemoNodes(domNode, memos);\r
+ for (var i = 0, j = memos.length; i < j; i++) {\r
+ var node = memos[i].domNode;\r
+ var combinedParams = [node];\r
+ if (extraCallbackParamsArray)\r
+ ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);\r
+ ko.memoization.unmemoize(memos[i].memoId, combinedParams);\r
+ node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again\r
+ if (node.parentNode)\r
+ 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)\r
+ }\r
+ },\r
+\r
+ parseMemoText: function (memoText) {\r
+ var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);\r
+ return match ? match[1] : null;\r
+ }\r
+ };\r
+})();\r
+\r
+ko.exportSymbol('ko.memoization', ko.memoization);\r
+ko.exportSymbol('ko.memoization.memoize', ko.memoization.memoize);\r
+ko.exportSymbol('ko.memoization.unmemoize', ko.memoization.unmemoize);\r
+ko.exportSymbol('ko.memoization.parseMemoText', ko.memoization.parseMemoText);\r
+ko.exportSymbol('ko.memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);\r
+ko.extenders = {\r
+ 'throttle': function(target, timeout) {\r
+ // Throttling means two things:\r
+\r
+ // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies\r
+ // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate\r
+ target['throttleEvaluation'] = timeout;\r
+\r
+ // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*\r
+ // so the target cannot change value synchronously or faster than a certain rate\r
+ var writeTimeoutInstance = null;\r
+ return ko.dependentObservable({\r
+ 'read': target,\r
+ 'write': function(value) {\r
+ clearTimeout(writeTimeoutInstance);\r
+ writeTimeoutInstance = setTimeout(function() {\r
+ target(value);\r
+ }, timeout); \r
+ }\r
+ });\r
+ },\r
+\r
+ 'notify': function(target, notifyWhen) {\r
+ target["equalityComparer"] = notifyWhen == "always" \r
+ ? function() { return false } // Treat all values as not equal\r
+ : ko.observable["fn"]["equalityComparer"];\r
+ return target;\r
+ }\r
+};\r
+\r
+function applyExtenders(requestedExtenders) {\r
+ var target = this;\r
+ if (requestedExtenders) {\r
+ for (var key in requestedExtenders) {\r
+ var extenderHandler = ko.extenders[key];\r
+ if (typeof extenderHandler == 'function') {\r
+ target = extenderHandler(target, requestedExtenders[key]);\r
+ }\r
+ }\r
+ }\r
+ return target;\r
+}\r
+\r
+ko.exportSymbol('ko.extenders', ko.extenders);\r
+ko.subscription = function (callback, disposeCallback) {\r
+ this.callback = callback;\r
+ this.disposeCallback = disposeCallback;\r
+ ko.exportProperty(this, 'dispose', this.dispose);\r
+};\r
+ko.subscription.prototype.dispose = function () {\r
+ this.isDisposed = true;\r
+ this.disposeCallback();\r
+};\r
+\r
+ko.subscribable = function () {\r
+ this._subscriptions = {};\r
+\r
+ ko.utils.extend(this, ko.subscribable['fn']);\r
+ ko.exportProperty(this, 'subscribe', this.subscribe);\r
+ ko.exportProperty(this, 'extend', this.extend);\r
+ ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);\r
+}\r
+\r
+var defaultEvent = "change";\r
+\r
+ko.subscribable['fn'] = {\r
+ subscribe: function (callback, callbackTarget, event) {\r
+ event = event || defaultEvent;\r
+ var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;\r
+\r
+ var subscription = new ko.subscription(boundCallback, function () {\r
+ ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);\r
+ }.bind(this));\r
+\r
+ if (!this._subscriptions[event])\r
+ this._subscriptions[event] = [];\r
+ this._subscriptions[event].push(subscription);\r
+ return subscription;\r
+ },\r
+\r
+ "notifySubscribers": function (valueToNotify, event) {\r
+ event = event || defaultEvent;\r
+ if (this._subscriptions[event]) {\r
+ ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {\r
+ // In case a subscription was disposed during the arrayForEach cycle, check\r
+ // for isDisposed on each subscription before invoking its callback\r
+ if (subscription && (subscription.isDisposed !== true))\r
+ subscription.callback(valueToNotify);\r
+ });\r
+ }\r
+ },\r
+\r
+ getSubscriptionsCount: function () {\r
+ var total = 0;\r
+ for (var eventName in this._subscriptions) {\r
+ if (this._subscriptions.hasOwnProperty(eventName))\r
+ total += this._subscriptions[eventName].length;\r
+ }\r
+ return total;\r
+ },\r
+ \r
+ extend: applyExtenders\r
+};\r
+\r
+\r
+ko.isSubscribable = function (instance) {\r
+ return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";\r
+};\r
+\r
+ko.exportSymbol('ko.subscribable', ko.subscribable);\r
+ko.exportSymbol('ko.isSubscribable', ko.isSubscribable);\r
+\r
+ko.dependencyDetection = (function () {\r
+ var _frames = [];\r
+ \r
+ return {\r
+ begin: function (callback) {\r
+ _frames.push({ callback: callback, distinctDependencies:[] });\r
+ },\r
+\r
+ end: function () {\r
+ _frames.pop();\r
+ },\r
+\r
+ registerDependency: function (subscribable) {\r
+ if (!ko.isSubscribable(subscribable))\r
+ throw "Only subscribable things can act as dependencies";\r
+ if (_frames.length > 0) {\r
+ var topFrame = _frames[_frames.length - 1];\r
+ if (ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)\r
+ return;\r
+ topFrame.distinctDependencies.push(subscribable);\r
+ topFrame.callback(subscribable);\r
+ }\r
+ }\r
+ };\r
+})();var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };\r
+\r
+ko.observable = function (initialValue) {\r
+ var _latestValue = initialValue;\r
+\r
+ function observable() {\r
+ if (arguments.length > 0) {\r
+ // Write \r
+ \r
+ // Ignore writes if the value hasn't changed\r
+ if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {\r
+ observable.valueWillMutate();\r
+ _latestValue = arguments[0];\r
+ observable.valueHasMutated();\r
+ }\r
+ return this; // Permits chained assignments\r
+ }\r
+ else {\r
+ // Read\r
+ ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation\r
+ return _latestValue;\r
+ }\r
+ }\r
+ ko.subscribable.call(observable);\r
+ observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }\r
+ observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }\r
+ ko.utils.extend(observable, ko.observable['fn']);\r
+\r
+ ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);\r
+ ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);\r
+ \r
+ return observable;\r
+}\r
+\r
+ko.observable['fn'] = {\r
+ __ko_proto__: ko.observable,\r
+\r
+ "equalityComparer": function valuesArePrimitiveAndEqual(a, b) {\r
+ var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);\r
+ return oldValueIsPrimitive ? (a === b) : false;\r
+ }\r
+};\r
+\r
+ko.isObservable = function (instance) {\r
+ if ((instance === null) || (instance === undefined) || (instance.__ko_proto__ === undefined)) return false;\r
+ if (instance.__ko_proto__ === ko.observable) return true;\r
+ return ko.isObservable(instance.__ko_proto__); // Walk the prototype chain\r
+}\r
+ko.isWriteableObservable = function (instance) {\r
+ // Observable\r
+ if ((typeof instance == "function") && instance.__ko_proto__ === ko.observable)\r
+ return true;\r
+ // Writeable dependent observable\r
+ if ((typeof instance == "function") && (instance.__ko_proto__ === ko.dependentObservable) && (instance.hasWriteFunction))\r
+ return true;\r
+ // Anything else\r
+ return false;\r
+}\r
+\r
+\r
+ko.exportSymbol('ko.observable', ko.observable);\r
+ko.exportSymbol('ko.isObservable', ko.isObservable);\r
+ko.exportSymbol('ko.isWriteableObservable', ko.isWriteableObservable);\r
+ko.observableArray = function (initialValues) {\r
+ if (arguments.length == 0) {\r
+ // Zero-parameter constructor initializes to empty array\r
+ initialValues = [];\r
+ }\r
+ if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))\r
+ throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");\r
+ \r
+ var result = new ko.observable(initialValues);\r
+ ko.utils.extend(result, ko.observableArray['fn']);\r
+ \r
+ ko.exportProperty(result, "remove", result.remove);\r
+ ko.exportProperty(result, "removeAll", result.removeAll);\r
+ ko.exportProperty(result, "destroy", result.destroy);\r
+ ko.exportProperty(result, "destroyAll", result.destroyAll);\r
+ ko.exportProperty(result, "indexOf", result.indexOf);\r
+ ko.exportProperty(result, "replace", result.replace);\r
+ \r
+ return result;\r
+}\r
+\r
+ko.observableArray['fn'] = {\r
+ remove: function (valueOrPredicate) {\r
+ var underlyingArray = this();\r
+ var removedValues = [];\r
+ var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };\r
+ for (var i = 0; i < underlyingArray.length; i++) {\r
+ var value = underlyingArray[i];\r
+ if (predicate(value)) {\r
+ if (removedValues.length === 0) {\r
+ this.valueWillMutate();\r
+ }\r
+ removedValues.push(value);\r
+ underlyingArray.splice(i, 1);\r
+ i--;\r
+ }\r
+ }\r
+ if (removedValues.length) {\r
+ this.valueHasMutated();\r
+ }\r
+ return removedValues;\r
+ },\r
+\r
+ removeAll: function (arrayOfValues) {\r
+ // If you passed zero args, we remove everything\r
+ if (arrayOfValues === undefined) {\r
+ var underlyingArray = this();\r
+ var allValues = underlyingArray.slice(0);\r
+ this.valueWillMutate();\r
+ underlyingArray.splice(0, underlyingArray.length);\r
+ this.valueHasMutated();\r
+ return allValues;\r
+ }\r
+ // If you passed an arg, we interpret it as an array of entries to remove\r
+ if (!arrayOfValues)\r
+ return [];\r
+ return this.remove(function (value) {\r
+ return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;\r
+ });\r
+ },\r
+ \r
+ destroy: function (valueOrPredicate) {\r
+ var underlyingArray = this();\r
+ var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };\r
+ this.valueWillMutate();\r
+ for (var i = underlyingArray.length - 1; i >= 0; i--) {\r
+ var value = underlyingArray[i];\r
+ if (predicate(value))\r
+ underlyingArray[i]["_destroy"] = true;\r
+ }\r
+ this.valueHasMutated();\r
+ },\r
+ \r
+ destroyAll: function (arrayOfValues) {\r
+ // If you passed zero args, we destroy everything\r
+ if (arrayOfValues === undefined)\r
+ return this.destroy(function() { return true });\r
+ \r
+ // If you passed an arg, we interpret it as an array of entries to destroy\r
+ if (!arrayOfValues)\r
+ return [];\r
+ return this.destroy(function (value) {\r
+ return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;\r
+ }); \r
+ },\r
+\r
+ indexOf: function (item) {\r
+ var underlyingArray = this();\r
+ return ko.utils.arrayIndexOf(underlyingArray, item);\r
+ },\r
+ \r
+ replace: function(oldItem, newItem) {\r
+ var index = this.indexOf(oldItem);\r
+ if (index >= 0) {\r
+ this.valueWillMutate();\r
+ this()[index] = newItem;\r
+ this.valueHasMutated();\r
+ }\r
+ } \r
+}\r
+\r
+// Populate ko.observableArray.fn with read/write functions from native arrays\r
+ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {\r
+ ko.observableArray['fn'][methodName] = function () { \r
+ var underlyingArray = this();\r
+ this.valueWillMutate();\r
+ var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);\r
+ this.valueHasMutated();\r
+ return methodCallResult;\r
+ };\r
+});\r
+\r
+// Populate ko.observableArray.fn with read-only functions from native arrays\r
+ko.utils.arrayForEach(["slice"], function (methodName) {\r
+ ko.observableArray['fn'][methodName] = function () {\r
+ var underlyingArray = this();\r
+ return underlyingArray[methodName].apply(underlyingArray, arguments);\r
+ };\r
+});\r
+\r
+ko.exportSymbol('ko.observableArray', ko.observableArray);\r
+function prepareOptions(evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {\r
+ if (evaluatorFunctionOrOptions && typeof evaluatorFunctionOrOptions == "object") {\r
+ // Single-parameter syntax - everything is on this "options" param\r
+ options = evaluatorFunctionOrOptions;\r
+ } else {\r
+ // Multi-parameter syntax - construct the options according to the params passed\r
+ options = options || {};\r
+ options["read"] = evaluatorFunctionOrOptions || options["read"];\r
+ }\r
+ // By here, "options" is always non-null\r
+ \r
+ if (typeof options["read"] != "function")\r
+ throw "Pass a function that returns the value of the dependentObservable";\r
+ \r
+ return options; \r
+}\r
+\r
+ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {\r
+ var _latestValue, \r
+ _hasBeenEvaluated = false, \r
+ options = prepareOptions(evaluatorFunctionOrOptions, evaluatorFunctionTarget, options);\r
+\r
+ // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values\r
+ // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),\r
+ // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)\r
+ var disposeWhenNodeIsRemoved = (typeof options["disposeWhenNodeIsRemoved"] == "object") ? options["disposeWhenNodeIsRemoved"] : null;\r
+ var disposeWhenNodeIsRemovedCallback = null;\r
+ if (disposeWhenNodeIsRemoved) {\r
+ disposeWhenNodeIsRemovedCallback = function() { dependentObservable.dispose() };\r
+ ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, disposeWhenNodeIsRemovedCallback);\r
+ var existingDisposeWhenFunction = options["disposeWhen"];\r
+ options["disposeWhen"] = function () {\r
+ return (!ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved)) \r
+ || ((typeof existingDisposeWhenFunction == "function") && existingDisposeWhenFunction());\r
+ } \r
+ }\r
+ \r
+ var _subscriptionsToDependencies = [];\r
+ function disposeAllSubscriptionsToDependencies() {\r
+ ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {\r
+ subscription.dispose();\r
+ });\r
+ _subscriptionsToDependencies = [];\r
+ }\r
+ \r
+ var evaluationTimeoutInstance = null;\r
+ function evaluatePossiblyAsync() {\r
+ var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];\r
+ if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {\r
+ clearTimeout(evaluationTimeoutInstance);\r
+ evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);\r
+ } else\r
+ evaluateImmediate();\r
+ }\r
+\r
+ function evaluateImmediate() {\r
+ // Don't dispose on first evaluation, because the "disposeWhen" callback might\r
+ // e.g., dispose when the associated DOM element isn't in the doc, and it's not\r
+ // going to be in the doc until *after* the first evaluation\r
+ if ((_hasBeenEvaluated) && typeof options["disposeWhen"] == "function") {\r
+ if (options["disposeWhen"]()) {\r
+ dependentObservable.dispose();\r
+ return;\r
+ }\r
+ }\r
+\r
+ try {\r
+ disposeAllSubscriptionsToDependencies();\r
+ ko.dependencyDetection.begin(function(subscribable) {\r
+ _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync));\r
+ });\r
+ var valueForThis = options["owner"] || evaluatorFunctionTarget; // If undefined, it will default to "window" by convention. This might change in the future.\r
+ var newValue = options["read"].call(valueForThis);\r
+ dependentObservable["notifySubscribers"](_latestValue, "beforeChange");\r
+ _latestValue = newValue;\r
+ } finally {\r
+ ko.dependencyDetection.end();\r
+ }\r
+\r
+ dependentObservable["notifySubscribers"](_latestValue);\r
+ _hasBeenEvaluated = true;\r
+ }\r
+\r
+ function dependentObservable() {\r
+ if (arguments.length > 0) {\r
+ if (typeof options["write"] === "function") {\r
+ // Writing a value\r
+ var valueForThis = options["owner"] || evaluatorFunctionTarget; // If undefined, it will default to "window" by convention. This might change in the future.\r
+ options["write"].apply(valueForThis, arguments);\r
+ } else {\r
+ throw "Cannot write a value to a dependentObservable unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.";\r
+ }\r
+ } else {\r
+ // Reading the value\r
+ if (!_hasBeenEvaluated)\r
+ evaluateImmediate();\r
+ ko.dependencyDetection.registerDependency(dependentObservable);\r
+ return _latestValue;\r
+ }\r
+ }\r
+ dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; }\r
+ dependentObservable.hasWriteFunction = typeof options["write"] === "function";\r
+ dependentObservable.dispose = function () {\r
+ if (disposeWhenNodeIsRemoved)\r
+ ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, disposeWhenNodeIsRemovedCallback);\r
+ disposeAllSubscriptionsToDependencies();\r
+ };\r
+ \r
+ ko.subscribable.call(dependentObservable);\r
+ ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);\r
+\r
+ if (options['deferEvaluation'] !== true)\r
+ evaluateImmediate();\r
+ \r
+ ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);\r
+ ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);\r
+ \r
+ return dependentObservable;\r
+};\r
+\r
+ko.dependentObservable['fn'] = {\r
+ __ko_proto__: ko.dependentObservable\r
+};\r
+\r
+ko.dependentObservable.__ko_proto__ = ko.observable;\r
+\r
+ko.exportSymbol('ko.dependentObservable', ko.dependentObservable);\r
+ko.exportSymbol('ko.computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"\r
+(function() { \r
+ var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)\r
+ \r
+ ko.toJS = function(rootObject) {\r
+ if (arguments.length == 0)\r
+ throw new Error("When calling ko.toJS, pass the object you want to convert.");\r
+ \r
+ // We just unwrap everything at every level in the object graph\r
+ return mapJsObjectGraph(rootObject, function(valueToMap) {\r
+ // Loop because an observable's value might in turn be another observable wrapper\r
+ for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)\r
+ valueToMap = valueToMap();\r
+ return valueToMap;\r
+ });\r
+ };\r
+\r
+ ko.toJSON = function(rootObject) {\r
+ var plainJavaScriptObject = ko.toJS(rootObject);\r
+ return ko.utils.stringifyJson(plainJavaScriptObject);\r
+ };\r
+ \r
+ function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {\r
+ visitedObjects = visitedObjects || new objectLookup();\r
+ \r
+ rootObject = mapInputCallback(rootObject);\r
+ var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));\r
+ if (!canHaveProperties)\r
+ return rootObject;\r
+ \r
+ var outputProperties = rootObject instanceof Array ? [] : {};\r
+ visitedObjects.save(rootObject, outputProperties); \r
+ \r
+ visitPropertiesOrArrayEntries(rootObject, function(indexer) {\r
+ var propertyValue = mapInputCallback(rootObject[indexer]);\r
+ \r
+ switch (typeof propertyValue) {\r
+ case "boolean":\r
+ case "number":\r
+ case "string":\r
+ case "function":\r
+ outputProperties[indexer] = propertyValue;\r
+ break;\r
+ case "object":\r
+ case "undefined": \r
+ var previouslyMappedValue = visitedObjects.get(propertyValue);\r
+ outputProperties[indexer] = (previouslyMappedValue !== undefined)\r
+ ? previouslyMappedValue\r
+ : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);\r
+ break; \r
+ }\r
+ });\r
+ \r
+ return outputProperties;\r
+ }\r
+ \r
+ function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {\r
+ if (rootObject instanceof Array) {\r
+ for (var i = 0; i < rootObject.length; i++)\r
+ visitorCallback(i);\r
+ } else {\r
+ for (var propertyName in rootObject)\r
+ visitorCallback(propertyName);\r
+ }\r
+ }; \r
+ \r
+ function objectLookup() {\r
+ var keys = [];\r
+ var values = [];\r
+ this.save = function(key, value) {\r
+ var existingIndex = ko.utils.arrayIndexOf(keys, key);\r
+ if (existingIndex >= 0)\r
+ values[existingIndex] = value;\r
+ else {\r
+ keys.push(key);\r
+ values.push(value); \r
+ } \r
+ };\r
+ this.get = function(key) {\r
+ var existingIndex = ko.utils.arrayIndexOf(keys, key);\r
+ return (existingIndex >= 0) ? values[existingIndex] : undefined;\r
+ };\r
+ };\r
+})();\r
+\r
+ko.exportSymbol('ko.toJS', ko.toJS);\r
+ko.exportSymbol('ko.toJSON', ko.toJSON);(function () {\r
+ var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';\r
+\r
+ // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values\r
+ // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values\r
+ // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.\r
+ ko.selectExtensions = {\r
+ readValue : function(element) {\r
+ if (element.tagName == 'OPTION') {\r
+ if (element[hasDomDataExpandoProperty] === true)\r
+ return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);\r
+ return element.getAttribute("value");\r
+ } else if (element.tagName == 'SELECT')\r
+ return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;\r
+ else\r
+ return element.value;\r
+ },\r
+ \r
+ writeValue: function(element, value) {\r
+ if (element.tagName == 'OPTION') {\r
+ switch(typeof value) {\r
+ case "string":\r
+ ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);\r
+ if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node\r
+ delete element[hasDomDataExpandoProperty];\r
+ }\r
+ element.value = value; \r
+ break;\r
+ default:\r
+ // Store arbitrary object using DomData\r
+ ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);\r
+ element[hasDomDataExpandoProperty] = true;\r
+\r
+ // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.\r
+ element.value = typeof value === "number" ? value : "";\r
+ break;\r
+ } \r
+ } else if (element.tagName == 'SELECT') {\r
+ for (var i = element.options.length - 1; i >= 0; i--) {\r
+ if (ko.selectExtensions.readValue(element.options[i]) == value) {\r
+ element.selectedIndex = i;\r
+ break;\r
+ }\r
+ }\r
+ } else {\r
+ if ((value === null) || (value === undefined))\r
+ value = "";\r
+ element.value = value;\r
+ }\r
+ }\r
+ }; \r
+})();\r
+\r
+ko.exportSymbol('ko.selectExtensions', ko.selectExtensions);\r
+ko.exportSymbol('ko.selectExtensions.readValue', ko.selectExtensions.readValue);\r
+ko.exportSymbol('ko.selectExtensions.writeValue', ko.selectExtensions.writeValue);\r
+\r
+ko.jsonExpressionRewriting = (function () {\r
+ var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;\r
+ var javaScriptAssignmentTarget = /^[\_$a-z][\_$a-z0-9]*(\[.*?\])*(\.[\_$a-z][\_$a-z0-9]*(\[.*?\])*)*$/i;\r
+ var javaScriptReservedWords = ["true", "false"];\r
+\r
+ function restoreTokens(string, tokens) {\r
+ var prevValue = null;\r
+ while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)\r
+ prevValue = string;\r
+ string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {\r
+ return tokens[tokenIndex];\r
+ });\r
+ }\r
+ return string;\r
+ }\r
+\r
+ function isWriteableValue(expression) {\r
+ if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)\r
+ return false;\r
+ return expression.match(javaScriptAssignmentTarget) !== null;\r
+ }\r
+\r
+ function ensureQuoted(key) {\r
+ var trimmedKey = ko.utils.stringTrim(key);\r
+ switch (trimmedKey.length && trimmedKey.charAt(0)) {\r
+ case "'":\r
+ case '"': \r
+ return key;\r
+ default:\r
+ return "'" + trimmedKey + "'";\r
+ }\r
+ }\r
+\r
+ return {\r
+ bindingRewriteValidators: [],\r
+ \r
+ parseObjectLiteral: function(objectLiteralString) {\r
+ // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser\r
+ // that is sufficient just to split an object literal string into a set of top-level key-value pairs\r
+\r
+ var str = ko.utils.stringTrim(objectLiteralString);\r
+ if (str.length < 3)\r
+ return [];\r
+ if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal\r
+ str = str.substring(1, str.length - 1);\r
+\r
+ // Pull out any string literals and regex literals\r
+ var tokens = [];\r
+ var tokenStart = null, tokenEndChar;\r
+ for (var position = 0; position < str.length; position++) {\r
+ var c = str.charAt(position);\r
+ if (tokenStart === null) {\r
+ switch (c) {\r
+ case '"':\r
+ case "'":\r
+ case "/":\r
+ tokenStart = position;\r
+ tokenEndChar = c;\r
+ break;\r
+ }\r
+ } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {\r
+ var token = str.substring(tokenStart, position + 1);\r
+ tokens.push(token);\r
+ var replacement = "@ko_token_" + (tokens.length - 1) + "@";\r
+ str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);\r
+ position -= (token.length - replacement.length);\r
+ tokenStart = null;\r
+ }\r
+ }\r
+\r
+ // Next pull out balanced paren, brace, and bracket blocks\r
+ tokenStart = null;\r
+ tokenEndChar = null;\r
+ var tokenDepth = 0, tokenStartChar = null;\r
+ for (var position = 0; position < str.length; position++) {\r
+ var c = str.charAt(position);\r
+ if (tokenStart === null) {\r
+ switch (c) {\r
+ case "{": tokenStart = position; tokenStartChar = c;\r
+ tokenEndChar = "}";\r
+ break;\r
+ case "(": tokenStart = position; tokenStartChar = c;\r
+ tokenEndChar = ")";\r
+ break;\r
+ case "[": tokenStart = position; tokenStartChar = c;\r
+ tokenEndChar = "]";\r
+ break;\r
+ }\r
+ }\r
+\r
+ if (c === tokenStartChar)\r
+ tokenDepth++;\r
+ else if (c === tokenEndChar) {\r
+ tokenDepth--;\r
+ if (tokenDepth === 0) {\r
+ var token = str.substring(tokenStart, position + 1);\r
+ tokens.push(token);\r
+ var replacement = "@ko_token_" + (tokens.length - 1) + "@";\r
+ str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);\r
+ position -= (token.length - replacement.length);\r
+ tokenStart = null; \r
+ }\r
+ }\r
+ }\r
+\r
+ // Now we can safely split on commas to get the key/value pairs\r
+ var result = [];\r
+ var keyValuePairs = str.split(",");\r
+ for (var i = 0, j = keyValuePairs.length; i < j; i++) {\r
+ var pair = keyValuePairs[i];\r
+ var colonPos = pair.indexOf(":");\r
+ if ((colonPos > 0) && (colonPos < pair.length - 1)) {\r
+ var key = pair.substring(0, colonPos);\r
+ var value = pair.substring(colonPos + 1);\r
+ result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });\r
+ } else {\r
+ result.push({ 'unknown': restoreTokens(pair, tokens) });\r
+ }\r
+ }\r
+ return result; \r
+ },\r
+\r
+ insertPropertyAccessorsIntoJson: function (objectLiteralStringOrKeyValueArray) {\r
+ var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string" \r
+ ? ko.jsonExpressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)\r
+ : objectLiteralStringOrKeyValueArray;\r
+ var resultStrings = [], propertyAccessorResultStrings = [];\r
+\r
+ var keyValueEntry;\r
+ for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {\r
+ if (resultStrings.length > 0)\r
+ resultStrings.push(",");\r
+\r
+ if (keyValueEntry['key']) {\r
+ var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];\r
+ resultStrings.push(quotedKey);\r
+ resultStrings.push(":"); \r
+ resultStrings.push(val);\r
+\r
+ if (isWriteableValue(ko.utils.stringTrim(val))) {\r
+ if (propertyAccessorResultStrings.length > 0)\r
+ propertyAccessorResultStrings.push(", ");\r
+ propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");\r
+ } \r
+ } else if (keyValueEntry['unknown']) {\r
+ resultStrings.push(keyValueEntry['unknown']);\r
+ }\r
+ }\r
+\r
+ var combinedResult = resultStrings.join("");\r
+ if (propertyAccessorResultStrings.length > 0) {\r
+ var allPropertyAccessors = propertyAccessorResultStrings.join("");\r
+ combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } "; \r
+ }\r
+\r
+ return combinedResult;\r
+ },\r
+\r
+ keyValueArrayContainsKey: function(keyValueArray, key) {\r
+ for (var i = 0; i < keyValueArray.length; i++)\r
+ if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)\r
+ return true; \r
+ return false;\r
+ }\r
+ };\r
+})();\r
+\r
+ko.exportSymbol('ko.jsonExpressionRewriting', ko.jsonExpressionRewriting);\r
+ko.exportSymbol('ko.jsonExpressionRewriting.bindingRewriteValidators', ko.jsonExpressionRewriting.bindingRewriteValidators);\r
+ko.exportSymbol('ko.jsonExpressionRewriting.parseObjectLiteral', ko.jsonExpressionRewriting.parseObjectLiteral);\r
+ko.exportSymbol('ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson);\r
+(function() {\r
+ // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes\r
+ // may be used to represent hierarchy (in addition to the DOM's natural hierarchy). \r
+ // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state \r
+ // of that virtual hierarchy\r
+ // \r
+ // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)\r
+ // without having to scatter special cases all over the binding and templating code.\r
+\r
+ // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)\r
+ // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.\r
+ // So, use node.text where available, and node.nodeValue elsewhere\r
+ var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";\r
+\r
+ var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko\s+(.*\:.*)\s*-->$/ : /^\s*ko\s+(.*\:.*)\s*$/;\r
+ var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;\r
+ var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };\r
+\r
+ function isStartComment(node) {\r
+ return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);\r
+ }\r
+\r
+ function isEndComment(node) {\r
+ return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);\r
+ }\r
+\r
+ function getVirtualChildren(startComment, allowUnbalanced) {\r
+ var currentNode = startComment;\r
+ var depth = 1;\r
+ var children = [];\r
+ while (currentNode = currentNode.nextSibling) {\r
+ if (isEndComment(currentNode)) {\r
+ depth--;\r
+ if (depth === 0)\r
+ return children;\r
+ }\r
+\r
+ children.push(currentNode);\r
+\r
+ if (isStartComment(currentNode))\r
+ depth++;\r
+ }\r
+ if (!allowUnbalanced)\r
+ throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);\r
+ return null;\r
+ }\r
+\r
+ function getMatchingEndComment(startComment, allowUnbalanced) {\r
+ var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);\r
+ if (allVirtualChildren) {\r
+ if (allVirtualChildren.length > 0)\r
+ return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;\r
+ return startComment.nextSibling;\r
+ } else\r
+ return null; // Must have no matching end comment, and allowUnbalanced is true\r
+ }\r
+\r
+ function nodeArrayToText(nodeArray, cleanNodes) {\r
+ var texts = [];\r
+ for (var i = 0, j = nodeArray.length; i < j; i++) {\r
+ if (cleanNodes)\r
+ ko.utils.domNodeDisposal.cleanNode(nodeArray[i]);\r
+ texts.push(ko.utils.outerHTML(nodeArray[i]));\r
+ }\r
+ return String.prototype.concat.apply("", texts);\r
+ } \r
+\r
+ function getUnbalancedChildTags(node) {\r
+ // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>\r
+ // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->\r
+ var childNode = node.firstChild, captureRemaining = null;\r
+ if (childNode) {\r
+ do {\r
+ if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes\r
+ captureRemaining.push(childNode);\r
+ else if (isStartComment(childNode)) {\r
+ var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);\r
+ if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set\r
+ childNode = matchingEndComment;\r
+ else\r
+ captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point\r
+ } else if (isEndComment(childNode)) {\r
+ captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing\r
+ }\r
+ } while (childNode = childNode.nextSibling);\r
+ }\r
+ return captureRemaining;\r
+ }\r
+\r
+ ko.virtualElements = {\r
+ allowedBindings: {},\r
+\r
+ childNodes: function(node) {\r
+ return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;\r
+ },\r
+\r
+ emptyNode: function(node) {\r
+ if (!isStartComment(node))\r
+ ko.utils.emptyDomNode(node);\r
+ else {\r
+ var virtualChildren = ko.virtualElements.childNodes(node);\r
+ for (var i = 0, j = virtualChildren.length; i < j; i++)\r
+ ko.removeNode(virtualChildren[i]);\r
+ }\r
+ },\r
+\r
+ setDomNodeChildren: function(node, childNodes) {\r
+ if (!isStartComment(node))\r
+ ko.utils.setDomNodeChildren(node, childNodes);\r
+ else {\r
+ ko.virtualElements.emptyNode(node);\r
+ var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children\r
+ for (var i = 0, j = childNodes.length; i < j; i++)\r
+ endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);\r
+ }\r
+ },\r
+\r
+ prepend: function(containerNode, nodeToPrepend) {\r
+ if (!isStartComment(containerNode)) {\r
+ if (containerNode.firstChild)\r
+ containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);\r
+ else\r
+ containerNode.appendChild(nodeToPrepend); \r
+ } else {\r
+ // Start comments must always have a parent and at least one following sibling (the end comment)\r
+ containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);\r
+ }\r
+ },\r
+\r
+ insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {\r
+ if (!isStartComment(containerNode)) {\r
+ // Insert after insertion point\r
+ if (insertAfterNode.nextSibling)\r
+ containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);\r
+ else\r
+ containerNode.appendChild(nodeToInsert); \r
+ } else {\r
+ // Children of start comments must always have a parent and at least one following sibling (the end comment)\r
+ containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);\r
+ } \r
+ },\r
+\r
+ nextSibling: function(node) {\r
+ if (!isStartComment(node)) {\r
+ if (node.nextSibling && isEndComment(node.nextSibling))\r
+ return undefined;\r
+ return node.nextSibling;\r
+ } else {\r
+ return getMatchingEndComment(node).nextSibling;\r
+ }\r
+ },\r
+\r
+ virtualNodeBindingValue: function(node) {\r
+ var regexMatch = isStartComment(node);\r
+ return regexMatch ? regexMatch[1] : null; \r
+ },\r
+\r
+ extractAnonymousTemplateIfVirtualElement: function(node) {\r
+ if (ko.virtualElements.virtualNodeBindingValue(node)) {\r
+ // Empty out the virtual children, and associate "node" with an anonymous template matching its previous virtual children\r
+ var virtualChildren = ko.virtualElements.childNodes(node);\r
+ var anonymousTemplateText = nodeArrayToText(virtualChildren, true);\r
+ ko.virtualElements.emptyNode(node);\r
+ new ko.templateSources.anonymousTemplate(node).text(anonymousTemplateText);\r
+ }\r
+ },\r
+ \r
+ normaliseVirtualElementDomStructure: function(elementVerified) {\r
+ // Workaround for https://github.com/SteveSanderson/knockout/issues/155 \r
+ // (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\r
+ // that are direct descendants of <ul> into the preceding <li>)\r
+ if (!htmlTagsWithOptionallyClosingChildren[elementVerified.tagName.toLowerCase()])\r
+ return;\r
+ \r
+ // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags\r
+ // must be intended to appear *after* that child, so move them there.\r
+ var childNode = elementVerified.firstChild;\r
+ if (childNode) {\r
+ do {\r
+ if (childNode.nodeType === 1) {\r
+ var unbalancedTags = getUnbalancedChildTags(childNode);\r
+ if (unbalancedTags) {\r
+ // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child\r
+ var nodeToInsertBefore = childNode.nextSibling;\r
+ for (var i = 0; i < unbalancedTags.length; i++) {\r
+ if (nodeToInsertBefore)\r
+ elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);\r
+ else\r
+ elementVerified.appendChild(unbalancedTags[i]);\r
+ }\r
+ }\r
+ }\r
+ } while (childNode = childNode.nextSibling);\r
+ }\r
+ } \r
+ }; \r
+})();\r
+(function() {\r
+ var defaultBindingAttributeName = "data-bind";\r
+\r
+ ko.bindingProvider = function() { };\r
+\r
+ ko.utils.extend(ko.bindingProvider.prototype, {\r
+ 'nodeHasBindings': function(node) {\r
+ switch (node.nodeType) {\r
+ case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element\r
+ case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node\r
+ default: return false;\r
+ }\r
+ },\r
+\r
+ 'getBindings': function(node, bindingContext) {\r
+ var bindingsString = this['getBindingsString'](node, bindingContext);\r
+ return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext) : null;\r
+ },\r
+\r
+ // The following function is only used internally by this default provider.\r
+ // It's not part of the interface definition for a general binding provider.\r
+ 'getBindingsString': function(node, bindingContext) {\r
+ switch (node.nodeType) {\r
+ case 1: return node.getAttribute(defaultBindingAttributeName); // Element\r
+ case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node\r
+ default: return null;\r
+ }\r
+ },\r
+\r
+ // The following function is only used internally by this default provider.\r
+ // It's not part of the interface definition for a general binding provider.\r
+ 'parseBindingsString': function(bindingsString, bindingContext) {\r
+ try {\r
+ var viewModel = bindingContext['$data'];\r
+ var rewrittenBindings = " { " + ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson(bindingsString) + " } ";\r
+ return ko.utils.evalWithinScope(rewrittenBindings, viewModel === null ? window : viewModel, bindingContext);\r
+ } catch (ex) {\r
+ throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);\r
+ } \r
+ }\r
+ });\r
+\r
+ ko.bindingProvider['instance'] = new ko.bindingProvider();\r
+})();\r
+\r
+ko.exportSymbol('ko.bindingProvider', ko.bindingProvider);(function () {\r
+ ko.bindingHandlers = {};\r
+\r
+ ko.bindingContext = function(dataItem, parentBindingContext) {\r
+ this['$data'] = dataItem;\r
+ if (parentBindingContext) {\r
+ this['$parent'] = parentBindingContext['$data'];\r
+ this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);\r
+ this['$parents'].unshift(this['$parent']);\r
+ this['$root'] = parentBindingContext['$root'];\r
+ } else {\r
+ this['$parents'] = [];\r
+ this['$root'] = dataItem; \r
+ }\r
+ }\r
+ ko.bindingContext.prototype['createChildContext'] = function (dataItem) {\r
+ return new ko.bindingContext(dataItem, this);\r
+ };\r
+\r
+ function validateThatBindingIsAllowedForVirtualElements(bindingName) {\r
+ var validator = ko.virtualElements.allowedBindings[bindingName];\r
+ if (!validator)\r
+ throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")\r
+ }\r
+\r
+ function applyBindingsToDescendantsInternal (viewModel, elementVerified) {\r
+ var currentChild, nextInQueue = elementVerified.childNodes[0];\r
+ while (currentChild = nextInQueue) {\r
+ // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position\r
+ nextInQueue = ko.virtualElements.nextSibling(currentChild);\r
+ applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, false);\r
+ } \r
+ }\r
+ \r
+ function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, isRootNodeForBindingContext) {\r
+ var shouldBindDescendants = true;\r
+\r
+ // Perf optimisation: Apply bindings only if...\r
+ // (1) It's a root element for this binding context, as we will need to store the binding context on this node\r
+ // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those\r
+ // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)\r
+ var isElement = (nodeVerified.nodeType == 1);\r
+ if (isElement) // Workaround IE <= 8 HTML parsing weirdness\r
+ ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);\r
+\r
+ var shouldApplyBindings = (isElement && isRootNodeForBindingContext) // Case (1)\r
+ || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)\r
+ if (shouldApplyBindings)\r
+ shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, isRootNodeForBindingContext).shouldBindDescendants;\r
+ \r
+ if (isElement && shouldBindDescendants)\r
+ applyBindingsToDescendantsInternal(viewModel, nodeVerified);\r
+ } \r
+\r
+ function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, isRootNodeForBindingContext) {\r
+ // Need to be sure that inits are only run once, and updates never run until all the inits have been run\r
+ var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits\r
+\r
+ // Pre-process any anonymous template bounded by comment nodes\r
+ ko.virtualElements.extractAnonymousTemplateIfVirtualElement(node);\r
+\r
+ // Each time the dependentObservable is evaluated (after data changes),\r
+ // the binding attribute is reparsed so that it can pick out the correct\r
+ // model properties in the context of the changed data.\r
+ // DOM event callbacks need to be able to access this changed data,\r
+ // so we need a single parsedBindings variable (shared by all callbacks\r
+ // associated with this node's bindings) that all the closures can access.\r
+ var parsedBindings;\r
+ function makeValueAccessor(bindingKey) {\r
+ return function () { return parsedBindings[bindingKey] }\r
+ }\r
+ function parsedBindingsAccessor() {\r
+ return parsedBindings;\r
+ }\r
+ \r
+ var bindingHandlerThatControlsDescendantBindings;\r
+ new ko.dependentObservable(\r
+ function () {\r
+ // Ensure we have a nonnull binding context to work with\r
+ var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)\r
+ ? viewModelOrBindingContext\r
+ : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));\r
+ var viewModel = bindingContextInstance['$data'];\r
+\r
+ // We only need to store the bindingContext at the root of the subtree where it applies\r
+ // as all descendants will be able to find it by scanning up their ancestry\r
+ if (isRootNodeForBindingContext)\r
+ ko.storedBindingContextForNode(node, bindingContextInstance);\r
+\r
+ // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings\r
+ var evaluatedBindings = (typeof bindings == "function") ? bindings() : bindings;\r
+ parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);\r
+\r
+ if (parsedBindings) {\r
+ // First run all the inits, so bindings can register for notification on changes\r
+ if (initPhase === 0) {\r
+ initPhase = 1;\r
+ for (var bindingKey in parsedBindings) {\r
+ var binding = ko.bindingHandlers[bindingKey];\r
+ if (binding && node.nodeType === 8)\r
+ validateThatBindingIsAllowedForVirtualElements(bindingKey);\r
+\r
+ if (binding && typeof binding["init"] == "function") {\r
+ var handlerInitFn = binding["init"];\r
+ var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);\r
+ \r
+ // If this binding handler claims to control descendant bindings, make a note of this\r
+ if (initResult && initResult['controlsDescendantBindings']) {\r
+ if (bindingHandlerThatControlsDescendantBindings !== undefined)\r
+ 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.");\r
+ bindingHandlerThatControlsDescendantBindings = bindingKey;\r
+ }\r
+ }\r
+ }\r
+ initPhase = 2;\r
+ }\r
+ \r
+ // ... then run all the updates, which might trigger changes even on the first evaluation\r
+ if (initPhase === 2) {\r
+ for (var bindingKey in parsedBindings) {\r
+ var binding = ko.bindingHandlers[bindingKey];\r
+ if (binding && typeof binding["update"] == "function") {\r
+ var handlerUpdateFn = binding["update"];\r
+ handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);\r
+ }\r
+ }\r
+ }\r
+ }\r
+ },\r
+ null,\r
+ { 'disposeWhenNodeIsRemoved' : node }\r
+ );\r
+ \r
+ return { \r
+ shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined\r
+ };\r
+ };\r
+\r
+ var storedBindingContextDomDataKey = "__ko_bindingContext__";\r
+ ko.storedBindingContextForNode = function (node, bindingContext) {\r
+ if (arguments.length == 2)\r
+ ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);\r
+ else\r
+ return ko.utils.domData.get(node, storedBindingContextDomDataKey);\r
+ }\r
+\r
+ ko.applyBindingsToNode = function (node, bindings, viewModel) {\r
+ if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness\r
+ ko.virtualElements.normaliseVirtualElementDomStructure(node); \r
+ return applyBindingsToNodeInternal(node, bindings, viewModel, true);\r
+ };\r
+\r
+ ko.applyBindingsToDescendants = function(viewModel, rootNode) {\r
+ if (rootNode.nodeType === 1)\r
+ applyBindingsToDescendantsInternal(viewModel, rootNode);\r
+ };\r
+\r
+ ko.applyBindings = function (viewModel, rootNode) {\r
+ if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))\r
+ throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");\r
+ rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional\r
+\r
+ applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);\r
+ };\r
+\r
+ // Retrieving binding context from arbitrary nodes\r
+ ko.contextFor = function(node) {\r
+ // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)\r
+ switch (node.nodeType) {\r
+ case 1:\r
+ case 8:\r
+ var context = ko.storedBindingContextForNode(node);\r
+ if (context) return context;\r
+ if (node.parentNode) return ko.contextFor(node.parentNode);\r
+ break;\r
+ }\r
+ return undefined;\r
+ };\r
+ ko.dataFor = function(node) {\r
+ var context = ko.contextFor(node);\r
+ return context ? context['$data'] : undefined;\r
+ }; \r
+ \r
+ ko.exportSymbol('ko.bindingHandlers', ko.bindingHandlers);\r
+ ko.exportSymbol('ko.applyBindings', ko.applyBindings);\r
+ ko.exportSymbol('ko.applyBindingsToDescendants', ko.applyBindingsToDescendants);\r
+ ko.exportSymbol('ko.applyBindingsToNode', ko.applyBindingsToNode);\r
+ ko.exportSymbol('ko.contextFor', ko.contextFor);\r
+ ko.exportSymbol('ko.dataFor', ko.dataFor);\r
+})();// For certain common events (currently just 'click'), allow a simplified data-binding syntax\r
+// e.g. click:handler instead of the usual full-length event:{click:handler}\r
+var eventHandlersWithShortcuts = ['click'];\r
+ko.utils.arrayForEach(eventHandlersWithShortcuts, function(eventName) {\r
+ ko.bindingHandlers[eventName] = {\r
+ 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {\r
+ var newValueAccessor = function () {\r
+ var result = {};\r
+ result[eventName] = valueAccessor();\r
+ return result;\r
+ };\r
+ return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);\r
+ }\r
+ } \r
+});\r
+\r
+\r
+ko.bindingHandlers['event'] = {\r
+ 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {\r
+ var eventsToHandle = valueAccessor() || {};\r
+ for(var eventNameOutsideClosure in eventsToHandle) {\r
+ (function() {\r
+ var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure\r
+ if (typeof eventName == "string") {\r
+ ko.utils.registerEventHandler(element, eventName, function (event) {\r
+ var handlerReturnValue;\r
+ var handlerFunction = valueAccessor()[eventName];\r
+ if (!handlerFunction)\r
+ return;\r
+ var allBindings = allBindingsAccessor();\r
+ \r
+ try { \r
+ // Take all the event args, and prefix with the viewmodel\r
+ var argsForHandler = ko.utils.makeArray(arguments);\r
+ argsForHandler.unshift(viewModel);\r
+ handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);\r
+ } finally {\r
+ if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.\r
+ if (event.preventDefault)\r
+ event.preventDefault();\r
+ else\r
+ event.returnValue = false;\r
+ }\r
+ }\r
+ \r
+ var bubble = allBindings[eventName + 'Bubble'] !== false;\r
+ if (!bubble) {\r
+ event.cancelBubble = true;\r
+ if (event.stopPropagation)\r
+ event.stopPropagation();\r
+ }\r
+ });\r
+ }\r
+ })();\r
+ }\r
+ }\r
+};\r
+\r
+ko.bindingHandlers['submit'] = {\r
+ 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {\r
+ if (typeof valueAccessor() != "function")\r
+ throw new Error("The value for a submit binding must be a function");\r
+ ko.utils.registerEventHandler(element, "submit", function (event) {\r
+ var handlerReturnValue;\r
+ var value = valueAccessor();\r
+ try { handlerReturnValue = value.call(viewModel, element); }\r
+ finally {\r
+ if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.\r
+ if (event.preventDefault)\r
+ event.preventDefault();\r
+ else\r
+ event.returnValue = false;\r
+ }\r
+ }\r
+ });\r
+ }\r
+};\r
+\r
+ko.bindingHandlers['visible'] = {\r
+ 'update': function (element, valueAccessor) {\r
+ var value = ko.utils.unwrapObservable(valueAccessor());\r
+ var isCurrentlyVisible = !(element.style.display == "none");\r
+ if (value && !isCurrentlyVisible)\r
+ element.style.display = "";\r
+ else if ((!value) && isCurrentlyVisible)\r
+ element.style.display = "none";\r
+ }\r
+}\r
+\r
+ko.bindingHandlers['enable'] = {\r
+ 'update': function (element, valueAccessor) {\r
+ var value = ko.utils.unwrapObservable(valueAccessor());\r
+ if (value && element.disabled)\r
+ element.removeAttribute("disabled");\r
+ else if ((!value) && (!element.disabled))\r
+ element.disabled = true;\r
+ }\r
+};\r
+\r
+ko.bindingHandlers['disable'] = { \r
+ 'update': function (element, valueAccessor) { \r
+ ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) }); \r
+ } \r
+};\r
+\r
+function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {\r
+ if (preferModelValue) {\r
+ if (modelValue !== ko.selectExtensions.readValue(element))\r
+ ko.selectExtensions.writeValue(element, modelValue);\r
+ }\r
+\r
+ // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.\r
+ // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,\r
+ // change the model value to match the dropdown.\r
+ if (modelValue !== ko.selectExtensions.readValue(element))\r
+ ko.utils.triggerEvent(element, "change");\r
+};\r
+\r
+ko.bindingHandlers['value'] = {\r
+ 'init': function (element, valueAccessor, allBindingsAccessor) { \r
+ // Always catch "change" event; possibly other events too if asked\r
+ var eventsToCatch = ["change"];\r
+ var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];\r
+ if (requestedEventsToCatch) {\r
+ if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names\r
+ requestedEventsToCatch = [requestedEventsToCatch];\r
+ ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);\r
+ eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);\r
+ }\r
+ \r
+ ko.utils.arrayForEach(eventsToCatch, function(eventName) {\r
+ // The syntax "after<eventname>" means "run the handler asynchronously after the event"\r
+ // This is useful, for example, to catch "keydown" events after the browser has updated the control\r
+ // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)\r
+ var handleEventAsynchronously = false;\r
+ if (ko.utils.stringStartsWith(eventName, "after")) {\r
+ handleEventAsynchronously = true;\r
+ eventName = eventName.substring("after".length);\r
+ }\r
+ var runEventHandler = handleEventAsynchronously ? function(handler) { setTimeout(handler, 0) }\r
+ : function(handler) { handler() };\r
+ \r
+ ko.utils.registerEventHandler(element, eventName, function () {\r
+ runEventHandler(function() {\r
+ var modelValue = valueAccessor();\r
+ var elementValue = ko.selectExtensions.readValue(element);\r
+ if (ko.isWriteableObservable(modelValue))\r
+ modelValue(elementValue);\r
+ else {\r
+ var allBindings = allBindingsAccessor();\r
+ if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['value'])\r
+ allBindings['_ko_property_writers']['value'](elementValue); \r
+ }\r
+ });\r
+ }); \r
+ });\r
+ },\r
+ 'update': function (element, valueAccessor) {\r
+ var newValue = ko.utils.unwrapObservable(valueAccessor());\r
+ var elementValue = ko.selectExtensions.readValue(element);\r
+ var valueHasChanged = (newValue != elementValue);\r
+ \r
+ // 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). \r
+ // 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.\r
+ if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))\r
+ valueHasChanged = true;\r
+ \r
+ if (valueHasChanged) {\r
+ var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };\r
+ applyValueAction();\r
+\r
+ // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread\r
+ // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread\r
+ // to apply the value as well.\r
+ var alsoApplyAsynchronously = element.tagName == "SELECT";\r
+ if (alsoApplyAsynchronously)\r
+ setTimeout(applyValueAction, 0);\r
+ }\r
+ \r
+ // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,\r
+ // because you're not allowed to have a model value that disagrees with a visible UI selection.\r
+ if ((element.tagName == "SELECT") && (element.length > 0))\r
+ ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);\r
+ }\r
+};\r
+\r
+ko.bindingHandlers['options'] = {\r
+ 'update': function (element, valueAccessor, allBindingsAccessor) {\r
+ if (element.tagName != "SELECT")\r
+ throw new Error("options binding applies only to SELECT elements");\r
+\r
+ var selectWasPreviouslyEmpty = element.length == 0;\r
+ var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {\r
+ return node.tagName && node.tagName == "OPTION" && node.selected;\r
+ }), function (node) {\r
+ return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;\r
+ });\r
+ var previousScrollTop = element.scrollTop;\r
+ element.scrollTop = 0; // Workaround for a Chrome rendering bug. Note that we restore the scroll position later. (https://github.com/SteveSanderson/knockout/issues/215)\r
+\r
+ var value = ko.utils.unwrapObservable(valueAccessor());\r
+ var selectedValue = element.value;\r
+\r
+ // Remove all existing <option>s. \r
+ // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)\r
+ while (element.length > 0) {\r
+ ko.cleanNode(element.options[0]);\r
+ element.remove(0);\r
+ }\r
+\r
+ if (value) {\r
+ var allBindings = allBindingsAccessor();\r
+ if (typeof value.length != "number")\r
+ value = [value];\r
+ if (allBindings['optionsCaption']) {\r
+ var option = document.createElement("OPTION");\r
+ ko.utils.setHtml(option, allBindings['optionsCaption']);\r
+ ko.selectExtensions.writeValue(option, undefined);\r
+ element.appendChild(option);\r
+ }\r
+ for (var i = 0, j = value.length; i < j; i++) {\r
+ var option = document.createElement("OPTION");\r
+ \r
+ // Apply a value to the option element\r
+ var optionValue = typeof allBindings['optionsValue'] == "string" ? value[i][allBindings['optionsValue']] : value[i];\r
+ optionValue = ko.utils.unwrapObservable(optionValue);\r
+ ko.selectExtensions.writeValue(option, optionValue);\r
+ \r
+ // Apply some text to the option element\r
+ var optionsTextValue = allBindings['optionsText'];\r
+ var optionText;\r
+ if (typeof optionsTextValue == "function")\r
+ optionText = optionsTextValue(value[i]); // Given a function; run it against the data value\r
+ else if (typeof optionsTextValue == "string")\r
+ optionText = value[i][optionsTextValue]; // Given a string; treat it as a property name on the data value\r
+ else\r
+ optionText = optionValue; // Given no optionsText arg; use the data value itself\r
+ if ((optionText === null) || (optionText === undefined))\r
+ optionText = ""; \r
+\r
+ ko.utils.setTextContent(option, optionText);\r
+\r
+ element.appendChild(option);\r
+ }\r
+\r
+ // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.\r
+ // That's why we first added them without selection. Now it's time to set the selection.\r
+ var newOptions = element.getElementsByTagName("OPTION");\r
+ var countSelectionsRetained = 0;\r
+ for (var i = 0, j = newOptions.length; i < j; i++) {\r
+ if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {\r
+ ko.utils.setOptionNodeSelectionState(newOptions[i], true);\r
+ countSelectionsRetained++;\r
+ }\r
+ }\r
+ \r
+ if (previousScrollTop)\r
+ element.scrollTop = previousScrollTop;\r
+\r
+ if (selectWasPreviouslyEmpty && ('value' in allBindings)) {\r
+ // Ensure consistency between model value and selected option.\r
+ // If the dropdown is being populated for the first time here (or was otherwise previously empty),\r
+ // the dropdown selection state is meaningless, so we preserve the model value.\r
+ ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.unwrapObservable(allBindings['value']), /* preferModelValue */ true);\r
+ }\r
+ }\r
+ }\r
+};\r
+ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';\r
+\r
+ko.bindingHandlers['selectedOptions'] = {\r
+ getSelectedValuesFromSelectNode: function (selectNode) {\r
+ var result = [];\r
+ var nodes = selectNode.childNodes;\r
+ for (var i = 0, j = nodes.length; i < j; i++) {\r
+ var node = nodes[i];\r
+ if ((node.tagName == "OPTION") && node.selected)\r
+ result.push(ko.selectExtensions.readValue(node));\r
+ }\r
+ return result;\r
+ },\r
+ 'init': function (element, valueAccessor, allBindingsAccessor) {\r
+ ko.utils.registerEventHandler(element, "change", function () { \r
+ var value = valueAccessor();\r
+ if (ko.isWriteableObservable(value))\r
+ value(ko.bindingHandlers['selectedOptions'].getSelectedValuesFromSelectNode(this));\r
+ else {\r
+ var allBindings = allBindingsAccessor();\r
+ if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['value'])\r
+ allBindings['_ko_property_writers']['value'](ko.bindingHandlers['selectedOptions'].getSelectedValuesFromSelectNode(this));\r
+ }\r
+ }); \r
+ },\r
+ 'update': function (element, valueAccessor) {\r
+ if (element.tagName != "SELECT")\r
+ throw new Error("values binding applies only to SELECT elements");\r
+\r
+ var newValue = ko.utils.unwrapObservable(valueAccessor());\r
+ if (newValue && typeof newValue.length == "number") {\r
+ var nodes = element.childNodes;\r
+ for (var i = 0, j = nodes.length; i < j; i++) {\r
+ var node = nodes[i];\r
+ if (node.tagName == "OPTION")\r
+ ko.utils.setOptionNodeSelectionState(node, ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0);\r
+ }\r
+ }\r
+ }\r
+};\r
+\r
+ko.bindingHandlers['text'] = {\r
+ 'update': function (element, valueAccessor) {\r
+ ko.utils.setTextContent(element, valueAccessor());\r
+ }\r
+};\r
+\r
+ko.bindingHandlers['html'] = {\r
+ 'init': function() {\r
+ // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)\r
+ return { 'controlsDescendantBindings': true };\r
+ },\r
+ 'update': function (element, valueAccessor) {\r
+ var value = ko.utils.unwrapObservable(valueAccessor());\r
+ ko.utils.setHtml(element, value);\r
+ }\r
+};\r
+\r
+ko.bindingHandlers['css'] = {\r
+ 'update': function (element, valueAccessor) {\r
+ var value = ko.utils.unwrapObservable(valueAccessor() || {});\r
+ for (var className in value) {\r
+ if (typeof className == "string") {\r
+ var shouldHaveClass = ko.utils.unwrapObservable(value[className]);\r
+ ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);\r
+ }\r
+ }\r
+ }\r
+};\r
+\r
+ko.bindingHandlers['style'] = {\r
+ 'update': function (element, valueAccessor) {\r
+ var value = ko.utils.unwrapObservable(valueAccessor() || {});\r
+ for (var styleName in value) {\r
+ if (typeof styleName == "string") {\r
+ var styleValue = ko.utils.unwrapObservable(value[styleName]);\r
+ element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect\r
+ }\r
+ }\r
+ }\r
+};\r
+\r
+ko.bindingHandlers['uniqueName'] = {\r
+ 'init': function (element, valueAccessor) {\r
+ if (valueAccessor()) {\r
+ element.name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);\r
+\r
+ // Workaround IE 6/7 issue\r
+ // - https://github.com/SteveSanderson/knockout/issues/197\r
+ // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/\r
+ if (ko.utils.isIe6 || ko.utils.isIe7)\r
+ element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);\r
+ }\r
+ }\r
+};\r
+ko.bindingHandlers['uniqueName'].currentIndex = 0;\r
+\r
+ko.bindingHandlers['checked'] = {\r
+ 'init': function (element, valueAccessor, allBindingsAccessor) {\r
+ var updateHandler = function() { \r
+ var valueToWrite;\r
+ if (element.type == "checkbox") {\r
+ valueToWrite = element.checked;\r
+ } else if ((element.type == "radio") && (element.checked)) {\r
+ valueToWrite = element.value;\r
+ } else {\r
+ return; // "checked" binding only responds to checkboxes and selected radio buttons\r
+ }\r
+ \r
+ var modelValue = valueAccessor(); \r
+ if ((element.type == "checkbox") && (ko.utils.unwrapObservable(modelValue) instanceof Array)) {\r
+ // For checkboxes bound to an array, we add/remove the checkbox value to that array\r
+ // This works for both observable and non-observable arrays\r
+ var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.unwrapObservable(modelValue), element.value);\r
+ if (element.checked && (existingEntryIndex < 0))\r
+ modelValue.push(element.value);\r
+ else if ((!element.checked) && (existingEntryIndex >= 0))\r
+ modelValue.splice(existingEntryIndex, 1);\r
+ } else if (ko.isWriteableObservable(modelValue)) { \r
+ if (modelValue() !== valueToWrite) { // Suppress repeated events when there's nothing new to notify (some browsers raise them)\r
+ modelValue(valueToWrite);\r
+ }\r
+ } else {\r
+ var allBindings = allBindingsAccessor();\r
+ if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['checked']) {\r
+ allBindings['_ko_property_writers']['checked'](valueToWrite);\r
+ }\r
+ }\r
+ };\r
+ ko.utils.registerEventHandler(element, "click", updateHandler);\r
+\r
+ // IE 6 won't allow radio buttons to be selected unless they have a name\r
+ if ((element.type == "radio") && !element.name)\r
+ ko.bindingHandlers['uniqueName']['init'](element, function() { return true });\r
+ },\r
+ 'update': function (element, valueAccessor) {\r
+ var value = ko.utils.unwrapObservable(valueAccessor());\r
+ \r
+ if (element.type == "checkbox") { \r
+ if (value instanceof Array) {\r
+ // When bound to an array, the checkbox being checked represents its value being present in that array\r
+ element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;\r
+ } else {\r
+ // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish\r
+ element.checked = value; \r
+ } \r
+ } else if (element.type == "radio") {\r
+ element.checked = (element.value == value);\r
+ }\r
+ }\r
+};\r
+\r
+ko.bindingHandlers['attr'] = {\r
+ 'update': function(element, valueAccessor, allBindingsAccessor) {\r
+ var value = ko.utils.unwrapObservable(valueAccessor()) || {};\r
+ for (var attrName in value) {\r
+ if (typeof attrName == "string") {\r
+ var attrValue = ko.utils.unwrapObservable(value[attrName]);\r
+ \r
+ // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely \r
+ // when someProp is a "no value"-like value (strictly null, false, or undefined)\r
+ // (because the absence of the "checked" attr is how to mark an element as not checked, etc.) \r
+ if ((attrValue === false) || (attrValue === null) || (attrValue === undefined))\r
+ element.removeAttribute(attrName);\r
+ else \r
+ element.setAttribute(attrName, attrValue.toString());\r
+ }\r
+ }\r
+ }\r
+};\r
+\r
+ko.bindingHandlers['hasfocus'] = {\r
+ 'init': function(element, valueAccessor, allBindingsAccessor) {\r
+ var writeValue = function(valueToWrite) {\r
+ var modelValue = valueAccessor();\r
+ if (valueToWrite == ko.utils.unwrapObservable(modelValue))\r
+ return;\r
+\r
+ if (ko.isWriteableObservable(modelValue))\r
+ modelValue(valueToWrite);\r
+ else {\r
+ var allBindings = allBindingsAccessor();\r
+ if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['hasfocus']) {\r
+ allBindings['_ko_property_writers']['hasfocus'](valueToWrite);\r
+ } \r
+ }\r
+ };\r
+ ko.utils.registerEventHandler(element, "focus", function() { writeValue(true) });\r
+ ko.utils.registerEventHandler(element, "focusin", function() { writeValue(true) }); // For IE\r
+ ko.utils.registerEventHandler(element, "blur", function() { writeValue(false) });\r
+ ko.utils.registerEventHandler(element, "focusout", function() { writeValue(false) }); // For IE\r
+ },\r
+ 'update': function(element, valueAccessor) {\r
+ var value = ko.utils.unwrapObservable(valueAccessor());\r
+ value ? element.focus() : element.blur();\r
+ ko.utils.triggerEvent(element, value ? "focusin" : "focusout"); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously\r
+ }\r
+};\r
+\r
+// "with: someExpression" is equivalent to "template: { if: someExpression, data: someExpression }"\r
+ko.bindingHandlers['with'] = {\r
+ makeTemplateValueAccessor: function(valueAccessor) {\r
+ return function() { var value = valueAccessor(); return { 'if': value, 'data': value, 'templateEngine': ko.nativeTemplateEngine.instance } };\r
+ },\r
+ 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {\r
+ return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['with'].makeTemplateValueAccessor(valueAccessor));\r
+ },\r
+ 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {\r
+ return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['with'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);\r
+ }\r
+};\r
+ko.jsonExpressionRewriting.bindingRewriteValidators['with'] = false; // Can't rewrite control flow bindings\r
+ko.virtualElements.allowedBindings['with'] = true;\r
+\r
+// "if: someExpression" is equivalent to "template: { if: someExpression }"\r
+ko.bindingHandlers['if'] = {\r
+ makeTemplateValueAccessor: function(valueAccessor) {\r
+ return function() { return { 'if': valueAccessor(), 'templateEngine': ko.nativeTemplateEngine.instance } };\r
+ }, \r
+ 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {\r
+ return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['if'].makeTemplateValueAccessor(valueAccessor));\r
+ },\r
+ 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {\r
+ return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['if'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);\r
+ }\r
+};\r
+ko.jsonExpressionRewriting.bindingRewriteValidators['if'] = false; // Can't rewrite control flow bindings\r
+ko.virtualElements.allowedBindings['if'] = true;\r
+\r
+// "ifnot: someExpression" is equivalent to "template: { ifnot: someExpression }"\r
+ko.bindingHandlers['ifnot'] = {\r
+ makeTemplateValueAccessor: function(valueAccessor) {\r
+ return function() { return { 'ifnot': valueAccessor(), 'templateEngine': ko.nativeTemplateEngine.instance } };\r
+ }, \r
+ 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {\r
+ return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['ifnot'].makeTemplateValueAccessor(valueAccessor));\r
+ },\r
+ 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {\r
+ return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['ifnot'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);\r
+ }\r
+};\r
+ko.jsonExpressionRewriting.bindingRewriteValidators['ifnot'] = false; // Can't rewrite control flow bindings\r
+ko.virtualElements.allowedBindings['ifnot'] = true;\r
+\r
+// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"\r
+// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"\r
+ko.bindingHandlers['foreach'] = {\r
+ makeTemplateValueAccessor: function(valueAccessor) {\r
+ return function() { \r
+ var bindingValue = ko.utils.unwrapObservable(valueAccessor());\r
+ \r
+ // If bindingValue is the array, just pass it on its own\r
+ if ((!bindingValue) || typeof bindingValue.length == "number")\r
+ return { 'foreach': bindingValue, 'templateEngine': ko.nativeTemplateEngine.instance };\r
+ \r
+ // If bindingValue.data is the array, preserve all relevant options\r
+ return { \r
+ 'foreach': bindingValue['data'], \r
+ 'includeDestroyed': bindingValue['includeDestroyed'],\r
+ 'afterAdd': bindingValue['afterAdd'],\r
+ 'beforeRemove': bindingValue['beforeRemove'], \r
+ 'afterRender': bindingValue['afterRender'],\r
+ 'templateEngine': ko.nativeTemplateEngine.instance\r
+ };\r
+ };\r
+ },\r
+ 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { \r
+ return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));\r
+ },\r
+ 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {\r
+ return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);\r
+ }\r
+};\r
+ko.jsonExpressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings\r
+ko.virtualElements.allowedBindings['foreach'] = true;\r
+ko.exportSymbol('ko.allowedVirtualElementBindings', ko.virtualElements.allowedBindings);// If you want to make a custom template engine,\r
+// \r
+// [1] Inherit from this class (like ko.nativeTemplateEngine does)\r
+// [2] Override 'renderTemplateSource', supplying a function with this signature:\r
+//\r
+// function (templateSource, bindingContext, options) {\r
+// // - templateSource.text() is the text of the template you should render\r
+// // - bindingContext.$data is the data you should pass into the template\r
+// // - you might also want to make bindingContext.$parent, bindingContext.$parents, \r
+// // and bindingContext.$root available in the template too\r
+// // - options gives you access to any other properties set on "data-bind: { template: options }"\r
+// //\r
+// // Return value: an array of DOM nodes\r
+// }\r
+//\r
+// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:\r
+//\r
+// function (script) {\r
+// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"\r
+// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }' \r
+// }\r
+//\r
+// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.\r
+// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)\r
+// and then you don't need to override 'createJavaScriptEvaluatorBlock'.\r
+\r
+ko.templateEngine = function () { };\r
+\r
+ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {\r
+ throw "Override renderTemplateSource";\r
+};\r
+\r
+ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {\r
+ throw "Override createJavaScriptEvaluatorBlock";\r
+};\r
+\r
+ko.templateEngine.prototype['makeTemplateSource'] = function(template) {\r
+ // Named template\r
+ if (typeof template == "string") {\r
+ var elem = document.getElementById(template);\r
+ if (!elem)\r
+ throw new Error("Cannot find template with ID " + template);\r
+ return new ko.templateSources.domElement(elem);\r
+ } else if ((template.nodeType == 1) || (template.nodeType == 8)) {\r
+ // Anonymous template\r
+ return new ko.templateSources.anonymousTemplate(template);\r
+ } else\r
+ throw new Error("Unknown template type: " + template);\r
+};\r
+\r
+ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options) {\r
+ var templateSource = this['makeTemplateSource'](template);\r
+ return this['renderTemplateSource'](templateSource, bindingContext, options);\r
+};\r
+\r
+ko.templateEngine.prototype['isTemplateRewritten'] = function (template) {\r
+ // Skip rewriting if requested\r
+ if (this['allowTemplateRewriting'] === false)\r
+ return true;\r
+ \r
+ // Perf optimisation - see below\r
+ if (this.knownRewrittenTemplates && this.knownRewrittenTemplates[template])\r
+ return true;\r
+ \r
+ return this['makeTemplateSource'](template)['data']("isRewritten");\r
+};\r
+\r
+ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback) {\r
+ var templateSource = this['makeTemplateSource'](template); \r
+ var rewritten = rewriterCallback(templateSource['text']());\r
+ templateSource['text'](rewritten);\r
+ templateSource['data']("isRewritten", true);\r
+ \r
+ // Perf optimisation - for named templates, track which ones have been rewritten so we can\r
+ // answer 'isTemplateRewritten' *without* having to use getElementById (which is slow on IE < 8)\r
+ if (typeof template == "string") {\r
+ this.knownRewrittenTemplates = this.knownRewrittenTemplates || {};\r
+ this.knownRewrittenTemplates[template] = true; \r
+ }\r
+};\r
+\r
+ko.exportSymbol('ko.templateEngine', ko.templateEngine);\r
+ko.templateRewriting = (function () {\r
+ var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;\r
+ var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;\r
+\r
+ function validateDataBindValuesForRewriting(keyValueArray) {\r
+ var allValidators = ko.jsonExpressionRewriting.bindingRewriteValidators;\r
+ for (var i = 0; i < keyValueArray.length; i++) {\r
+ var key = keyValueArray[i]['key'];\r
+ if (allValidators.hasOwnProperty(key)) {\r
+ var validator = allValidators[key]; \r
+\r
+ if (typeof validator === "function") {\r
+ var possibleErrorMessage = validator(keyValueArray[i]['value']);\r
+ if (possibleErrorMessage)\r
+ throw new Error(possibleErrorMessage);\r
+ } else if (!validator) {\r
+ throw new Error("This template engine does not support the '" + key + "' binding within its templates");\r
+ } \r
+ }\r
+ }\r
+ }\r
+\r
+ function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {\r
+ var dataBindKeyValueArray = ko.jsonExpressionRewriting.parseObjectLiteral(dataBindAttributeValue);\r
+ validateDataBindValuesForRewriting(dataBindKeyValueArray);\r
+ var rewrittenDataBindAttributeValue = ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson(dataBindKeyValueArray);\r
+\r
+ // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional \r
+ // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this \r
+ // extra indirection.\r
+ var applyBindingsToNextSiblingScript = "ko.templateRewriting.applyMemoizedBindingsToNextSibling(function() { \\r
+ return (function() { return { " + rewrittenDataBindAttributeValue + " } })() \\r
+ })";\r
+ return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain; \r
+ }\r
+\r
+ return {\r
+ ensureTemplateIsRewritten: function (template, templateEngine) {\r
+ if (!templateEngine['isTemplateRewritten'](template))\r
+ templateEngine['rewriteTemplate'](template, function (htmlString) {\r
+ return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);\r
+ });\r
+ },\r
+\r
+ memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {\r
+ return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {\r
+ return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);\r
+ }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {\r
+ return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine); \r
+ });\r
+ },\r
+\r
+ applyMemoizedBindingsToNextSibling: function (bindings) {\r
+ return ko.memoization.memoize(function (domNode, bindingContext) {\r
+ if (domNode.nextSibling)\r
+ ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);\r
+ });\r
+ }\r
+ }\r
+})();\r
+\r
+ko.exportSymbol('ko.templateRewriting', ko.templateRewriting);\r
+ko.exportSymbol('ko.templateRewriting.applyMemoizedBindingsToNextSibling', ko.templateRewriting.applyMemoizedBindingsToNextSibling); // Exported only because it has to be referenced by string lookup from within rewritten template\r
+(function() { \r
+ // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving\r
+ // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)\r
+ //\r
+ // Two are provided by default:\r
+ // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element\r
+ // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but \r
+ // without reading/writing the actual element text content, since it will be overwritten\r
+ // with the rendered template output.\r
+ // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.\r
+ // Template sources need to have the following functions:\r
+ // text() - returns the template text from your storage location\r
+ // text(value) - writes the supplied template text to your storage location\r
+ // data(key) - reads values stored using data(key, value) - see below\r
+ // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".\r
+ //\r
+ // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were\r
+ // using and overriding "makeTemplateSource" to return an instance of your custom template source.\r
+ \r
+ ko.templateSources = {};\r
+ \r
+ // ---- ko.templateSources.domElement -----\r
+ \r
+ ko.templateSources.domElement = function(element) {\r
+ this.domElement = element;\r
+ }\r
+ \r
+ ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {\r
+ if (arguments.length == 0) {\r
+ return this.domElement.tagName.toLowerCase() == "script" ? this.domElement.text : this.domElement.innerHTML;\r
+ } else {\r
+ var valueToWrite = arguments[0];\r
+ if (this.domElement.tagName.toLowerCase() == "script")\r
+ this.domElement.text = valueToWrite;\r
+ else\r
+ ko.utils.setHtml(this.domElement, valueToWrite);\r
+ }\r
+ };\r
+ \r
+ ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {\r
+ if (arguments.length === 1) {\r
+ return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);\r
+ } else {\r
+ ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);\r
+ }\r
+ };\r
+ \r
+ // ---- ko.templateSources.anonymousTemplate -----\r
+ \r
+ var anonymousTemplatesDomDataKey = "__ko_anon_template__";\r
+ ko.templateSources.anonymousTemplate = function(element) { \r
+ this.domElement = element;\r
+ }\r
+ ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();\r
+ ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {\r
+ if (arguments.length == 0) {\r
+ return ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey);\r
+ } else {\r
+ var valueToWrite = arguments[0];\r
+ ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, valueToWrite);\r
+ }\r
+ };\r
+ \r
+ ko.exportSymbol('ko.templateSources', ko.templateSources);\r
+ ko.exportSymbol('ko.templateSources.domElement', ko.templateSources.domElement);\r
+ ko.exportSymbol('ko.templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);\r
+})();\r
+(function () {\r
+ var _templateEngine;\r
+ ko.setTemplateEngine = function (templateEngine) {\r
+ if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))\r
+ throw "templateEngine must inherit from ko.templateEngine";\r
+ _templateEngine = templateEngine;\r
+ }\r
+\r
+ function invokeForEachNodeOrCommentInParent(nodeArray, parent, action) {\r
+ for (var i = 0; node = nodeArray[i]; i++) {\r
+ if (node.parentNode !== parent) // Skip anything that has been removed during binding\r
+ continue;\r
+ if ((node.nodeType === 1) || (node.nodeType === 8))\r
+ action(node);\r
+ } \r
+ }\r
+\r
+ ko.activateBindingsOnTemplateRenderedNodes = function(nodeArray, bindingContext) {\r
+ // To be used on any nodes that have been rendered by a template and have been inserted into some parent element. \r
+ // Safely iterates through nodeArray (being tolerant of any changes made to it during binding, e.g., \r
+ // if a binding inserts siblings), and for each:\r
+ // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings\r
+ // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)\r
+\r
+ var nodeArrayClone = ko.utils.arrayPushAll([], nodeArray); // So we can tolerate insertions/deletions during binding\r
+ var commonParentElement = (nodeArray.length > 0) ? nodeArray[0].parentNode : null; // All items must be in the same parent, so this is OK\r
+ \r
+ // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)\r
+ // whereas a regular applyBindings won't introduce new memoized nodes\r
+ \r
+ invokeForEachNodeOrCommentInParent(nodeArrayClone, commonParentElement, function(node) {\r
+ ko.applyBindings(bindingContext, node);\r
+ });\r
+ invokeForEachNodeOrCommentInParent(nodeArrayClone, commonParentElement, function(node) {\r
+ ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]); \r
+ }); \r
+ }\r
+\r
+ function getFirstNodeFromPossibleArray(nodeOrNodeArray) {\r
+ return nodeOrNodeArray.nodeType ? nodeOrNodeArray\r
+ : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]\r
+ : null;\r
+ }\r
+\r
+ function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {\r
+ options = options || {};\r
+ var templateEngineToUse = (options['templateEngine'] || _templateEngine);\r
+ ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse);\r
+ var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options);\r
+\r
+ // Loosely check result is an array of DOM nodes\r
+ if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))\r
+ throw "Template engine must return an array of DOM nodes";\r
+\r
+ var haveAddedNodesToParent = false;\r
+ switch (renderMode) {\r
+ case "replaceChildren": \r
+ ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray); \r
+ haveAddedNodesToParent = true;\r
+ break;\r
+ case "replaceNode": \r
+ ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray); \r
+ haveAddedNodesToParent = true;\r
+ break;\r
+ case "ignoreTargetNode": break;\r
+ default: \r
+ throw new Error("Unknown renderMode: " + renderMode);\r
+ }\r
+\r
+ if (haveAddedNodesToParent) {\r
+ ko.activateBindingsOnTemplateRenderedNodes(renderedNodesArray, bindingContext);\r
+ if (options['afterRender'])\r
+ options['afterRender'](renderedNodesArray, bindingContext['$data']); \r
+ }\r
+\r
+ return renderedNodesArray;\r
+ }\r
+\r
+ ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {\r
+ options = options || {};\r
+ if ((options['templateEngine'] || _templateEngine) == undefined)\r
+ throw "Set a template engine before calling renderTemplate";\r
+ renderMode = renderMode || "replaceChildren";\r
+\r
+ if (targetNodeOrNodeArray) {\r
+ var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);\r
+ \r
+ var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)\r
+ var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;\r
+ \r
+ return new ko.dependentObservable( // So the DOM is automatically updated when any dependency changes \r
+ function () {\r
+ // Ensure we've got a proper binding context to work with\r
+ var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))\r
+ ? dataOrBindingContext\r
+ : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));\r
+\r
+ // Support selecting template as a function of the data being rendered\r
+ var templateName = typeof(template) == 'function' ? template(bindingContext['$data']) : template; \r
+\r
+ var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);\r
+ if (renderMode == "replaceNode") {\r
+ targetNodeOrNodeArray = renderedNodesArray;\r
+ firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);\r
+ }\r
+ },\r
+ null,\r
+ { 'disposeWhen': whenToDispose, 'disposeWhenNodeIsRemoved': activelyDisposeWhenNodeIsRemoved }\r
+ );\r
+ } else {\r
+ // 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\r
+ return ko.memoization.memoize(function (domNode) {\r
+ ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");\r
+ });\r
+ }\r
+ };\r
+\r
+ ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) { \r
+ var createInnerBindingContext = function(arrayValue) {\r
+ return parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue));\r
+ };\r
+\r
+ // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode\r
+ var activateBindingsCallback = function(arrayValue, addedNodesArray) {\r
+ var bindingContext = createInnerBindingContext(arrayValue);\r
+ ko.activateBindingsOnTemplateRenderedNodes(addedNodesArray, bindingContext);\r
+ if (options['afterRender'])\r
+ options['afterRender'](addedNodesArray, bindingContext['$data']); \r
+ };\r
+ \r
+ return new ko.dependentObservable(function () {\r
+ var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];\r
+ if (typeof unwrappedArray.length == "undefined") // Coerce single value into array\r
+ unwrappedArray = [unwrappedArray];\r
+\r
+ // Filter out any entries marked as destroyed\r
+ var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {\r
+ return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);\r
+ });\r
+\r
+ ko.utils.setDomNodeChildrenFromArrayMapping(targetNode, filteredArray, function (arrayValue) {\r
+ // Support selecting template as a function of the data being rendered\r
+ var templateName = typeof(template) == 'function' ? template(arrayValue) : template;\r
+ return executeTemplate(null, "ignoreTargetNode", templateName, createInnerBindingContext(arrayValue), options);\r
+ }, options, activateBindingsCallback);\r
+ \r
+ }, null, { 'disposeWhenNodeIsRemoved': targetNode });\r
+ };\r
+\r
+ var templateSubscriptionDomDataKey = '__ko__templateSubscriptionDomDataKey__';\r
+ function disposeOldSubscriptionAndStoreNewOne(element, newSubscription) {\r
+ var oldSubscription = ko.utils.domData.get(element, templateSubscriptionDomDataKey);\r
+ if (oldSubscription && (typeof(oldSubscription.dispose) == 'function'))\r
+ oldSubscription.dispose();\r
+ ko.utils.domData.set(element, templateSubscriptionDomDataKey, newSubscription);\r
+ }\r
+ \r
+ ko.bindingHandlers['template'] = {\r
+ 'init': function(element, valueAccessor) {\r
+ // Support anonymous templates\r
+ var bindingValue = ko.utils.unwrapObservable(valueAccessor());\r
+ if ((typeof bindingValue != "string") && (!bindingValue.name) && (element.nodeType == 1)) {\r
+ // It's an anonymous template - store the element contents, then clear the element\r
+ new ko.templateSources.anonymousTemplate(element).text(element.innerHTML);\r
+ ko.utils.emptyDomNode(element);\r
+ }\r
+ return { 'controlsDescendantBindings': true };\r
+ },\r
+ 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {\r
+ var bindingValue = ko.utils.unwrapObservable(valueAccessor());\r
+ var templateName; \r
+ var shouldDisplay = true;\r
+ \r
+ if (typeof bindingValue == "string") {\r
+ templateName = bindingValue;\r
+ } else {\r
+ templateName = bindingValue.name;\r
+ \r
+ // Support "if"/"ifnot" conditions\r
+ if ('if' in bindingValue)\r
+ shouldDisplay = shouldDisplay && ko.utils.unwrapObservable(bindingValue['if']);\r
+ if ('ifnot' in bindingValue)\r
+ shouldDisplay = shouldDisplay && !ko.utils.unwrapObservable(bindingValue['ifnot']);\r
+ } \r
+ \r
+ var templateSubscription = null;\r
+ \r
+ if ((typeof bindingValue === 'object') && ('foreach' in bindingValue)) { // Note: can't use 'in' operator on strings\r
+ // Render once for each data point (treating data set as empty if shouldDisplay==false)\r
+ var dataArray = (shouldDisplay && bindingValue['foreach']) || [];\r
+ templateSubscription = ko.renderTemplateForEach(templateName || element, dataArray, /* options: */ bindingValue, element, bindingContext);\r
+ } else {\r
+ if (shouldDisplay) {\r
+ // Render once for this single data point (or use the viewModel if no data was provided)\r
+ var innerBindingContext = (typeof bindingValue == 'object') && ('data' in bindingValue)\r
+ ? bindingContext['createChildContext'](ko.utils.unwrapObservable(bindingValue['data'])) // Given an explitit 'data' value, we create a child binding context for it\r
+ : bindingContext; // Given no explicit 'data' value, we retain the same binding context\r
+ templateSubscription = ko.renderTemplate(templateName || element, innerBindingContext, /* options: */ bindingValue, element);\r
+ } else\r
+ ko.virtualElements.emptyNode(element);\r
+ }\r
+ \r
+ // It only makes sense to have a single template subscription per element (otherwise which one should have its output displayed?)\r
+ disposeOldSubscriptionAndStoreNewOne(element, templateSubscription);\r
+ }\r
+ };\r
+\r
+ // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.\r
+ ko.jsonExpressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {\r
+ var parsedBindingValue = ko.jsonExpressionRewriting.parseObjectLiteral(bindingValue);\r
+\r
+ if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])\r
+ return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)\r
+\r
+ if (ko.jsonExpressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))\r
+ return null; // Named templates can be rewritten, so return "no error"\r
+ return "This template engine does not support anonymous templates nested within its templates";\r
+ };\r
+\r
+ ko.virtualElements.allowedBindings['template'] = true;\r
+})();\r
+\r
+ko.exportSymbol('ko.setTemplateEngine', ko.setTemplateEngine);\r
+ko.exportSymbol('ko.renderTemplate', ko.renderTemplate);\r
+(function () {\r
+ // Simple calculation based on Levenshtein distance.\r
+ function calculateEditDistanceMatrix(oldArray, newArray, maxAllowedDistance) {\r
+ var distances = [];\r
+ for (var i = 0; i <= newArray.length; i++)\r
+ distances[i] = [];\r
+\r
+ // Top row - transform old array into empty array via deletions\r
+ for (var i = 0, j = Math.min(oldArray.length, maxAllowedDistance); i <= j; i++)\r
+ distances[0][i] = i;\r
+\r
+ // Left row - transform empty array into new array via additions\r
+ for (var i = 1, j = Math.min(newArray.length, maxAllowedDistance); i <= j; i++) {\r
+ distances[i][0] = i;\r
+ }\r
+\r
+ // Fill out the body of the array\r
+ var oldIndex, oldIndexMax = oldArray.length, newIndex, newIndexMax = newArray.length;\r
+ var distanceViaAddition, distanceViaDeletion;\r
+ for (oldIndex = 1; oldIndex <= oldIndexMax; oldIndex++) {\r
+ var newIndexMinForRow = Math.max(1, oldIndex - maxAllowedDistance);\r
+ var newIndexMaxForRow = Math.min(newIndexMax, oldIndex + maxAllowedDistance);\r
+ for (newIndex = newIndexMinForRow; newIndex <= newIndexMaxForRow; newIndex++) {\r
+ if (oldArray[oldIndex - 1] === newArray[newIndex - 1])\r
+ distances[newIndex][oldIndex] = distances[newIndex - 1][oldIndex - 1];\r
+ else {\r
+ var northDistance = distances[newIndex - 1][oldIndex] === undefined ? Number.MAX_VALUE : distances[newIndex - 1][oldIndex] + 1;\r
+ var westDistance = distances[newIndex][oldIndex - 1] === undefined ? Number.MAX_VALUE : distances[newIndex][oldIndex - 1] + 1;\r
+ distances[newIndex][oldIndex] = Math.min(northDistance, westDistance);\r
+ }\r
+ }\r
+ }\r
+\r
+ return distances;\r
+ }\r
+\r
+ function findEditScriptFromEditDistanceMatrix(editDistanceMatrix, oldArray, newArray) {\r
+ var oldIndex = oldArray.length;\r
+ var newIndex = newArray.length;\r
+ var editScript = [];\r
+ var maxDistance = editDistanceMatrix[newIndex][oldIndex];\r
+ if (maxDistance === undefined)\r
+ return null; // maxAllowedDistance must be too small\r
+ while ((oldIndex > 0) || (newIndex > 0)) {\r
+ var me = editDistanceMatrix[newIndex][oldIndex];\r
+ var distanceViaAdd = (newIndex > 0) ? editDistanceMatrix[newIndex - 1][oldIndex] : maxDistance + 1;\r
+ var distanceViaDelete = (oldIndex > 0) ? editDistanceMatrix[newIndex][oldIndex - 1] : maxDistance + 1;\r
+ var distanceViaRetain = (newIndex > 0) && (oldIndex > 0) ? editDistanceMatrix[newIndex - 1][oldIndex - 1] : maxDistance + 1;\r
+ if ((distanceViaAdd === undefined) || (distanceViaAdd < me - 1)) distanceViaAdd = maxDistance + 1;\r
+ if ((distanceViaDelete === undefined) || (distanceViaDelete < me - 1)) distanceViaDelete = maxDistance + 1;\r
+ if (distanceViaRetain < me - 1) distanceViaRetain = maxDistance + 1;\r
+\r
+ if ((distanceViaAdd <= distanceViaDelete) && (distanceViaAdd < distanceViaRetain)) {\r
+ editScript.push({ status: "added", value: newArray[newIndex - 1] });\r
+ newIndex--;\r
+ } else if ((distanceViaDelete < distanceViaAdd) && (distanceViaDelete < distanceViaRetain)) {\r
+ editScript.push({ status: "deleted", value: oldArray[oldIndex - 1] });\r
+ oldIndex--;\r
+ } else {\r
+ editScript.push({ status: "retained", value: oldArray[oldIndex - 1] });\r
+ newIndex--;\r
+ oldIndex--;\r
+ }\r
+ }\r
+ return editScript.reverse();\r
+ }\r
+\r
+ ko.utils.compareArrays = function (oldArray, newArray, maxEditsToConsider) {\r
+ if (maxEditsToConsider === undefined) {\r
+ return ko.utils.compareArrays(oldArray, newArray, 1) // First consider likely case where there is at most one edit (very fast)\r
+ || ko.utils.compareArrays(oldArray, newArray, 10) // If that fails, account for a fair number of changes while still being fast\r
+ || ko.utils.compareArrays(oldArray, newArray, Number.MAX_VALUE); // Ultimately give the right answer, even though it may take a long time\r
+ } else {\r
+ oldArray = oldArray || [];\r
+ newArray = newArray || [];\r
+ var editDistanceMatrix = calculateEditDistanceMatrix(oldArray, newArray, maxEditsToConsider);\r
+ return findEditScriptFromEditDistanceMatrix(editDistanceMatrix, oldArray, newArray);\r
+ }\r
+ }; \r
+})();\r
+\r
+ko.exportSymbol('ko.utils.compareArrays', ko.utils.compareArrays);\r
+\r
+(function () {\r
+ // Objective:\r
+ // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,\r
+ // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node\r
+ // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node\r
+ // 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\r
+ // previously mapped - retain those nodes, and just insert/delete other ones\r
+\r
+ // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node\r
+ // You can use this, for example, to activate bindings on those nodes.\r
+\r
+ function fixUpVirtualElements(contiguousNodeArray) {\r
+ // Ensures that contiguousNodeArray really *is* an array of contiguous siblings, even if some of the interior\r
+ // ones have changed since your array was first built (e.g., because your array contains virtual elements, and\r
+ // their virtual children changed when binding was applied to them).\r
+ // This is needed so that we can reliably remove or update the nodes corresponding to a given array item\r
+\r
+ if (contiguousNodeArray.length > 2) {\r
+ // Build up the actual new contiguous node set\r
+ var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];\r
+ while (current !== last) {\r
+ current = current.nextSibling;\r
+ if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)\r
+ return;\r
+ newContiguousSet.push(current);\r
+ }\r
+\r
+ // ... then mutate the input array to match this. \r
+ // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)\r
+ Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));\r
+ }\r
+ }\r
+\r
+ function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes) {\r
+ // Map this array value inside a dependentObservable so we re-map when any dependency changes\r
+ var mappedNodes = [];\r
+ var dependentObservable = ko.dependentObservable(function() {\r
+ var newMappedNodes = mapping(valueToMap) || [];\r
+ \r
+ // On subsequent evaluations, just replace the previously-inserted DOM nodes\r
+ if (mappedNodes.length > 0) {\r
+ fixUpVirtualElements(mappedNodes);\r
+ ko.utils.replaceDomNodes(mappedNodes, newMappedNodes);\r
+ if (callbackAfterAddingNodes)\r
+ callbackAfterAddingNodes(valueToMap, newMappedNodes);\r
+ }\r
+ \r
+ // Replace the contents of the mappedNodes array, thereby updating the record\r
+ // of which nodes would be deleted if valueToMap was itself later removed\r
+ mappedNodes.splice(0, mappedNodes.length);\r
+ ko.utils.arrayPushAll(mappedNodes, newMappedNodes);\r
+ }, null, { 'disposeWhenNodeIsRemoved': containerNode, 'disposeWhen': function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });\r
+ return { mappedNodes : mappedNodes, dependentObservable : dependentObservable };\r
+ }\r
+ \r
+ var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";\r
+\r
+ ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {\r
+ // Compare the provided array against the previous one\r
+ array = array || [];\r
+ options = options || {};\r
+ var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;\r
+ var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];\r
+ var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });\r
+ var editScript = ko.utils.compareArrays(lastArray, array);\r
+\r
+ // Build the new mapping result\r
+ var newMappingResult = [];\r
+ var lastMappingResultIndex = 0;\r
+ var nodesToDelete = [];\r
+ var nodesAdded = [];\r
+ var insertAfterNode = null;\r
+ for (var i = 0, j = editScript.length; i < j; i++) {\r
+ switch (editScript[i].status) {\r
+ case "retained":\r
+ // Just keep the information - don't touch the nodes\r
+ var dataToRetain = lastMappingResult[lastMappingResultIndex];\r
+ newMappingResult.push(dataToRetain);\r
+ if (dataToRetain.domNodes.length > 0)\r
+ insertAfterNode = dataToRetain.domNodes[dataToRetain.domNodes.length - 1];\r
+ lastMappingResultIndex++;\r
+ break;\r
+\r
+ case "deleted":\r
+ // Stop tracking changes to the mapping for these nodes\r
+ lastMappingResult[lastMappingResultIndex].dependentObservable.dispose();\r
+ \r
+ // Queue these nodes for later removal\r
+ fixUpVirtualElements(lastMappingResult[lastMappingResultIndex].domNodes);\r
+ ko.utils.arrayForEach(lastMappingResult[lastMappingResultIndex].domNodes, function (node) {\r
+ nodesToDelete.push({\r
+ element: node,\r
+ index: i,\r
+ value: editScript[i].value\r
+ });\r
+ insertAfterNode = node;\r
+ });\r
+ lastMappingResultIndex++;\r
+ break;\r
+\r
+ case "added": \r
+ var valueToMap = editScript[i].value;\r
+ var mapData = mapNodeAndRefreshWhenChanged(domNode, mapping, valueToMap, callbackAfterAddingNodes);\r
+ var mappedNodes = mapData.mappedNodes;\r
+ \r
+ // On the first evaluation, insert the nodes at the current insertion point\r
+ newMappingResult.push({ arrayEntry: editScript[i].value, domNodes: mappedNodes, dependentObservable: mapData.dependentObservable });\r
+ for (var nodeIndex = 0, nodeIndexMax = mappedNodes.length; nodeIndex < nodeIndexMax; nodeIndex++) {\r
+ var node = mappedNodes[nodeIndex];\r
+ nodesAdded.push({\r
+ element: node,\r
+ index: i,\r
+ value: editScript[i].value\r
+ });\r
+ if (insertAfterNode == null) {\r
+ // Insert "node" (the newly-created node) as domNode's first child\r
+ ko.virtualElements.prepend(domNode, node);\r
+ } else {\r
+ // Insert "node" into "domNode" immediately after "insertAfterNode"\r
+ ko.virtualElements.insertAfter(domNode, node, insertAfterNode);\r
+ }\r
+ insertAfterNode = node;\r
+ } \r
+ if (callbackAfterAddingNodes)\r
+ callbackAfterAddingNodes(valueToMap, mappedNodes);\r
+ break;\r
+ }\r
+ }\r
+ \r
+ ko.utils.arrayForEach(nodesToDelete, function (node) { ko.cleanNode(node.element) });\r
+\r
+ var invokedBeforeRemoveCallback = false;\r
+ if (!isFirstExecution) {\r
+ if (options['afterAdd']) {\r
+ for (var i = 0; i < nodesAdded.length; i++)\r
+ options['afterAdd'](nodesAdded[i].element, nodesAdded[i].index, nodesAdded[i].value);\r
+ }\r
+ if (options['beforeRemove']) {\r
+ for (var i = 0; i < nodesToDelete.length; i++)\r
+ options['beforeRemove'](nodesToDelete[i].element, nodesToDelete[i].index, nodesToDelete[i].value);\r
+ invokedBeforeRemoveCallback = true;\r
+ }\r
+ }\r
+ if (!invokedBeforeRemoveCallback)\r
+ ko.utils.arrayForEach(nodesToDelete, function (node) {\r
+ ko.removeNode(node.element);\r
+ });\r
+\r
+ // Store a copy of the array items we just considered so we can difference it next time\r
+ ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);\r
+ }\r
+})();\r
+\r
+ko.exportSymbol('ko.utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);\r
+ko.nativeTemplateEngine = function () {\r
+ this['allowTemplateRewriting'] = false;\r
+}\r
+\r
+ko.nativeTemplateEngine.prototype = new ko.templateEngine();\r
+ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {\r
+ var templateText = templateSource.text();\r
+ return ko.utils.parseHtmlFragment(templateText);\r
+};\r
+\r
+ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();\r
+ko.setTemplateEngine(ko.nativeTemplateEngine.instance);\r
+\r
+ko.exportSymbol('ko.nativeTemplateEngine', ko.nativeTemplateEngine);(function() {\r
+ ko.jqueryTmplTemplateEngine = function () {\r
+ // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl \r
+ // doesn't expose a version number, so we have to infer it.\r
+ // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,\r
+ // which KO internally refers to as version "2", so older versions are no longer detected.\r
+ var jQueryTmplVersion = this.jQueryTmplVersion = (function() { \r
+ if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))\r
+ return 0;\r
+ // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.\r
+ try {\r
+ if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {\r
+ // Since 1.0.0pre, custom tags should append markup to an array called "__"\r
+ return 2; // Final version of jquery.tmpl\r
+ } \r
+ } catch(ex) { /* Apparently not the version we were looking for */ }\r
+ \r
+ return 1; // Any older version that we don't support\r
+ })();\r
+ \r
+ function ensureHasReferencedJQueryTemplates() {\r
+ if (jQueryTmplVersion < 2)\r
+ throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");\r
+ }\r
+\r
+ function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {\r
+ return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);\r
+ }\r
+ \r
+ this['renderTemplateSource'] = function(templateSource, bindingContext, options) {\r
+ options = options || {};\r
+ ensureHasReferencedJQueryTemplates();\r
+ \r
+ // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)\r
+ var precompiled = templateSource['data']('precompiled');\r
+ if (!precompiled) {\r
+ var templateText = templateSource.text() || "";\r
+ // Wrap in "with($whatever.koBindingContext) { ... }"\r
+ templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";\r
+\r
+ precompiled = jQuery['template'](null, templateText);\r
+ templateSource['data']('precompiled', precompiled);\r
+ }\r
+ \r
+ var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays\r
+ var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);\r
+\r
+ var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);\r
+ resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work\r
+ jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders\r
+ return resultNodes; \r
+ };\r
+ \r
+ this['createJavaScriptEvaluatorBlock'] = function(script) {\r
+ return "{{ko_code ((function() { return " + script + " })()) }}";\r
+ };\r
+ \r
+ this['addTemplate'] = function(templateName, templateMarkup) {\r
+ document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");\r
+ };\r
+ \r
+ if (jQueryTmplVersion > 0) {\r
+ jQuery['tmpl']['tag']['ko_code'] = {\r
+ open: "__.push($1 || '');"\r
+ };\r
+ jQuery['tmpl']['tag']['ko_with'] = {\r
+ open: "with($1) {",\r
+ close: "} "\r
+ };\r
+ }\r
+ };\r
+ \r
+ ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();\r
+ \r
+ // Use this one by default *only if jquery.tmpl is referenced*\r
+ var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();\r
+ if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)\r
+ ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);\r
+ \r
+ ko.exportSymbol('ko.jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);\r
+})();})(window); \r