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