]> git.proxmox.com Git - pve-eslint.git/blob - eslint/tests/bench/small.js
bump version to 7.12.1-1
[pve-eslint.git] / eslint / tests / bench / small.js
1 // Knockout JavaScript library v3.0.0
2 // (c) Steven Sanderson - http://knockoutjs.com/
3 // License: MIT (http://www.opensource.org/licenses/mit-license.php)
4
5 (function(){
6 var DEBUG=true;
7 (function(undefined){
8 // (0, eval)('this') is a robust way of getting a reference to the global object
9 // For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023
10 var window = this || (0, eval)('this'),
11 document = window['document'],
12 navigator = window['navigator'],
13 jQuery = window["jQuery"],
14 JSON = window["JSON"];
15 (function(factory) {
16 // Support three module loading scenarios
17 if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
18 // [1] CommonJS/Node.js
19 var target = module['exports'] || exports; // module.exports is for Node.js
20 factory(target);
21 } else if (typeof define === 'function' && define['amd']) {
22 // [2] AMD anonymous module
23 define(['exports'], factory);
24 } else {
25 // [3] No module loader (plain <script> tag) - put directly in global namespace
26 factory(window['ko'] = {});
27 }
28 }(function(koExports){
29 // Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
30 // In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
31 var ko = typeof koExports !== 'undefined' ? koExports : {};
32 // Google Closure Compiler helpers (used only to make the minified file smaller)
33 ko.exportSymbol = function(koPath, object) {
34 var tokens = koPath.split(".");
35
36 // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
37 // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
38 var target = ko;
39
40 for (var i = 0; i < tokens.length - 1; i++)
41 target = target[tokens[i]];
42 target[tokens[tokens.length - 1]] = object;
43 };
44 ko.exportProperty = function(owner, publicName, object) {
45 owner[publicName] = object;
46 };
47 ko.version = "3.0.0";
48
49 ko.exportSymbol('version', ko.version);
50 ko.utils = (function () {
51 var objectForEach = function(obj, action) {
52 for (var prop in obj) {
53 if (obj.hasOwnProperty(prop)) {
54 action(prop, obj[prop]);
55 }
56 }
57 };
58
59 // 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)
60 var knownEvents = {}, knownEventTypesByEventName = {};
61 var keyEventTypeName = (navigator && /Firefox\/2/i.test(navigator.userAgent)) ? 'KeyboardEvent' : 'UIEvents';
62 knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
63 knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
64 objectForEach(knownEvents, function(eventType, knownEventsForType) {
65 if (knownEventsForType.length) {
66 for (var i = 0, j = knownEventsForType.length; i < j; i++)
67 knownEventTypesByEventName[knownEventsForType[i]] = eventType;
68 }
69 });
70 var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
71
72 // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
73 // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
74 // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
75 // If there is a future need to detect specific versions of IE10+, we will amend this.
76 var ieVersion = document && (function() {
77 var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
78
79 // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
80 while (
81 div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
82 iElems[0]
83 ) {}
84 return version > 4 ? version : undefined;
85 }());
86 var isIe6 = ieVersion === 6,
87 isIe7 = ieVersion === 7;
88
89 function isClickOnCheckableElement(element, eventType) {
90 if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
91 if (eventType.toLowerCase() != "click") return false;
92 var inputType = element.type;
93 return (inputType == "checkbox") || (inputType == "radio");
94 }
95
96 return {
97 fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
98
99 arrayForEach: function (array, action) {
100 for (var i = 0, j = array.length; i < j; i++)
101 action(array[i]);
102 },
103
104 arrayIndexOf: function (array, item) {
105 if (typeof Array.prototype.indexOf == "function")
106 return Array.prototype.indexOf.call(array, item);
107 for (var i = 0, j = array.length; i < j; i++)
108 if (array[i] === item)
109 return i;
110 return -1;
111 },
112
113 arrayFirst: function (array, predicate, predicateOwner) {
114 for (var i = 0, j = array.length; i < j; i++)
115 if (predicate.call(predicateOwner, array[i]))
116 return array[i];
117 return null;
118 },
119
120 arrayRemoveItem: function (array, itemToRemove) {
121 var index = ko.utils.arrayIndexOf(array, itemToRemove);
122 if (index >= 0)
123 array.splice(index, 1);
124 },
125
126 arrayGetDistinctValues: function (array) {
127 array = array || [];
128 var result = [];
129 for (var i = 0, j = array.length; i < j; i++) {
130 if (ko.utils.arrayIndexOf(result, array[i]) < 0)
131 result.push(array[i]);
132 }
133 return result;
134 },
135
136 arrayMap: function (array, mapping) {
137 array = array || [];
138 var result = [];
139 for (var i = 0, j = array.length; i < j; i++)
140 result.push(mapping(array[i]));
141 return result;
142 },
143
144 arrayFilter: function (array, predicate) {
145 array = array || [];
146 var result = [];
147 for (var i = 0, j = array.length; i < j; i++)
148 if (predicate(array[i]))
149 result.push(array[i]);
150 return result;
151 },
152
153 arrayPushAll: function (array, valuesToPush) {
154 if (valuesToPush instanceof Array)
155 array.push.apply(array, valuesToPush);
156 else
157 for (var i = 0, j = valuesToPush.length; i < j; i++)
158 array.push(valuesToPush[i]);
159 return array;
160 },
161
162 addOrRemoveItem: function(array, value, included) {
163 var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.peekObservable(array), value);
164 if (existingEntryIndex < 0) {
165 if (included)
166 array.push(value);
167 } else {
168 if (!included)
169 array.splice(existingEntryIndex, 1);
170 }
171 },
172
173 extend: function (target, source) {
174 if (source) {
175 for(var prop in source) {
176 if(source.hasOwnProperty(prop)) {
177 target[prop] = source[prop];
178 }
179 }
180 }
181 return target;
182 },
183
184 objectForEach: objectForEach,
185
186 objectMap: function(source, mapping) {
187 if (!source)
188 return source;
189 var target = {};
190 for (var prop in source) {
191 if (source.hasOwnProperty(prop)) {
192 target[prop] = mapping(source[prop], prop, source);
193 }
194 }
195 return target;
196 },
197
198 emptyDomNode: function (domNode) {
199 while (domNode.firstChild) {
200 ko.removeNode(domNode.firstChild);
201 }
202 },
203
204 moveCleanedNodesToContainerElement: function(nodes) {
205 // Ensure it's a real array, as we're about to reparent the nodes and
206 // we don't want the underlying collection to change while we're doing that.
207 var nodesArray = ko.utils.makeArray(nodes);
208
209 var container = document.createElement('div');
210 for (var i = 0, j = nodesArray.length; i < j; i++) {
211 container.appendChild(ko.cleanNode(nodesArray[i]));
212 }
213 return container;
214 },
215
216 cloneNodes: function (nodesArray, shouldCleanNodes) {
217 for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
218 var clonedNode = nodesArray[i].cloneNode(true);
219 newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
220 }
221 return newNodesArray;
222 },
223
224 setDomNodeChildren: function (domNode, childNodes) {
225 ko.utils.emptyDomNode(domNode);
226 if (childNodes) {
227 for (var i = 0, j = childNodes.length; i < j; i++)
228 domNode.appendChild(childNodes[i]);
229 }
230 },
231
232 replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
233 var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
234 if (nodesToReplaceArray.length > 0) {
235 var insertionPoint = nodesToReplaceArray[0];
236 var parent = insertionPoint.parentNode;
237 for (var i = 0, j = newNodesArray.length; i < j; i++)
238 parent.insertBefore(newNodesArray[i], insertionPoint);
239 for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
240 ko.removeNode(nodesToReplaceArray[i]);
241 }
242 }
243 },
244
245 fixUpContinuousNodeArray: function(continuousNodeArray, parentNode) {
246 // Before acting on a set of nodes that were previously outputted by a template function, we have to reconcile
247 // them against what is in the DOM right now. It may be that some of the nodes have already been removed, or that
248 // new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
249 // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
250 // So, this function translates the old "map" output array into its best guess of the set of current DOM nodes.
251 //
252 // Rules:
253 // [A] Any leading nodes that have been removed should be ignored
254 // These most likely correspond to memoization nodes that were already removed during binding
255 // See https://github.com/SteveSanderson/knockout/pull/440
256 // [B] We want to output a continuous series of nodes. So, ignore any nodes that have already been removed,
257 // and include any nodes that have been inserted among the previous collection
258
259 if (continuousNodeArray.length) {
260 // The parent node can be a virtual element; so get the real parent node
261 parentNode = (parentNode.nodeType === 8 && parentNode.parentNode) || parentNode;
262
263 // Rule [A]
264 while (continuousNodeArray.length && continuousNodeArray[0].parentNode !== parentNode)
265 continuousNodeArray.splice(0, 1);
266
267 // Rule [B]
268 if (continuousNodeArray.length > 1) {
269 var current = continuousNodeArray[0], last = continuousNodeArray[continuousNodeArray.length - 1];
270 // Replace with the actual new continuous node set
271 continuousNodeArray.length = 0;
272 while (current !== last) {
273 continuousNodeArray.push(current);
274 current = current.nextSibling;
275 if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
276 return;
277 }
278 continuousNodeArray.push(last);
279 }
280 }
281 return continuousNodeArray;
282 },
283
284 setOptionNodeSelectionState: function (optionNode, isSelected) {
285 // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
286 if (ieVersion < 7)
287 optionNode.setAttribute("selected", isSelected);
288 else
289 optionNode.selected = isSelected;
290 },
291
292 stringTrim: function (string) {
293 return string === null || string === undefined ? '' :
294 string.trim ?
295 string.trim() :
296 string.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
297 },
298
299 stringTokenize: function (string, delimiter) {
300 var result = [];
301 var tokens = (string || "").split(delimiter);
302 for (var i = 0, j = tokens.length; i < j; i++) {
303 var trimmed = ko.utils.stringTrim(tokens[i]);
304 if (trimmed !== "")
305 result.push(trimmed);
306 }
307 return result;
308 },
309
310 stringStartsWith: function (string, startsWith) {
311 string = string || "";
312 if (startsWith.length > string.length)
313 return false;
314 return string.substring(0, startsWith.length) === startsWith;
315 },
316
317 domNodeIsContainedBy: function (node, containedByNode) {
318 if (node === containedByNode)
319 return true;
320 if (node.nodeType === 11)
321 return false; // Fixes issue #1162 - can't use node.contains for document fragments on IE8
322 if (containedByNode.contains)
323 return containedByNode.contains(node.nodeType === 3 ? node.parentNode : node);
324 if (containedByNode.compareDocumentPosition)
325 return (containedByNode.compareDocumentPosition(node) & 16) == 16;
326 while (node && node != containedByNode) {
327 node = node.parentNode;
328 }
329 return !!node;
330 },
331
332 domNodeIsAttachedToDocument: function (node) {
333 return ko.utils.domNodeIsContainedBy(node, node.ownerDocument.documentElement);
334 },
335
336 anyDomNodeIsAttachedToDocument: function(nodes) {
337 return !!ko.utils.arrayFirst(nodes, ko.utils.domNodeIsAttachedToDocument);
338 },
339
340 tagNameLower: function(element) {
341 // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
342 // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
343 // we don't need to do the .toLowerCase() as it will always be lower case anyway.
344 return element && element.tagName && element.tagName.toLowerCase();
345 },
346
347 registerEventHandler: function (element, eventType, handler) {
348 var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
349 if (!mustUseAttachEvent && typeof jQuery != "undefined") {
350 if (isClickOnCheckableElement(element, eventType)) {
351 // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
352 // it toggles the element checked state *after* the click event handlers run, whereas native
353 // click events toggle the checked state *before* the event handler.
354 // Fix this by intecepting the handler and applying the correct checkedness before it runs.
355 var originalHandler = handler;
356 handler = function(event, eventData) {
357 var jQuerySuppliedCheckedState = this.checked;
358 if (eventData)
359 this.checked = eventData.checkedStateBeforeEvent !== true;
360 originalHandler.call(this, event);
361 this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
362 };
363 }
364 jQuery(element)['bind'](eventType, handler);
365 } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
366 element.addEventListener(eventType, handler, false);
367 else if (typeof element.attachEvent != "undefined") {
368 var attachEventHandler = function (event) { handler.call(element, event); },
369 attachEventName = "on" + eventType;
370 element.attachEvent(attachEventName, attachEventHandler);
371
372 // IE does not dispose attachEvent handlers automatically (unlike with addEventListener)
373 // so to avoid leaks, we have to remove them manually. See bug #856
374 ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
375 element.detachEvent(attachEventName, attachEventHandler);
376 });
377 } else
378 throw new Error("Browser doesn't support addEventListener or attachEvent");
379 },
380
381 triggerEvent: function (element, eventType) {
382 if (!(element && element.nodeType))
383 throw new Error("element must be a DOM node when calling triggerEvent");
384
385 if (typeof jQuery != "undefined") {
386 var eventData = [];
387 if (isClickOnCheckableElement(element, eventType)) {
388 // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
389 eventData.push({ checkedStateBeforeEvent: element.checked });
390 }
391 jQuery(element)['trigger'](eventType, eventData);
392 } else if (typeof document.createEvent == "function") {
393 if (typeof element.dispatchEvent == "function") {
394 var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
395 var event = document.createEvent(eventCategory);
396 event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
397 element.dispatchEvent(event);
398 }
399 else
400 throw new Error("The supplied element doesn't support dispatchEvent");
401 } else if (typeof element.fireEvent != "undefined") {
402 // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
403 // so to make it consistent, we'll do it manually here
404 if (isClickOnCheckableElement(element, eventType))
405 element.checked = element.checked !== true;
406 element.fireEvent("on" + eventType);
407 }
408 else
409 throw new Error("Browser doesn't support triggering events");
410 },
411
412 unwrapObservable: function (value) {
413 return ko.isObservable(value) ? value() : value;
414 },
415
416 peekObservable: function (value) {
417 return ko.isObservable(value) ? value.peek() : value;
418 },
419
420 toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
421 if (classNames) {
422 var cssClassNameRegex = /\S+/g,
423 currentClassNames = node.className.match(cssClassNameRegex) || [];
424 ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
425 ko.utils.addOrRemoveItem(currentClassNames, className, shouldHaveClass);
426 });
427 node.className = currentClassNames.join(" ");
428 }
429 },
430
431 setTextContent: function(element, textContent) {
432 var value = ko.utils.unwrapObservable(textContent);
433 if ((value === null) || (value === undefined))
434 value = "";
435
436 // We need there to be exactly one child: a text node.
437 // If there are no children, more than one, or if it's not a text node,
438 // we'll clear everything and create a single text node.
439 var innerTextNode = ko.virtualElements.firstChild(element);
440 if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
441 ko.virtualElements.setDomNodeChildren(element, [document.createTextNode(value)]);
442 } else {
443 innerTextNode.data = value;
444 }
445
446 ko.utils.forceRefresh(element);
447 },
448
449 setElementName: function(element, name) {
450 element.name = name;
451
452 // Workaround IE 6/7 issue
453 // - https://github.com/SteveSanderson/knockout/issues/197
454 // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
455 if (ieVersion <= 7) {
456 try {
457 element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
458 }
459 catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
460 }
461 },
462
463 forceRefresh: function(node) {
464 // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
465 if (ieVersion >= 9) {
466 // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
467 var elem = node.nodeType == 1 ? node : node.parentNode;
468 if (elem.style)
469 elem.style.zoom = elem.style.zoom;
470 }
471 },
472
473 ensureSelectElementIsRenderedCorrectly: function(selectElement) {
474 // 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.
475 // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
476 // Also fixes IE7 and IE8 bug that causes selects to be zero width if enclosed by 'if' or 'with'. (See issue #839)
477 if (ieVersion) {
478 var originalWidth = selectElement.style.width;
479 selectElement.style.width = 0;
480 selectElement.style.width = originalWidth;
481 }
482 },
483
484 range: function (min, max) {
485 min = ko.utils.unwrapObservable(min);
486 max = ko.utils.unwrapObservable(max);
487 var result = [];
488 for (var i = min; i <= max; i++)
489 result.push(i);
490 return result;
491 },
492
493 makeArray: function(arrayLikeObject) {
494 var result = [];
495 for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
496 result.push(arrayLikeObject[i]);
497 };
498 return result;
499 },
500
501 isIe6 : isIe6,
502 isIe7 : isIe7,
503 ieVersion : ieVersion,
504
505 getFormFields: function(form, fieldName) {
506 var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
507 var isMatchingField = (typeof fieldName == 'string')
508 ? function(field) { return field.name === fieldName }
509 : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
510 var matches = [];
511 for (var i = fields.length - 1; i >= 0; i--) {
512 if (isMatchingField(fields[i]))
513 matches.push(fields[i]);
514 };
515 return matches;
516 },
517
518 parseJson: function (jsonString) {
519 if (typeof jsonString == "string") {
520 jsonString = ko.utils.stringTrim(jsonString);
521 if (jsonString) {
522 if (JSON && JSON.parse) // Use native parsing where available
523 return JSON.parse(jsonString);
524 return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
525 }
526 }
527 return null;
528 },
529
530 stringifyJson: function (data, replacer, space) { // replacer and space are optional
531 if (!JSON || !JSON.stringify)
532 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");
533 return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
534 },
535
536 postJson: function (urlOrForm, data, options) {
537 options = options || {};
538 var params = options['params'] || {};
539 var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
540 var url = urlOrForm;
541
542 // If we were given a form, use its 'action' URL and pick out any requested field values
543 if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
544 var originalForm = urlOrForm;
545 url = originalForm.action;
546 for (var i = includeFields.length - 1; i >= 0; i--) {
547 var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
548 for (var j = fields.length - 1; j >= 0; j--)
549 params[fields[j].name] = fields[j].value;
550 }
551 }
552
553 data = ko.utils.unwrapObservable(data);
554 var form = document.createElement("form");
555 form.style.display = "none";
556 form.action = url;
557 form.method = "post";
558 for (var key in data) {
559 // Since 'data' this is a model object, we include all properties including those inherited from its prototype
560 var input = document.createElement("input");
561 input.name = key;
562 input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
563 form.appendChild(input);
564 }
565 objectForEach(params, function(key, value) {
566 var input = document.createElement("input");
567 input.name = key;
568 input.value = value;
569 form.appendChild(input);
570 });
571 document.body.appendChild(form);
572 options['submitter'] ? options['submitter'](form) : form.submit();
573 setTimeout(function () { form.parentNode.removeChild(form); }, 0);
574 }
575 }
576 }());
577
578 ko.exportSymbol('utils', ko.utils);
579 ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
580 ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
581 ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
582 ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
583 ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
584 ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
585 ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
586 ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
587 ko.exportSymbol('utils.extend', ko.utils.extend);
588 ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
589 ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
590 ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
591 ko.exportSymbol('utils.postJson', ko.utils.postJson);
592 ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
593 ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
594 ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
595 ko.exportSymbol('utils.range', ko.utils.range);
596 ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
597 ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
598 ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
599 ko.exportSymbol('utils.objectForEach', ko.utils.objectForEach);
600 ko.exportSymbol('utils.addOrRemoveItem', ko.utils.addOrRemoveItem);
601 ko.exportSymbol('unwrap', ko.utils.unwrapObservable); // Convenient shorthand, because this is used so commonly
602
603 if (!Function.prototype['bind']) {
604 // 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)
605 // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
606 Function.prototype['bind'] = function (object) {
607 var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
608 return function () {
609 return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
610 };
611 };
612 }
613
614 ko.utils.domData = new (function () {
615 var uniqueId = 0;
616 var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
617 var dataStore = {};
618
619 function getAll(node, createIfNotFound) {
620 var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
621 var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
622 if (!hasExistingDataStore) {
623 if (!createIfNotFound)
624 return undefined;
625 dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
626 dataStore[dataStoreKey] = {};
627 }
628 return dataStore[dataStoreKey];
629 }
630
631 return {
632 get: function (node, key) {
633 var allDataForNode = getAll(node, false);
634 return allDataForNode === undefined ? undefined : allDataForNode[key];
635 },
636 set: function (node, key, value) {
637 if (value === undefined) {
638 // Make sure we don't actually create a new domData key if we are actually deleting a value
639 if (getAll(node, false) === undefined)
640 return;
641 }
642 var allDataForNode = getAll(node, true);
643 allDataForNode[key] = value;
644 },
645 clear: function (node) {
646 var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
647 if (dataStoreKey) {
648 delete dataStore[dataStoreKey];
649 node[dataStoreKeyExpandoPropertyName] = null;
650 return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
651 }
652 return false;
653 },
654
655 nextKey: function () {
656 return (uniqueId++) + dataStoreKeyExpandoPropertyName;
657 }
658 };
659 })();
660
661 ko.exportSymbol('utils.domData', ko.utils.domData);
662 ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
663
664 ko.utils.domNodeDisposal = new (function () {
665 var domDataKey = ko.utils.domData.nextKey();
666 var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
667 var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
668
669 function getDisposeCallbacksCollection(node, createIfNotFound) {
670 var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
671 if ((allDisposeCallbacks === undefined) && createIfNotFound) {
672 allDisposeCallbacks = [];
673 ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
674 }
675 return allDisposeCallbacks;
676 }
677 function destroyCallbacksCollection(node) {
678 ko.utils.domData.set(node, domDataKey, undefined);
679 }
680
681 function cleanSingleNode(node) {
682 // Run all the dispose callbacks
683 var callbacks = getDisposeCallbacksCollection(node, false);
684 if (callbacks) {
685 callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
686 for (var i = 0; i < callbacks.length; i++)
687 callbacks[i](node);
688 }
689
690 // Also erase the DOM data
691 ko.utils.domData.clear(node);
692
693 // Special support for jQuery here because it's so commonly used.
694 // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
695 // so notify it to tear down any resources associated with the node & descendants here.
696 if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
697 jQuery['cleanData']([node]);
698
699 // Also clear any immediate-child comment nodes, as these wouldn't have been found by
700 // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
701 if (cleanableNodeTypesWithDescendants[node.nodeType])
702 cleanImmediateCommentTypeChildren(node);
703 }
704
705 function cleanImmediateCommentTypeChildren(nodeWithChildren) {
706 var child, nextChild = nodeWithChildren.firstChild;
707 while (child = nextChild) {
708 nextChild = child.nextSibling;
709 if (child.nodeType === 8)
710 cleanSingleNode(child);
711 }
712 }
713
714 return {
715 addDisposeCallback : function(node, callback) {
716 if (typeof callback != "function")
717 throw new Error("Callback must be a function");
718 getDisposeCallbacksCollection(node, true).push(callback);
719 },
720
721 removeDisposeCallback : function(node, callback) {
722 var callbacksCollection = getDisposeCallbacksCollection(node, false);
723 if (callbacksCollection) {
724 ko.utils.arrayRemoveItem(callbacksCollection, callback);
725 if (callbacksCollection.length == 0)
726 destroyCallbacksCollection(node);
727 }
728 },
729
730 cleanNode : function(node) {
731 // First clean this node, where applicable
732 if (cleanableNodeTypes[node.nodeType]) {
733 cleanSingleNode(node);
734
735 // ... then its descendants, where applicable
736 if (cleanableNodeTypesWithDescendants[node.nodeType]) {
737 // Clone the descendants list in case it changes during iteration
738 var descendants = [];
739 ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
740 for (var i = 0, j = descendants.length; i < j; i++)
741 cleanSingleNode(descendants[i]);
742 }
743 }
744 return node;
745 },
746
747 removeNode : function(node) {
748 ko.cleanNode(node);
749 if (node.parentNode)
750 node.parentNode.removeChild(node);
751 }
752 }
753 })();
754 ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
755 ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
756 ko.exportSymbol('cleanNode', ko.cleanNode);
757 ko.exportSymbol('removeNode', ko.removeNode);
758 ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
759 ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
760 ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
761 (function () {
762 var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
763
764 function simpleHtmlParse(html) {
765 // Based on jQuery's "clean" function, but only accounting for table-related elements.
766 // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
767
768 // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
769 // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
770 // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
771 // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
772
773 // Trim whitespace, otherwise indexOf won't work as expected
774 var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
775
776 // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
777 var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
778 !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
779 (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
780 /* anything else */ [0, "", ""];
781
782 // Go to html and back, then peel off extra wrappers
783 // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
784 var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
785 if (typeof window['innerShiv'] == "function") {
786 div.appendChild(window['innerShiv'](markup));
787 } else {
788 div.innerHTML = markup;
789 }
790
791 // Move to the right depth
792 while (wrap[0]--)
793 div = div.lastChild;
794
795 return ko.utils.makeArray(div.lastChild.childNodes);
796 }
797
798 function jQueryHtmlParse(html) {
799 // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
800 if (jQuery['parseHTML']) {
801 return jQuery['parseHTML'](html) || []; // Ensure we always return an array and never null
802 } else {
803 // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
804 var elems = jQuery['clean']([html]);
805
806 // 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.
807 // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
808 // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
809 if (elems && elems[0]) {
810 // Find the top-most parent element that's a direct child of a document fragment
811 var elem = elems[0];
812 while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
813 elem = elem.parentNode;
814 // ... then detach it
815 if (elem.parentNode)
816 elem.parentNode.removeChild(elem);
817 }
818
819 return elems;
820 }
821 }
822
823 ko.utils.parseHtmlFragment = function(html) {
824 return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
825 : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
826 };
827
828 ko.utils.setHtml = function(node, html) {
829 ko.utils.emptyDomNode(node);
830
831 // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
832 html = ko.utils.unwrapObservable(html);
833
834 if ((html !== null) && (html !== undefined)) {
835 if (typeof html != 'string')
836 html = html.toString();
837
838 // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
839 // for example <tr> elements which are not normally allowed to exist on their own.
840 // If you've referenced jQuery we'll use that rather than duplicating its code.
841 if (typeof jQuery != 'undefined') {
842 jQuery(node)['html'](html);
843 } else {
844 // ... otherwise, use KO's own parsing logic.
845 var parsedNodes = ko.utils.parseHtmlFragment(html);
846 for (var i = 0; i < parsedNodes.length; i++)
847 node.appendChild(parsedNodes[i]);
848 }
849 }
850 };
851 })();
852
853 ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
854 ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
855
856 ko.memoization = (function () {
857 var memos = {};
858
859 function randomMax8HexChars() {
860 return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
861 }
862 function generateRandomId() {
863 return randomMax8HexChars() + randomMax8HexChars();
864 }
865 function findMemoNodes(rootNode, appendToArray) {
866 if (!rootNode)
867 return;
868 if (rootNode.nodeType == 8) {
869 var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
870 if (memoId != null)
871 appendToArray.push({ domNode: rootNode, memoId: memoId });
872 } else if (rootNode.nodeType == 1) {
873 for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
874 findMemoNodes(childNodes[i], appendToArray);
875 }
876 }
877
878 return {
879 memoize: function (callback) {
880 if (typeof callback != "function")
881 throw new Error("You can only pass a function to ko.memoization.memoize()");
882 var memoId = generateRandomId();
883 memos[memoId] = callback;
884 return "<!--[ko_memo:" + memoId + "]-->";
885 },
886
887 unmemoize: function (memoId, callbackParams) {
888 var callback = memos[memoId];
889 if (callback === undefined)
890 throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
891 try {
892 callback.apply(null, callbackParams || []);
893 return true;
894 }
895 finally { delete memos[memoId]; }
896 },
897
898 unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
899 var memos = [];
900 findMemoNodes(domNode, memos);
901 for (var i = 0, j = memos.length; i < j; i++) {
902 var node = memos[i].domNode;
903 var combinedParams = [node];
904 if (extraCallbackParamsArray)
905 ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
906 ko.memoization.unmemoize(memos[i].memoId, combinedParams);
907 node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
908 if (node.parentNode)
909 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)
910 }
911 },
912
913 parseMemoText: function (memoText) {
914 var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
915 return match ? match[1] : null;
916 }
917 };
918 })();
919
920 ko.exportSymbol('memoization', ko.memoization);
921 ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
922 ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
923 ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
924 ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
925 ko.extenders = {
926 'throttle': function(target, timeout) {
927 // Throttling means two things:
928
929 // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
930 // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
931 target['throttleEvaluation'] = timeout;
932
933 // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
934 // so the target cannot change value synchronously or faster than a certain rate
935 var writeTimeoutInstance = null;
936 return ko.dependentObservable({
937 'read': target,
938 'write': function(value) {
939 clearTimeout(writeTimeoutInstance);
940 writeTimeoutInstance = setTimeout(function() {
941 target(value);
942 }, timeout);
943 }
944 });
945 },
946
947 'notify': function(target, notifyWhen) {
948 target["equalityComparer"] = notifyWhen == "always" ?
949 null : // null equalityComparer means to always notify
950 valuesArePrimitiveAndEqual;
951 }
952 };
953
954 var primitiveTypes = { 'undefined':1, 'boolean':1, 'number':1, 'string':1 };
955 function valuesArePrimitiveAndEqual(a, b) {
956 var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
957 return oldValueIsPrimitive ? (a === b) : false;
958 }
959
960 function applyExtenders(requestedExtenders) {
961 var target = this;
962 if (requestedExtenders) {
963 ko.utils.objectForEach(requestedExtenders, function(key, value) {
964 var extenderHandler = ko.extenders[key];
965 if (typeof extenderHandler == 'function') {
966 target = extenderHandler(target, value) || target;
967 }
968 });
969 }
970 return target;
971 }
972
973 ko.exportSymbol('extenders', ko.extenders);
974
975 ko.subscription = function (target, callback, disposeCallback) {
976 this.target = target;
977 this.callback = callback;
978 this.disposeCallback = disposeCallback;
979 ko.exportProperty(this, 'dispose', this.dispose);
980 };
981 ko.subscription.prototype.dispose = function () {
982 this.isDisposed = true;
983 this.disposeCallback();
984 };
985
986 ko.subscribable = function () {
987 this._subscriptions = {};
988
989 ko.utils.extend(this, ko.subscribable['fn']);
990 ko.exportProperty(this, 'subscribe', this.subscribe);
991 ko.exportProperty(this, 'extend', this.extend);
992 ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
993 }
994
995 var defaultEvent = "change";
996
997 ko.subscribable['fn'] = {
998 subscribe: function (callback, callbackTarget, event) {
999 event = event || defaultEvent;
1000 var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
1001
1002 var subscription = new ko.subscription(this, boundCallback, function () {
1003 ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
1004 }.bind(this));
1005
1006 if (!this._subscriptions[event])
1007 this._subscriptions[event] = [];
1008 this._subscriptions[event].push(subscription);
1009 return subscription;
1010 },
1011
1012 "notifySubscribers": function (valueToNotify, event) {
1013 event = event || defaultEvent;
1014 if (this.hasSubscriptionsForEvent(event)) {
1015 try {
1016 ko.dependencyDetection.begin();
1017 for (var a = this._subscriptions[event].slice(0), i = 0, subscription; subscription = a[i]; ++i) {
1018 // In case a subscription was disposed during the arrayForEach cycle, check
1019 // for isDisposed on each subscription before invoking its callback
1020 if (subscription && (subscription.isDisposed !== true))
1021 subscription.callback(valueToNotify);
1022 }
1023 } finally {
1024 ko.dependencyDetection.end();
1025 }
1026 }
1027 },
1028
1029 hasSubscriptionsForEvent: function(event) {
1030 return this._subscriptions[event] && this._subscriptions[event].length;
1031 },
1032
1033 getSubscriptionsCount: function () {
1034 var total = 0;
1035 ko.utils.objectForEach(this._subscriptions, function(eventName, subscriptions) {
1036 total += subscriptions.length;
1037 });
1038 return total;
1039 },
1040
1041 extend: applyExtenders
1042 };
1043
1044
1045 ko.isSubscribable = function (instance) {
1046 return instance != null && typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
1047 };
1048
1049 ko.exportSymbol('subscribable', ko.subscribable);
1050 ko.exportSymbol('isSubscribable', ko.isSubscribable);
1051
1052 ko.dependencyDetection = (function () {
1053 var _frames = [];
1054
1055 return {
1056 begin: function (callback) {
1057 _frames.push(callback && { callback: callback, distinctDependencies:[] });
1058 },
1059
1060 end: function () {
1061 _frames.pop();
1062 },
1063
1064 registerDependency: function (subscribable) {
1065 if (!ko.isSubscribable(subscribable))
1066 throw new Error("Only subscribable things can act as dependencies");
1067 if (_frames.length > 0) {
1068 var topFrame = _frames[_frames.length - 1];
1069 if (!topFrame || ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
1070 return;
1071 topFrame.distinctDependencies.push(subscribable);
1072 topFrame.callback(subscribable);
1073 }
1074 },
1075
1076 ignore: function(callback, callbackTarget, callbackArgs) {
1077 try {
1078 _frames.push(null);
1079 return callback.apply(callbackTarget, callbackArgs || []);
1080 } finally {
1081 _frames.pop();
1082 }
1083 }
1084 };
1085 })();
1086 ko.observable = function (initialValue) {
1087 var _latestValue = initialValue;
1088
1089 function observable() {
1090 if (arguments.length > 0) {
1091 // Write
1092
1093 // Ignore writes if the value hasn't changed
1094 if (!observable['equalityComparer'] || !observable['equalityComparer'](_latestValue, arguments[0])) {
1095 observable.valueWillMutate();
1096 _latestValue = arguments[0];
1097 if (DEBUG) observable._latestValue = _latestValue;
1098 observable.valueHasMutated();
1099 }
1100 return this; // Permits chained assignments
1101 }
1102 else {
1103 // Read
1104 ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
1105 return _latestValue;
1106 }
1107 }
1108 if (DEBUG) observable._latestValue = _latestValue;
1109 ko.subscribable.call(observable);
1110 observable.peek = function() { return _latestValue };
1111 observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
1112 observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
1113 ko.utils.extend(observable, ko.observable['fn']);
1114
1115 ko.exportProperty(observable, 'peek', observable.peek);
1116 ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
1117 ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
1118
1119 return observable;
1120 }
1121
1122 ko.observable['fn'] = {
1123 "equalityComparer": valuesArePrimitiveAndEqual
1124 };
1125
1126 var protoProperty = ko.observable.protoProperty = "__ko_proto__";
1127 ko.observable['fn'][protoProperty] = ko.observable;
1128
1129 ko.hasPrototype = function(instance, prototype) {
1130 if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
1131 if (instance[protoProperty] === prototype) return true;
1132 return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
1133 };
1134
1135 ko.isObservable = function (instance) {
1136 return ko.hasPrototype(instance, ko.observable);
1137 }
1138 ko.isWriteableObservable = function (instance) {
1139 // Observable
1140 if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
1141 return true;
1142 // Writeable dependent observable
1143 if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
1144 return true;
1145 // Anything else
1146 return false;
1147 }
1148
1149
1150 ko.exportSymbol('observable', ko.observable);
1151 ko.exportSymbol('isObservable', ko.isObservable);
1152 ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
1153 ko.observableArray = function (initialValues) {
1154 initialValues = initialValues || [];
1155
1156 if (typeof initialValues != 'object' || !('length' in initialValues))
1157 throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
1158
1159 var result = ko.observable(initialValues);
1160 ko.utils.extend(result, ko.observableArray['fn']);
1161 return result.extend({'trackArrayChanges':true});
1162 };
1163
1164 ko.observableArray['fn'] = {
1165 'remove': function (valueOrPredicate) {
1166 var underlyingArray = this.peek();
1167 var removedValues = [];
1168 var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
1169 for (var i = 0; i < underlyingArray.length; i++) {
1170 var value = underlyingArray[i];
1171 if (predicate(value)) {
1172 if (removedValues.length === 0) {
1173 this.valueWillMutate();
1174 }
1175 removedValues.push(value);
1176 underlyingArray.splice(i, 1);
1177 i--;
1178 }
1179 }
1180 if (removedValues.length) {
1181 this.valueHasMutated();
1182 }
1183 return removedValues;
1184 },
1185
1186 'removeAll': function (arrayOfValues) {
1187 // If you passed zero args, we remove everything
1188 if (arrayOfValues === undefined) {
1189 var underlyingArray = this.peek();
1190 var allValues = underlyingArray.slice(0);
1191 this.valueWillMutate();
1192 underlyingArray.splice(0, underlyingArray.length);
1193 this.valueHasMutated();
1194 return allValues;
1195 }
1196 // If you passed an arg, we interpret it as an array of entries to remove
1197 if (!arrayOfValues)
1198 return [];
1199 return this['remove'](function (value) {
1200 return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
1201 });
1202 },
1203
1204 'destroy': function (valueOrPredicate) {
1205 var underlyingArray = this.peek();
1206 var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
1207 this.valueWillMutate();
1208 for (var i = underlyingArray.length - 1; i >= 0; i--) {
1209 var value = underlyingArray[i];
1210 if (predicate(value))
1211 underlyingArray[i]["_destroy"] = true;
1212 }
1213 this.valueHasMutated();
1214 },
1215
1216 'destroyAll': function (arrayOfValues) {
1217 // If you passed zero args, we destroy everything
1218 if (arrayOfValues === undefined)
1219 return this['destroy'](function() { return true });
1220
1221 // If you passed an arg, we interpret it as an array of entries to destroy
1222 if (!arrayOfValues)
1223 return [];
1224 return this['destroy'](function (value) {
1225 return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
1226 });
1227 },
1228
1229 'indexOf': function (item) {
1230 var underlyingArray = this();
1231 return ko.utils.arrayIndexOf(underlyingArray, item);
1232 },
1233
1234 'replace': function(oldItem, newItem) {
1235 var index = this['indexOf'](oldItem);
1236 if (index >= 0) {
1237 this.valueWillMutate();
1238 this.peek()[index] = newItem;
1239 this.valueHasMutated();
1240 }
1241 }
1242 };
1243
1244 // Populate ko.observableArray.fn with read/write functions from native arrays
1245 // Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
1246 // because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
1247 ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
1248 ko.observableArray['fn'][methodName] = function () {
1249 // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
1250 // (for consistency with mutating regular observables)
1251 var underlyingArray = this.peek();
1252 this.valueWillMutate();
1253 this.cacheDiffForKnownOperation(underlyingArray, methodName, arguments);
1254 var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
1255 this.valueHasMutated();
1256 return methodCallResult;
1257 };
1258 });
1259
1260 // Populate ko.observableArray.fn with read-only functions from native arrays
1261 ko.utils.arrayForEach(["slice"], function (methodName) {
1262 ko.observableArray['fn'][methodName] = function () {
1263 var underlyingArray = this();
1264 return underlyingArray[methodName].apply(underlyingArray, arguments);
1265 };
1266 });
1267
1268 ko.exportSymbol('observableArray', ko.observableArray);
1269 var arrayChangeEventName = 'arrayChange';
1270 ko.extenders['trackArrayChanges'] = function(target) {
1271 // Only modify the target observable once
1272 if (target.cacheDiffForKnownOperation) {
1273 return;
1274 }
1275 var trackingChanges = false,
1276 cachedDiff = null,
1277 pendingNotifications = 0,
1278 underlyingSubscribeFunction = target.subscribe;
1279
1280 // Intercept "subscribe" calls, and for array change events, ensure change tracking is enabled
1281 target.subscribe = target['subscribe'] = function(callback, callbackTarget, event) {
1282 if (event === arrayChangeEventName) {
1283 trackChanges();
1284 }
1285 return underlyingSubscribeFunction.apply(this, arguments);
1286 };
1287
1288 function trackChanges() {
1289 // Calling 'trackChanges' multiple times is the same as calling it once
1290 if (trackingChanges) {
1291 return;
1292 }
1293
1294 trackingChanges = true;
1295
1296 // Intercept "notifySubscribers" to track how many times it was called.
1297 var underlyingNotifySubscribersFunction = target['notifySubscribers'];
1298 target['notifySubscribers'] = function(valueToNotify, event) {
1299 if (!event || event === defaultEvent) {
1300 ++pendingNotifications;
1301 }
1302 return underlyingNotifySubscribersFunction.apply(this, arguments);
1303 };
1304
1305 // Each time the array changes value, capture a clone so that on the next
1306 // change it's possible to produce a diff
1307 var previousContents = [].concat(target.peek() || []);
1308 cachedDiff = null;
1309 target.subscribe(function(currentContents) {
1310 // Make a copy of the current contents and ensure it's an array
1311 currentContents = [].concat(currentContents || []);
1312
1313 // Compute the diff and issue notifications, but only if someone is listening
1314 if (target.hasSubscriptionsForEvent(arrayChangeEventName)) {
1315 var changes = getChanges(previousContents, currentContents);
1316 if (changes.length) {
1317 target['notifySubscribers'](changes, arrayChangeEventName);
1318 }
1319 }
1320
1321 // Eliminate references to the old, removed items, so they can be GCed
1322 previousContents = currentContents;
1323 cachedDiff = null;
1324 pendingNotifications = 0;
1325 });
1326 }
1327
1328 function getChanges(previousContents, currentContents) {
1329 // We try to re-use cached diffs.
1330 // The only scenario where pendingNotifications > 1 is when using the KO 'deferred updates' plugin,
1331 // which without this check would not be compatible with arrayChange notifications. Without that
1332 // plugin, notifications are always issued immediately so we wouldn't be queueing up more than one.
1333 if (!cachedDiff || pendingNotifications > 1) {
1334 cachedDiff = ko.utils.compareArrays(previousContents, currentContents, { 'sparse': true });
1335 }
1336
1337 return cachedDiff;
1338 }
1339
1340 target.cacheDiffForKnownOperation = function(rawArray, operationName, args) {
1341 // Only run if we're currently tracking changes for this observable array
1342 // and there aren't any pending deferred notifications.
1343 if (!trackingChanges || pendingNotifications) {
1344 return;
1345 }
1346 var diff = [],
1347 arrayLength = rawArray.length,
1348 argsLength = args.length,
1349 offset = 0;
1350
1351 function pushDiff(status, value, index) {
1352 diff.push({ 'status': status, 'value': value, 'index': index });
1353 }
1354 switch (operationName) {
1355 case 'push':
1356 offset = arrayLength;
1357 case 'unshift':
1358 for (var index = 0; index < argsLength; index++) {
1359 pushDiff('added', args[index], offset + index);
1360 }
1361 break;
1362
1363 case 'pop':
1364 offset = arrayLength - 1;
1365 case 'shift':
1366 if (arrayLength) {
1367 pushDiff('deleted', rawArray[offset], offset);
1368 }
1369 break;
1370
1371 case 'splice':
1372 // Negative start index means 'from end of array'. After that we clamp to [0...arrayLength].
1373 // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
1374 var startIndex = Math.min(Math.max(0, args[0] < 0 ? arrayLength + args[0] : args[0]), arrayLength),
1375 endDeleteIndex = argsLength === 1 ? arrayLength : Math.min(startIndex + (args[1] || 0), arrayLength),
1376 endAddIndex = startIndex + argsLength - 2,
1377 endIndex = Math.max(endDeleteIndex, endAddIndex);
1378 for (var index = startIndex, argsIndex = 2; index < endIndex; ++index, ++argsIndex) {
1379 if (index < endDeleteIndex)
1380 pushDiff('deleted', rawArray[index], index);
1381 if (index < endAddIndex)
1382 pushDiff('added', args[argsIndex], index);
1383 }
1384 break;
1385
1386 default:
1387 return;
1388 }
1389 cachedDiff = diff;
1390 };
1391 };
1392 ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
1393 var _latestValue,
1394 _hasBeenEvaluated = false,
1395 _isBeingEvaluated = false,
1396 _suppressDisposalUntilDisposeWhenReturnsFalse = false,
1397 readFunction = evaluatorFunctionOrOptions;
1398
1399 if (readFunction && typeof readFunction == "object") {
1400 // Single-parameter syntax - everything is on this "options" param
1401 options = readFunction;
1402 readFunction = options["read"];
1403 } else {
1404 // Multi-parameter syntax - construct the options according to the params passed
1405 options = options || {};
1406 if (!readFunction)
1407 readFunction = options["read"];
1408 }
1409 if (typeof readFunction != "function")
1410 throw new Error("Pass a function that returns the value of the ko.computed");
1411
1412 function addSubscriptionToDependency(subscribable) {
1413 _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync));
1414 }
1415
1416 function disposeAllSubscriptionsToDependencies() {
1417 ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
1418 subscription.dispose();
1419 });
1420 _subscriptionsToDependencies = [];
1421 }
1422
1423 function evaluatePossiblyAsync() {
1424 var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
1425 if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
1426 clearTimeout(evaluationTimeoutInstance);
1427 evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
1428 } else
1429 evaluateImmediate();
1430 }
1431
1432 function evaluateImmediate() {
1433 if (_isBeingEvaluated) {
1434 // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
1435 // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
1436 // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
1437 // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
1438 return;
1439 }
1440
1441 if (disposeWhen && disposeWhen()) {
1442 // See comment below about _suppressDisposalUntilDisposeWhenReturnsFalse
1443 if (!_suppressDisposalUntilDisposeWhenReturnsFalse) {
1444 dispose();
1445 _hasBeenEvaluated = true;
1446 return;
1447 }
1448 } else {
1449 // It just did return false, so we can stop suppressing now
1450 _suppressDisposalUntilDisposeWhenReturnsFalse = false;
1451 }
1452
1453 _isBeingEvaluated = true;
1454 try {
1455 // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
1456 // Then, during evaluation, we cross off any that are in fact still being used.
1457 var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
1458
1459 ko.dependencyDetection.begin(function(subscribable) {
1460 var inOld;
1461 if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
1462 disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
1463 else
1464 addSubscriptionToDependency(subscribable); // Brand new subscription - add it
1465 });
1466
1467 var newValue = evaluatorFunctionTarget ? readFunction.call(evaluatorFunctionTarget) : readFunction();
1468
1469 // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
1470 for (var i = disposalCandidates.length - 1; i >= 0; i--) {
1471 if (disposalCandidates[i])
1472 _subscriptionsToDependencies.splice(i, 1)[0].dispose();
1473 }
1474 _hasBeenEvaluated = true;
1475
1476 if (!dependentObservable['equalityComparer'] || !dependentObservable['equalityComparer'](_latestValue, newValue)) {
1477 dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
1478
1479 _latestValue = newValue;
1480 if (DEBUG) dependentObservable._latestValue = _latestValue;
1481 dependentObservable["notifySubscribers"](_latestValue);
1482 }
1483 } finally {
1484 ko.dependencyDetection.end();
1485 _isBeingEvaluated = false;
1486 }
1487
1488 if (!_subscriptionsToDependencies.length)
1489 dispose();
1490 }
1491
1492 function dependentObservable() {
1493 if (arguments.length > 0) {
1494 if (typeof writeFunction === "function") {
1495 // Writing a value
1496 writeFunction.apply(evaluatorFunctionTarget, arguments);
1497 } else {
1498 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.");
1499 }
1500 return this; // Permits chained assignments
1501 } else {
1502 // Reading the value
1503 if (!_hasBeenEvaluated)
1504 evaluateImmediate();
1505 ko.dependencyDetection.registerDependency(dependentObservable);
1506 return _latestValue;
1507 }
1508 }
1509
1510 function peek() {
1511 if (!_hasBeenEvaluated)
1512 evaluateImmediate();
1513 return _latestValue;
1514 }
1515
1516 function isActive() {
1517 return !_hasBeenEvaluated || _subscriptionsToDependencies.length > 0;
1518 }
1519
1520 // By here, "options" is always non-null
1521 var writeFunction = options["write"],
1522 disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
1523 disposeWhenOption = options["disposeWhen"] || options.disposeWhen,
1524 disposeWhen = disposeWhenOption,
1525 dispose = disposeAllSubscriptionsToDependencies,
1526 _subscriptionsToDependencies = [],
1527 evaluationTimeoutInstance = null;
1528
1529 if (!evaluatorFunctionTarget)
1530 evaluatorFunctionTarget = options["owner"];
1531
1532 dependentObservable.peek = peek;
1533 dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
1534 dependentObservable.hasWriteFunction = typeof options["write"] === "function";
1535 dependentObservable.dispose = function () { dispose(); };
1536 dependentObservable.isActive = isActive;
1537
1538 ko.subscribable.call(dependentObservable);
1539 ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
1540
1541 ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
1542 ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
1543 ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
1544 ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
1545
1546 // Add a "disposeWhen" callback that, on each evaluation, disposes if the node was removed without using ko.removeNode.
1547 if (disposeWhenNodeIsRemoved) {
1548 // Since this computed is associated with a DOM node, and we don't want to dispose the computed
1549 // until the DOM node is *removed* from the document (as opposed to never having been in the document),
1550 // we'll prevent disposal until "disposeWhen" first returns false.
1551 _suppressDisposalUntilDisposeWhenReturnsFalse = true;
1552
1553 // Only watch for the node's disposal if the value really is a node. It might not be,
1554 // e.g., { disposeWhenNodeIsRemoved: true } can be used to opt into the "only dispose
1555 // after first false result" behaviour even if there's no specific node to watch. This
1556 // technique is intended for KO's internal use only and shouldn't be documented or used
1557 // by application code, as it's likely to change in a future version of KO.
1558 if (disposeWhenNodeIsRemoved.nodeType) {
1559 disposeWhen = function () {
1560 return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || (disposeWhenOption && disposeWhenOption());
1561 };
1562 }
1563 }
1564
1565 // Evaluate, unless deferEvaluation is true
1566 if (options['deferEvaluation'] !== true)
1567 evaluateImmediate();
1568
1569 // Attach a DOM node disposal callback so that the computed will be proactively disposed as soon as the node is
1570 // removed using ko.removeNode. But skip if isActive is false (there will never be any dependencies to dispose).
1571 if (disposeWhenNodeIsRemoved && isActive()) {
1572 dispose = function() {
1573 ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, dispose);
1574 disposeAllSubscriptionsToDependencies();
1575 };
1576 ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
1577 }
1578
1579 return dependentObservable;
1580 };
1581
1582 ko.isComputed = function(instance) {
1583 return ko.hasPrototype(instance, ko.dependentObservable);
1584 };
1585
1586 var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
1587 ko.dependentObservable[protoProp] = ko.observable;
1588
1589 ko.dependentObservable['fn'] = {
1590 "equalityComparer": valuesArePrimitiveAndEqual
1591 };
1592 ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
1593
1594 ko.exportSymbol('dependentObservable', ko.dependentObservable);
1595 ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
1596 ko.exportSymbol('isComputed', ko.isComputed);
1597
1598 (function() {
1599 var maxNestedObservableDepth = 10; // Escape the (unlikely) pathological case where an observable's current value is itself (or similar reference cycle)
1600
1601 ko.toJS = function(rootObject) {
1602 if (arguments.length == 0)
1603 throw new Error("When calling ko.toJS, pass the object you want to convert.");
1604
1605 // We just unwrap everything at every level in the object graph
1606 return mapJsObjectGraph(rootObject, function(valueToMap) {
1607 // Loop because an observable's value might in turn be another observable wrapper
1608 for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
1609 valueToMap = valueToMap();
1610 return valueToMap;
1611 });
1612 };
1613
1614 ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
1615 var plainJavaScriptObject = ko.toJS(rootObject);
1616 return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
1617 };
1618
1619 function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
1620 visitedObjects = visitedObjects || new objectLookup();
1621
1622 rootObject = mapInputCallback(rootObject);
1623 var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date)) && (!(rootObject instanceof String)) && (!(rootObject instanceof Number)) && (!(rootObject instanceof Boolean));
1624 if (!canHaveProperties)
1625 return rootObject;
1626
1627 var outputProperties = rootObject instanceof Array ? [] : {};
1628 visitedObjects.save(rootObject, outputProperties);
1629
1630 visitPropertiesOrArrayEntries(rootObject, function(indexer) {
1631 var propertyValue = mapInputCallback(rootObject[indexer]);
1632
1633 switch (typeof propertyValue) {
1634 case "boolean":
1635 case "number":
1636 case "string":
1637 case "function":
1638 outputProperties[indexer] = propertyValue;
1639 break;
1640 case "object":
1641 case "undefined":
1642 var previouslyMappedValue = visitedObjects.get(propertyValue);
1643 outputProperties[indexer] = (previouslyMappedValue !== undefined)
1644 ? previouslyMappedValue
1645 : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
1646 break;
1647 }
1648 });
1649
1650 return outputProperties;
1651 }
1652
1653 function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
1654 if (rootObject instanceof Array) {
1655 for (var i = 0; i < rootObject.length; i++)
1656 visitorCallback(i);
1657
1658 // For arrays, also respect toJSON property for custom mappings (fixes #278)
1659 if (typeof rootObject['toJSON'] == 'function')
1660 visitorCallback('toJSON');
1661 } else {
1662 for (var propertyName in rootObject) {
1663 visitorCallback(propertyName);
1664 }
1665 }
1666 };
1667
1668 function objectLookup() {
1669 this.keys = [];
1670 this.values = [];
1671 };
1672
1673 objectLookup.prototype = {
1674 constructor: objectLookup,
1675 save: function(key, value) {
1676 var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
1677 if (existingIndex >= 0)
1678 this.values[existingIndex] = value;
1679 else {
1680 this.keys.push(key);
1681 this.values.push(value);
1682 }
1683 },
1684 get: function(key) {
1685 var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
1686 return (existingIndex >= 0) ? this.values[existingIndex] : undefined;
1687 }
1688 };
1689 })();
1690
1691 ko.exportSymbol('toJS', ko.toJS);
1692 ko.exportSymbol('toJSON', ko.toJSON);
1693 (function () {
1694 var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
1695
1696 // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
1697 // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
1698 // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
1699 ko.selectExtensions = {
1700 readValue : function(element) {
1701 switch (ko.utils.tagNameLower(element)) {
1702 case 'option':
1703 if (element[hasDomDataExpandoProperty] === true)
1704 return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
1705 return ko.utils.ieVersion <= 7
1706 ? (element.getAttributeNode('value') && element.getAttributeNode('value').specified ? element.value : element.text)
1707 : element.value;
1708 case 'select':
1709 return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
1710 default:
1711 return element.value;
1712 }
1713 },
1714
1715 writeValue: function(element, value) {
1716 switch (ko.utils.tagNameLower(element)) {
1717 case 'option':
1718 switch(typeof value) {
1719 case "string":
1720 ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
1721 if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
1722 delete element[hasDomDataExpandoProperty];
1723 }
1724 element.value = value;
1725 break;
1726 default:
1727 // Store arbitrary object using DomData
1728 ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
1729 element[hasDomDataExpandoProperty] = true;
1730
1731 // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
1732 element.value = typeof value === "number" ? value : "";
1733 break;
1734 }
1735 break;
1736 case 'select':
1737 if (value === "")
1738 value = undefined;
1739 if (value === null || value === undefined)
1740 element.selectedIndex = -1;
1741 for (var i = element.options.length - 1; i >= 0; i--) {
1742 if (ko.selectExtensions.readValue(element.options[i]) == value) {
1743 element.selectedIndex = i;
1744 break;
1745 }
1746 }
1747 // for drop-down select, ensure first is selected
1748 if (!(element.size > 1) && element.selectedIndex === -1) {
1749 element.selectedIndex = 0;
1750 }
1751 break;
1752 default:
1753 if ((value === null) || (value === undefined))
1754 value = "";
1755 element.value = value;
1756 break;
1757 }
1758 }
1759 };
1760 })();
1761
1762 ko.exportSymbol('selectExtensions', ko.selectExtensions);
1763 ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
1764 ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
1765 ko.expressionRewriting = (function () {
1766 var javaScriptReservedWords = ["true", "false", "null", "undefined"];
1767
1768 // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
1769 // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
1770 // This also will not properly handle nested brackets (e.g., obj1[obj2['prop']]; see #911).
1771 var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
1772
1773 function getWriteableValue(expression) {
1774 if (ko.utils.arrayIndexOf(javaScriptReservedWords, expression) >= 0)
1775 return false;
1776 var match = expression.match(javaScriptAssignmentTarget);
1777 return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
1778 }
1779
1780 // The following regular expressions will be used to split an object-literal string into tokens
1781
1782 // These two match strings, either with double quotes or single quotes
1783 var stringDouble = '"(?:[^"\\\\]|\\\\.)*"',
1784 stringSingle = "'(?:[^'\\\\]|\\\\.)*'",
1785 // Matches a regular expression (text enclosed by slashes), but will also match sets of divisions
1786 // as a regular expression (this is handled by the parsing loop below).
1787 stringRegexp = '/(?:[^/\\\\]|\\\\.)*/\w*',
1788 // These characters have special meaning to the parser and must not appear in the middle of a
1789 // token, except as part of a string.
1790 specials = ',"\'{}()/:[\\]',
1791 // Match text (at least two characters) that does not contain any of the above special characters,
1792 // although some of the special characters are allowed to start it (all but the colon and comma).
1793 // The text can contain spaces, but leading or trailing spaces are skipped.
1794 everyThingElse = '[^\\s:,/][^' + specials + ']*[^\\s' + specials + ']',
1795 // Match any non-space character not matched already. This will match colons and commas, since they're
1796 // not matched by "everyThingElse", but will also match any other single character that wasn't already
1797 // matched (for example: in "a: 1, b: 2", each of the non-space characters will be matched by oneNotSpace).
1798 oneNotSpace = '[^\\s]',
1799
1800 // Create the actual regular expression by or-ing the above strings. The order is important.
1801 bindingToken = RegExp(stringDouble + '|' + stringSingle + '|' + stringRegexp + '|' + everyThingElse + '|' + oneNotSpace, 'g'),
1802
1803 // Match end of previous token to determine whether a slash is a division or regex.
1804 divisionLookBehind = /[\])"'A-Za-z0-9_$]+$/,
1805 keywordRegexLookBehind = {'in':1,'return':1,'typeof':1};
1806
1807 function parseObjectLiteral(objectLiteralString) {
1808 // Trim leading and trailing spaces from the string
1809 var str = ko.utils.stringTrim(objectLiteralString);
1810
1811 // Trim braces '{' surrounding the whole object literal
1812 if (str.charCodeAt(0) === 123) str = str.slice(1, -1);
1813
1814 // Split into tokens
1815 var result = [], toks = str.match(bindingToken), key, values, depth = 0;
1816
1817 if (toks) {
1818 // Append a comma so that we don't need a separate code block to deal with the last item
1819 toks.push(',');
1820
1821 for (var i = 0, tok; tok = toks[i]; ++i) {
1822 var c = tok.charCodeAt(0);
1823 // A comma signals the end of a key/value pair if depth is zero
1824 if (c === 44) { // ","
1825 if (depth <= 0) {
1826 if (key)
1827 result.push(values ? {key: key, value: values.join('')} : {'unknown': key});
1828 key = values = depth = 0;
1829 continue;
1830 }
1831 // Simply skip the colon that separates the name and value
1832 } else if (c === 58) { // ":"
1833 if (!values)
1834 continue;
1835 // A set of slashes is initially matched as a regular expression, but could be division
1836 } else if (c === 47 && i && tok.length > 1) { // "/"
1837 // Look at the end of the previous token to determine if the slash is actually division
1838 var match = toks[i-1].match(divisionLookBehind);
1839 if (match && !keywordRegexLookBehind[match[0]]) {
1840 // The slash is actually a division punctuator; re-parse the remainder of the string (not including the slash)
1841 str = str.substr(str.indexOf(tok) + 1);
1842 toks = str.match(bindingToken);
1843 toks.push(',');
1844 i = -1;
1845 // Continue with just the slash
1846 tok = '/';
1847 }
1848 // Increment depth for parentheses, braces, and brackets so that interior commas are ignored
1849 } else if (c === 40 || c === 123 || c === 91) { // '(', '{', '['
1850 ++depth;
1851 } else if (c === 41 || c === 125 || c === 93) { // ')', '}', ']'
1852 --depth;
1853 // The key must be a single token; if it's a string, trim the quotes
1854 } else if (!key && !values) {
1855 key = (c === 34 || c === 39) /* '"', "'" */ ? tok.slice(1, -1) : tok;
1856 continue;
1857 }
1858 if (values)
1859 values.push(tok);
1860 else
1861 values = [tok];
1862 }
1863 }
1864 return result;
1865 }
1866
1867 // Two-way bindings include a write function that allow the handler to update the value even if it's not an observable.
1868 var twoWayBindings = {};
1869
1870 function preProcessBindings(bindingsStringOrKeyValueArray, bindingOptions) {
1871 bindingOptions = bindingOptions || {};
1872
1873 function processKeyValue(key, val) {
1874 var writableVal;
1875 function callPreprocessHook(obj) {
1876 return (obj && obj['preprocess']) ? (val = obj['preprocess'](val, key, processKeyValue)) : true;
1877 }
1878 if (!callPreprocessHook(ko['getBindingHandler'](key)))
1879 return;
1880
1881 if (twoWayBindings[key] && (writableVal = getWriteableValue(val))) {
1882 // For two-way bindings, provide a write method in case the value
1883 // isn't a writable observable.
1884 propertyAccessorResultStrings.push("'" + key + "':function(_z){" + writableVal + "=_z}");
1885 }
1886
1887 // Values are wrapped in a function so that each value can be accessed independently
1888 if (makeValueAccessors) {
1889 val = 'function(){return ' + val + ' }';
1890 }
1891 resultStrings.push("'" + key + "':" + val);
1892 }
1893
1894 var resultStrings = [],
1895 propertyAccessorResultStrings = [],
1896 makeValueAccessors = bindingOptions['valueAccessors'],
1897 keyValueArray = typeof bindingsStringOrKeyValueArray === "string" ?
1898 parseObjectLiteral(bindingsStringOrKeyValueArray) : bindingsStringOrKeyValueArray;
1899
1900 ko.utils.arrayForEach(keyValueArray, function(keyValue) {
1901 processKeyValue(keyValue.key || keyValue['unknown'], keyValue.value);
1902 });
1903
1904 if (propertyAccessorResultStrings.length)
1905 processKeyValue('_ko_property_writers', "{" + propertyAccessorResultStrings.join(",") + "}");
1906
1907 return resultStrings.join(",");
1908 }
1909
1910 return {
1911 bindingRewriteValidators: [],
1912
1913 twoWayBindings: twoWayBindings,
1914
1915 parseObjectLiteral: parseObjectLiteral,
1916
1917 preProcessBindings: preProcessBindings,
1918
1919 keyValueArrayContainsKey: function(keyValueArray, key) {
1920 for (var i = 0; i < keyValueArray.length; i++)
1921 if (keyValueArray[i]['key'] == key)
1922 return true;
1923 return false;
1924 },
1925
1926 // Internal, private KO utility for updating model properties from within bindings
1927 // property: If the property being updated is (or might be) an observable, pass it here
1928 // If it turns out to be a writable observable, it will be written to directly
1929 // allBindings: An object with a get method to retrieve bindings in the current execution context.
1930 // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
1931 // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
1932 // value: The value to be written
1933 // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
1934 // it is !== existing value on that writable observable
1935 writeValueToProperty: function(property, allBindings, key, value, checkIfDifferent) {
1936 if (!property || !ko.isObservable(property)) {
1937 var propWriters = allBindings.get('_ko_property_writers');
1938 if (propWriters && propWriters[key])
1939 propWriters[key](value);
1940 } else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {
1941 property(value);
1942 }
1943 }
1944 };
1945 })();
1946
1947 ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
1948 ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
1949 ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
1950 ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
1951
1952 // Making bindings explicitly declare themselves as "two way" isn't ideal in the long term (it would be better if
1953 // all bindings could use an official 'property writer' API without needing to declare that they might). However,
1954 // since this is not, and has never been, a public API (_ko_property_writers was never documented), it's acceptable
1955 // as an internal implementation detail in the short term.
1956 // For those developers who rely on _ko_property_writers in their custom bindings, we expose _twoWayBindings as an
1957 // undocumented feature that makes it relatively easy to upgrade to KO 3.0. However, this is still not an official
1958 // public API, and we reserve the right to remove it at any time if we create a real public property writers API.
1959 ko.exportSymbol('expressionRewriting._twoWayBindings', ko.expressionRewriting.twoWayBindings);
1960
1961 // For backward compatibility, define the following aliases. (Previously, these function names were misleading because
1962 // they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
1963 ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
1964 ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);
1965 (function() {
1966 // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
1967 // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
1968 // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
1969 // of that virtual hierarchy
1970 //
1971 // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
1972 // without having to scatter special cases all over the binding and templating code.
1973
1974 // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
1975 // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
1976 // So, use node.text where available, and node.nodeValue elsewhere
1977 var commentNodesHaveTextProperty = document && document.createComment("test").text === "<!--test-->";
1978
1979 var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/;
1980 var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
1981 var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
1982
1983 function isStartComment(node) {
1984 return (node.nodeType == 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
1985 }
1986
1987 function isEndComment(node) {
1988 return (node.nodeType == 8) && endCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
1989 }
1990
1991 function getVirtualChildren(startComment, allowUnbalanced) {
1992 var currentNode = startComment;
1993 var depth = 1;
1994 var children = [];
1995 while (currentNode = currentNode.nextSibling) {
1996 if (isEndComment(currentNode)) {
1997 depth--;
1998 if (depth === 0)
1999 return children;
2000 }
2001
2002 children.push(currentNode);
2003
2004 if (isStartComment(currentNode))
2005 depth++;
2006 }
2007 if (!allowUnbalanced)
2008 throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
2009 return null;
2010 }
2011
2012 function getMatchingEndComment(startComment, allowUnbalanced) {
2013 var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
2014 if (allVirtualChildren) {
2015 if (allVirtualChildren.length > 0)
2016 return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
2017 return startComment.nextSibling;
2018 } else
2019 return null; // Must have no matching end comment, and allowUnbalanced is true
2020 }
2021
2022 function getUnbalancedChildTags(node) {
2023 // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
2024 // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
2025 var childNode = node.firstChild, captureRemaining = null;
2026 if (childNode) {
2027 do {
2028 if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
2029 captureRemaining.push(childNode);
2030 else if (isStartComment(childNode)) {
2031 var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
2032 if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
2033 childNode = matchingEndComment;
2034 else
2035 captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
2036 } else if (isEndComment(childNode)) {
2037 captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
2038 }
2039 } while (childNode = childNode.nextSibling);
2040 }
2041 return captureRemaining;
2042 }
2043
2044 ko.virtualElements = {
2045 allowedBindings: {},
2046
2047 childNodes: function(node) {
2048 return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
2049 },
2050
2051 emptyNode: function(node) {
2052 if (!isStartComment(node))
2053 ko.utils.emptyDomNode(node);
2054 else {
2055 var virtualChildren = ko.virtualElements.childNodes(node);
2056 for (var i = 0, j = virtualChildren.length; i < j; i++)
2057 ko.removeNode(virtualChildren[i]);
2058 }
2059 },
2060
2061 setDomNodeChildren: function(node, childNodes) {
2062 if (!isStartComment(node))
2063 ko.utils.setDomNodeChildren(node, childNodes);
2064 else {
2065 ko.virtualElements.emptyNode(node);
2066 var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
2067 for (var i = 0, j = childNodes.length; i < j; i++)
2068 endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
2069 }
2070 },
2071
2072 prepend: function(containerNode, nodeToPrepend) {
2073 if (!isStartComment(containerNode)) {
2074 if (containerNode.firstChild)
2075 containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
2076 else
2077 containerNode.appendChild(nodeToPrepend);
2078 } else {
2079 // Start comments must always have a parent and at least one following sibling (the end comment)
2080 containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
2081 }
2082 },
2083
2084 insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
2085 if (!insertAfterNode) {
2086 ko.virtualElements.prepend(containerNode, nodeToInsert);
2087 } else if (!isStartComment(containerNode)) {
2088 // Insert after insertion point
2089 if (insertAfterNode.nextSibling)
2090 containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
2091 else
2092 containerNode.appendChild(nodeToInsert);
2093 } else {
2094 // Children of start comments must always have a parent and at least one following sibling (the end comment)
2095 containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
2096 }
2097 },
2098
2099 firstChild: function(node) {
2100 if (!isStartComment(node))
2101 return node.firstChild;
2102 if (!node.nextSibling || isEndComment(node.nextSibling))
2103 return null;
2104 return node.nextSibling;
2105 },
2106
2107 nextSibling: function(node) {
2108 if (isStartComment(node))
2109 node = getMatchingEndComment(node);
2110 if (node.nextSibling && isEndComment(node.nextSibling))
2111 return null;
2112 return node.nextSibling;
2113 },
2114
2115 hasBindingValue: isStartComment,
2116
2117 virtualNodeBindingValue: function(node) {
2118 var regexMatch = (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
2119 return regexMatch ? regexMatch[1] : null;
2120 },
2121
2122 normaliseVirtualElementDomStructure: function(elementVerified) {
2123 // Workaround for https://github.com/SteveSanderson/knockout/issues/155
2124 // (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
2125 // that are direct descendants of <ul> into the preceding <li>)
2126 if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
2127 return;
2128
2129 // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
2130 // must be intended to appear *after* that child, so move them there.
2131 var childNode = elementVerified.firstChild;
2132 if (childNode) {
2133 do {
2134 if (childNode.nodeType === 1) {
2135 var unbalancedTags = getUnbalancedChildTags(childNode);
2136 if (unbalancedTags) {
2137 // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
2138 var nodeToInsertBefore = childNode.nextSibling;
2139 for (var i = 0; i < unbalancedTags.length; i++) {
2140 if (nodeToInsertBefore)
2141 elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
2142 else
2143 elementVerified.appendChild(unbalancedTags[i]);
2144 }
2145 }
2146 }
2147 } while (childNode = childNode.nextSibling);
2148 }
2149 }
2150 };
2151 })();
2152 ko.exportSymbol('virtualElements', ko.virtualElements);
2153 ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
2154 ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
2155 //ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
2156 ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
2157 //ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
2158 ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
2159 ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
2160 (function() {
2161 var defaultBindingAttributeName = "data-bind";
2162
2163 ko.bindingProvider = function() {
2164 this.bindingCache = {};
2165 };
2166
2167 ko.utils.extend(ko.bindingProvider.prototype, {
2168 'nodeHasBindings': function(node) {
2169 switch (node.nodeType) {
2170 case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
2171 case 8: return ko.virtualElements.hasBindingValue(node); // Comment node
2172 default: return false;
2173 }
2174 },
2175
2176 'getBindings': function(node, bindingContext) {
2177 var bindingsString = this['getBindingsString'](node, bindingContext);
2178 return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
2179 },
2180
2181 'getBindingAccessors': function(node, bindingContext) {
2182 var bindingsString = this['getBindingsString'](node, bindingContext);
2183 return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node, {'valueAccessors':true}) : null;
2184 },
2185
2186 // The following function is only used internally by this default provider.
2187 // It's not part of the interface definition for a general binding provider.
2188 'getBindingsString': function(node, bindingContext) {
2189 switch (node.nodeType) {
2190 case 1: return node.getAttribute(defaultBindingAttributeName); // Element
2191 case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
2192 default: return null;
2193 }
2194 },
2195
2196 // The following function is only used internally by this default provider.
2197 // It's not part of the interface definition for a general binding provider.
2198 'parseBindingsString': function(bindingsString, bindingContext, node, options) {
2199 try {
2200 var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache, options);
2201 return bindingFunction(bindingContext, node);
2202 } catch (ex) {
2203 ex.message = "Unable to parse bindings.\nBindings value: " + bindingsString + "\nMessage: " + ex.message;
2204 throw ex;
2205 }
2206 }
2207 });
2208
2209 ko.bindingProvider['instance'] = new ko.bindingProvider();
2210
2211 function createBindingsStringEvaluatorViaCache(bindingsString, cache, options) {
2212 var cacheKey = bindingsString + (options && options['valueAccessors'] || '');
2213 return cache[cacheKey]
2214 || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, options));
2215 }
2216
2217 function createBindingsStringEvaluator(bindingsString, options) {
2218 // Build the source for a function that evaluates "expression"
2219 // For each scope variable, add an extra level of "with" nesting
2220 // Example result: with(sc1) { with(sc0) { return (expression) } }
2221 var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString, options),
2222 functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
2223 return new Function("$context", "$element", functionBody);
2224 }
2225 })();
2226
2227 ko.exportSymbol('bindingProvider', ko.bindingProvider);
2228 (function () {
2229 ko.bindingHandlers = {};
2230
2231 // The following element types will not be recursed into during binding. In the future, we
2232 // may consider adding <template> to this list, because such elements' contents are always
2233 // intended to be bound in a different context from where they appear in the document.
2234 var bindingDoesNotRecurseIntoElementTypes = {
2235 // Don't want bindings that operate on text nodes to mutate <script> contents,
2236 // because it's unexpected and a potential XSS issue
2237 'script': true
2238 };
2239
2240 // Use an overridable method for retrieving binding handlers so that a plugins may support dynamically created handlers
2241 ko['getBindingHandler'] = function(bindingKey) {
2242 return ko.bindingHandlers[bindingKey];
2243 };
2244
2245 // The ko.bindingContext constructor is only called directly to create the root context. For child
2246 // contexts, use bindingContext.createChildContext or bindingContext.extend.
2247 ko.bindingContext = function(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback) {
2248
2249 // The binding context object includes static properties for the current, parent, and root view models.
2250 // If a view model is actually stored in an observable, the corresponding binding context object, and
2251 // any child contexts, must be updated when the view model is changed.
2252 function updateContext() {
2253 // Most of the time, the context will directly get a view model object, but if a function is given,
2254 // we call the function to retrieve the view model. If the function accesses any obsevables (or is
2255 // itself an observable), the dependency is tracked, and those observables can later cause the binding
2256 // context to be updated.
2257 var dataItem = isFunc ? dataItemOrAccessor() : dataItemOrAccessor;
2258
2259 if (parentContext) {
2260 // When a "parent" context is given, register a dependency on the parent context. Thus whenever the
2261 // parent context is updated, this context will also be updated.
2262 if (parentContext._subscribable)
2263 parentContext._subscribable();
2264
2265 // Copy $root and any custom properties from the parent context
2266 ko.utils.extend(self, parentContext);
2267
2268 // Because the above copy overwrites our own properties, we need to reset them.
2269 // During the first execution, "subscribable" isn't set, so don't bother doing the update then.
2270 if (subscribable) {
2271 self._subscribable = subscribable;
2272 }
2273 } else {
2274 self['$parents'] = [];
2275 self['$root'] = dataItem;
2276
2277 // Export 'ko' in the binding context so it will be available in bindings and templates
2278 // even if 'ko' isn't exported as a global, such as when using an AMD loader.
2279 // See https://github.com/SteveSanderson/knockout/issues/490
2280 self['ko'] = ko;
2281 }
2282 self['$rawData'] = dataItemOrAccessor;
2283 self['$data'] = dataItem;
2284 if (dataItemAlias)
2285 self[dataItemAlias] = dataItem;
2286
2287 // The extendCallback function is provided when creating a child context or extending a context.
2288 // It handles the specific actions needed to finish setting up the binding context. Actions in this
2289 // function could also add dependencies to this binding context.
2290 if (extendCallback)
2291 extendCallback(self, parentContext, dataItem);
2292
2293 return self['$data'];
2294 }
2295 function disposeWhen() {
2296 return nodes && !ko.utils.anyDomNodeIsAttachedToDocument(nodes);
2297 }
2298
2299 var self = this,
2300 isFunc = typeof(dataItemOrAccessor) == "function",
2301 nodes,
2302 subscribable = ko.dependentObservable(updateContext, null, { disposeWhen: disposeWhen, disposeWhenNodeIsRemoved: true });
2303
2304 // At this point, the binding context has been initialized, and the "subscribable" computed observable is
2305 // subscribed to any observables that were accessed in the process. If there is nothing to track, the
2306 // computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
2307 // the context object.
2308 if (subscribable.isActive()) {
2309 self._subscribable = subscribable;
2310
2311 // Always notify because even if the model ($data) hasn't changed, other context properties might have changed
2312 subscribable['equalityComparer'] = null;
2313
2314 // We need to be able to dispose of this computed observable when it's no longer needed. This would be
2315 // easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
2316 // we cannot assume that those nodes have any relation to each other. So instead we track any node that
2317 // the context is attached to, and dispose the computed when all of those nodes have been cleaned.
2318
2319 // Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
2320 nodes = [];
2321 subscribable._addNode = function(node) {
2322 nodes.push(node);
2323 ko.utils.domNodeDisposal.addDisposeCallback(node, function(node) {
2324 ko.utils.arrayRemoveItem(nodes, node);
2325 if (!nodes.length) {
2326 subscribable.dispose();
2327 self._subscribable = subscribable = undefined;
2328 }
2329 });
2330 };
2331 }
2332 }
2333
2334 // Extend the binding context hierarchy with a new view model object. If the parent context is watching
2335 // any obsevables, the new child context will automatically get a dependency on the parent context.
2336 // But this does not mean that the $data value of the child context will also get updated. If the child
2337 // view model also depends on the parent view model, you must provide a function that returns the correct
2338 // view model on each update.
2339 ko.bindingContext.prototype['createChildContext'] = function (dataItemOrAccessor, dataItemAlias, extendCallback) {
2340 return new ko.bindingContext(dataItemOrAccessor, this, dataItemAlias, function(self, parentContext) {
2341 // Extend the context hierarchy by setting the appropriate pointers
2342 self['$parentContext'] = parentContext;
2343 self['$parent'] = parentContext['$data'];
2344 self['$parents'] = (parentContext['$parents'] || []).slice(0);
2345 self['$parents'].unshift(self['$parent']);
2346 if (extendCallback)
2347 extendCallback(self);
2348 });
2349 };
2350
2351 // Extend the binding context with new custom properties. This doesn't change the context hierarchy.
2352 // Similarly to "child" contexts, provide a function here to make sure that the correct values are set
2353 // when an observable view model is updated.
2354 ko.bindingContext.prototype['extend'] = function(properties) {
2355 return new ko.bindingContext(this['$rawData'], this, null, function(self) {
2356 ko.utils.extend(self, typeof(properties) == "function" ? properties() : properties);
2357 });
2358 };
2359
2360 // Returns the valueAccesor function for a binding value
2361 function makeValueAccessor(value) {
2362 return function() {
2363 return value;
2364 };
2365 }
2366
2367 // Returns the value of a valueAccessor function
2368 function evaluateValueAccessor(valueAccessor) {
2369 return valueAccessor();
2370 }
2371
2372 // Given a function that returns bindings, create and return a new object that contains
2373 // binding value-accessors functions. Each accessor function calls the original function
2374 // so that it always gets the latest value and all dependencies are captured. This is used
2375 // by ko.applyBindingsToNode and getBindingsAndMakeAccessors.
2376 function makeAccessorsFromFunction(callback) {
2377 return ko.utils.objectMap(ko.dependencyDetection.ignore(callback), function(value, key) {
2378 return function() {
2379 return callback()[key];
2380 };
2381 });
2382 }
2383
2384 // Given a bindings function or object, create and return a new object that contains
2385 // binding value-accessors functions. This is used by ko.applyBindingsToNode.
2386 function makeBindingAccessors(bindings, context, node) {
2387 if (typeof bindings === 'function') {
2388 return makeAccessorsFromFunction(bindings.bind(null, context, node));
2389 } else {
2390 return ko.utils.objectMap(bindings, makeValueAccessor);
2391 }
2392 }
2393
2394 // This function is used if the binding provider doesn't include a getBindingAccessors function.
2395 // It must be called with 'this' set to the provider instance.
2396 function getBindingsAndMakeAccessors(node, context) {
2397 return makeAccessorsFromFunction(this['getBindings'].bind(this, node, context));
2398 }
2399
2400 function validateThatBindingIsAllowedForVirtualElements(bindingName) {
2401 var validator = ko.virtualElements.allowedBindings[bindingName];
2402 if (!validator)
2403 throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
2404 }
2405
2406 function applyBindingsToDescendantsInternal (bindingContext, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
2407 var currentChild,
2408 nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement),
2409 provider = ko.bindingProvider['instance'],
2410 preprocessNode = provider['preprocessNode'];
2411
2412 // Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's
2413 // possible to insert new siblings after it, and/or replace the node with a different one. This can be used to
2414 // implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that
2415 // trigger insertion of <template> contents at that point in the document.
2416 if (preprocessNode) {
2417 while (currentChild = nextInQueue) {
2418 nextInQueue = ko.virtualElements.nextSibling(currentChild);
2419 preprocessNode.call(provider, currentChild);
2420 }
2421 // Reset nextInQueue for the next loop
2422 nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
2423 }
2424
2425 while (currentChild = nextInQueue) {
2426 // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
2427 nextInQueue = ko.virtualElements.nextSibling(currentChild);
2428 applyBindingsToNodeAndDescendantsInternal(bindingContext, currentChild, bindingContextsMayDifferFromDomParentElement);
2429 }
2430 }
2431
2432 function applyBindingsToNodeAndDescendantsInternal (bindingContext, nodeVerified, bindingContextMayDifferFromDomParentElement) {
2433 var shouldBindDescendants = true;
2434
2435 // Perf optimisation: Apply bindings only if...
2436 // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
2437 // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
2438 // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
2439 var isElement = (nodeVerified.nodeType === 1);
2440 if (isElement) // Workaround IE <= 8 HTML parsing weirdness
2441 ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
2442
2443 var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
2444 || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
2445 if (shouldApplyBindings)
2446 shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, bindingContext, bindingContextMayDifferFromDomParentElement)['shouldBindDescendants'];
2447
2448 if (shouldBindDescendants && !bindingDoesNotRecurseIntoElementTypes[ko.utils.tagNameLower(nodeVerified)]) {
2449 // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
2450 // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
2451 // hence bindingContextsMayDifferFromDomParentElement is false
2452 // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
2453 // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
2454 // hence bindingContextsMayDifferFromDomParentElement is true
2455 applyBindingsToDescendantsInternal(bindingContext, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
2456 }
2457 }
2458
2459 var boundElementDomDataKey = ko.utils.domData.nextKey();
2460
2461
2462 function topologicalSortBindings(bindings) {
2463 // Depth-first sort
2464 var result = [], // The list of key/handler pairs that we will return
2465 bindingsConsidered = {}, // A temporary record of which bindings are already in 'result'
2466 cyclicDependencyStack = []; // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it
2467 ko.utils.objectForEach(bindings, function pushBinding(bindingKey) {
2468 if (!bindingsConsidered[bindingKey]) {
2469 var binding = ko['getBindingHandler'](bindingKey);
2470 if (binding) {
2471 // First add dependencies (if any) of the current binding
2472 if (binding['after']) {
2473 cyclicDependencyStack.push(bindingKey);
2474 ko.utils.arrayForEach(binding['after'], function(bindingDependencyKey) {
2475 if (bindings[bindingDependencyKey]) {
2476 if (ko.utils.arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) {
2477 throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + cyclicDependencyStack.join(", "));
2478 } else {
2479 pushBinding(bindingDependencyKey);
2480 }
2481 }
2482 });
2483 cyclicDependencyStack.pop();
2484 }
2485 // Next add the current binding
2486 result.push({ key: bindingKey, handler: binding });
2487 }
2488 bindingsConsidered[bindingKey] = true;
2489 }
2490 });
2491
2492 return result;
2493 }
2494
2495 function applyBindingsToNodeInternal(node, sourceBindings, bindingContext, bindingContextMayDifferFromDomParentElement) {
2496 // Prevent multiple applyBindings calls for the same node, except when a binding value is specified
2497 var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
2498 if (!sourceBindings) {
2499 if (alreadyBound) {
2500 throw Error("You cannot apply bindings multiple times to the same element.");
2501 }
2502 ko.utils.domData.set(node, boundElementDomDataKey, true);
2503 }
2504
2505 // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
2506 // we can easily recover it just by scanning up the node's ancestors in the DOM
2507 // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
2508 if (!alreadyBound && bindingContextMayDifferFromDomParentElement)
2509 ko.storedBindingContextForNode(node, bindingContext);
2510
2511 // Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings
2512 var bindings;
2513 if (sourceBindings && typeof sourceBindings !== 'function') {
2514 bindings = sourceBindings;
2515 } else {
2516 var provider = ko.bindingProvider['instance'],
2517 getBindings = provider['getBindingAccessors'] || getBindingsAndMakeAccessors;
2518
2519 if (sourceBindings || bindingContext._subscribable) {
2520 // When an obsevable view model is used, the binding context will expose an observable _subscribable value.
2521 // Get the binding from the provider within a computed observable so that we can update the bindings whenever
2522 // the binding context is updated.
2523 var bindingsUpdater = ko.dependentObservable(
2524 function() {
2525 bindings = sourceBindings ? sourceBindings(bindingContext, node) : getBindings.call(provider, node, bindingContext);
2526 // Register a dependency on the binding context
2527 if (bindings && bindingContext._subscribable)
2528 bindingContext._subscribable();
2529 return bindings;
2530 },
2531 null, { disposeWhenNodeIsRemoved: node }
2532 );
2533
2534 if (!bindings || !bindingsUpdater.isActive())
2535 bindingsUpdater = null;
2536 } else {
2537 bindings = ko.dependencyDetection.ignore(getBindings, provider, [node, bindingContext]);
2538 }
2539 }
2540
2541 var bindingHandlerThatControlsDescendantBindings;
2542 if (bindings) {
2543 // Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding
2544 // context update), just return the value accessor from the binding. Otherwise, return a function that always gets
2545 // the latest binding value and registers a dependency on the binding updater.
2546 var getValueAccessor = bindingsUpdater
2547 ? function(bindingKey) {
2548 return function() {
2549 return evaluateValueAccessor(bindingsUpdater()[bindingKey]);
2550 };
2551 } : function(bindingKey) {
2552 return bindings[bindingKey];
2553 };
2554
2555 // Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated
2556 function allBindings() {
2557 return ko.utils.objectMap(bindingsUpdater ? bindingsUpdater() : bindings, evaluateValueAccessor);
2558 }
2559 // The following is the 3.x allBindings API
2560 allBindings['get'] = function(key) {
2561 return bindings[key] && evaluateValueAccessor(getValueAccessor(key));
2562 };
2563 allBindings['has'] = function(key) {
2564 return key in bindings;
2565 };
2566
2567 // First put the bindings into the right order
2568 var orderedBindings = topologicalSortBindings(bindings);
2569
2570 // Go through the sorted bindings, calling init and update for each
2571 ko.utils.arrayForEach(orderedBindings, function(bindingKeyAndHandler) {
2572 // Note that topologicalSortBindings has already filtered out any nonexistent binding handlers,
2573 // so bindingKeyAndHandler.handler will always be nonnull.
2574 var handlerInitFn = bindingKeyAndHandler.handler["init"],
2575 handlerUpdateFn = bindingKeyAndHandler.handler["update"],
2576 bindingKey = bindingKeyAndHandler.key;
2577
2578 if (node.nodeType === 8) {
2579 validateThatBindingIsAllowedForVirtualElements(bindingKey);
2580 }
2581
2582 try {
2583 // Run init, ignoring any dependencies
2584 if (typeof handlerInitFn == "function") {
2585 ko.dependencyDetection.ignore(function() {
2586 var initResult = handlerInitFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
2587
2588 // If this binding handler claims to control descendant bindings, make a note of this
2589 if (initResult && initResult['controlsDescendantBindings']) {
2590 if (bindingHandlerThatControlsDescendantBindings !== undefined)
2591 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.");
2592 bindingHandlerThatControlsDescendantBindings = bindingKey;
2593 }
2594 });
2595 }
2596
2597 // Run update in its own computed wrapper
2598 if (typeof handlerUpdateFn == "function") {
2599 ko.dependentObservable(
2600 function() {
2601 handlerUpdateFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
2602 },
2603 null,
2604 { disposeWhenNodeIsRemoved: node }
2605 );
2606 }
2607 } catch (ex) {
2608 ex.message = "Unable to process binding \"" + bindingKey + ": " + bindings[bindingKey] + "\"\nMessage: " + ex.message;
2609 throw ex;
2610 }
2611 });
2612 }
2613
2614 return {
2615 'shouldBindDescendants': bindingHandlerThatControlsDescendantBindings === undefined
2616 };
2617 };
2618
2619 var storedBindingContextDomDataKey = ko.utils.domData.nextKey();
2620 ko.storedBindingContextForNode = function (node, bindingContext) {
2621 if (arguments.length == 2) {
2622 ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
2623 if (bindingContext._subscribable)
2624 bindingContext._subscribable._addNode(node);
2625 } else {
2626 return ko.utils.domData.get(node, storedBindingContextDomDataKey);
2627 }
2628 }
2629
2630 function getBindingContext(viewModelOrBindingContext) {
2631 return viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
2632 ? viewModelOrBindingContext
2633 : new ko.bindingContext(viewModelOrBindingContext);
2634 }
2635
2636 ko.applyBindingAccessorsToNode = function (node, bindings, viewModelOrBindingContext) {
2637 if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
2638 ko.virtualElements.normaliseVirtualElementDomStructure(node);
2639 return applyBindingsToNodeInternal(node, bindings, getBindingContext(viewModelOrBindingContext), true);
2640 };
2641
2642 ko.applyBindingsToNode = function (node, bindings, viewModelOrBindingContext) {
2643 var context = getBindingContext(viewModelOrBindingContext);
2644 return ko.applyBindingAccessorsToNode(node, makeBindingAccessors(bindings, context, node), context);
2645 };
2646
2647 ko.applyBindingsToDescendants = function(viewModelOrBindingContext, rootNode) {
2648 if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
2649 applyBindingsToDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
2650 };
2651
2652 ko.applyBindings = function (viewModelOrBindingContext, rootNode) {
2653 if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
2654 throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
2655 rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
2656
2657 applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
2658 };
2659
2660 // Retrieving binding context from arbitrary nodes
2661 ko.contextFor = function(node) {
2662 // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
2663 switch (node.nodeType) {
2664 case 1:
2665 case 8:
2666 var context = ko.storedBindingContextForNode(node);
2667 if (context) return context;
2668 if (node.parentNode) return ko.contextFor(node.parentNode);
2669 break;
2670 }
2671 return undefined;
2672 };
2673 ko.dataFor = function(node) {
2674 var context = ko.contextFor(node);
2675 return context ? context['$data'] : undefined;
2676 };
2677
2678 ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
2679 ko.exportSymbol('applyBindings', ko.applyBindings);
2680 ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
2681 ko.exportSymbol('applyBindingAccessorsToNode', ko.applyBindingAccessorsToNode);
2682 ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
2683 ko.exportSymbol('contextFor', ko.contextFor);
2684 ko.exportSymbol('dataFor', ko.dataFor);
2685 })();
2686 var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
2687 ko.bindingHandlers['attr'] = {
2688 'update': function(element, valueAccessor, allBindings) {
2689 var value = ko.utils.unwrapObservable(valueAccessor()) || {};
2690 ko.utils.objectForEach(value, function(attrName, attrValue) {
2691 attrValue = ko.utils.unwrapObservable(attrValue);
2692
2693 // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
2694 // when someProp is a "no value"-like value (strictly null, false, or undefined)
2695 // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
2696 var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
2697 if (toRemove)
2698 element.removeAttribute(attrName);
2699
2700 // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
2701 // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
2702 // but instead of figuring out the mode, we'll just set the attribute through the Javascript
2703 // property for IE <= 8.
2704 if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
2705 attrName = attrHtmlToJavascriptMap[attrName];
2706 if (toRemove)
2707 element.removeAttribute(attrName);
2708 else
2709 element[attrName] = attrValue;
2710 } else if (!toRemove) {
2711 element.setAttribute(attrName, attrValue.toString());
2712 }
2713
2714 // Treat "name" specially - although you can think of it as an attribute, it also needs
2715 // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
2716 // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
2717 // entirely, and there's no strong reason to allow for such casing in HTML.
2718 if (attrName === "name") {
2719 ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
2720 }
2721 });
2722 }
2723 };
2724 (function() {
2725
2726 ko.bindingHandlers['checked'] = {
2727 'after': ['value', 'attr'],
2728 'init': function (element, valueAccessor, allBindings) {
2729 function checkedValue() {
2730 return allBindings['has']('checkedValue')
2731 ? ko.utils.unwrapObservable(allBindings.get('checkedValue'))
2732 : element.value;
2733 }
2734
2735 function updateModel() {
2736 // This updates the model value from the view value.
2737 // It runs in response to DOM events (click) and changes in checkedValue.
2738 var isChecked = element.checked,
2739 elemValue = useCheckedValue ? checkedValue() : isChecked;
2740
2741 // When we're first setting up this computed, don't change any model state.
2742 if (!shouldSet) {
2743 return;
2744 }
2745
2746 // We can ignore unchecked radio buttons, because some other radio
2747 // button will be getting checked, and that one can take care of updating state.
2748 if (isRadio && !isChecked) {
2749 return;
2750 }
2751
2752 var modelValue = ko.dependencyDetection.ignore(valueAccessor);
2753 if (isValueArray) {
2754 if (oldElemValue !== elemValue) {
2755 // When we're responding to the checkedValue changing, and the element is
2756 // currently checked, replace the old elem value with the new elem value
2757 // in the model array.
2758 if (isChecked) {
2759 ko.utils.addOrRemoveItem(modelValue, elemValue, true);
2760 ko.utils.addOrRemoveItem(modelValue, oldElemValue, false);
2761 }
2762
2763 oldElemValue = elemValue;
2764 } else {
2765 // When we're responding to the user having checked/unchecked a checkbox,
2766 // add/remove the element value to the model array.
2767 ko.utils.addOrRemoveItem(modelValue, elemValue, isChecked);
2768 }
2769 } else {
2770 ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'checked', elemValue, true);
2771 }
2772 };
2773
2774 function updateView() {
2775 // This updates the view value from the model value.
2776 // It runs in response to changes in the bound (checked) value.
2777 var modelValue = ko.utils.unwrapObservable(valueAccessor());
2778
2779 if (isValueArray) {
2780 // When a checkbox is bound to an array, being checked represents its value being present in that array
2781 element.checked = ko.utils.arrayIndexOf(modelValue, checkedValue()) >= 0;
2782 } else if (isCheckbox) {
2783 // When a checkbox is bound to any other value (not an array), being checked represents the value being trueish
2784 element.checked = modelValue;
2785 } else {
2786 // For radio buttons, being checked means that the radio button's value corresponds to the model value
2787 element.checked = (checkedValue() === modelValue);
2788 }
2789 };
2790
2791 var isCheckbox = element.type == "checkbox",
2792 isRadio = element.type == "radio";
2793
2794 // Only bind to check boxes and radio buttons
2795 if (!isCheckbox && !isRadio) {
2796 return;
2797 }
2798
2799 var isValueArray = isCheckbox && (ko.utils.unwrapObservable(valueAccessor()) instanceof Array),
2800 oldElemValue = isValueArray ? checkedValue() : undefined,
2801 useCheckedValue = isRadio || isValueArray,
2802 shouldSet = false;
2803
2804 // IE 6 won't allow radio buttons to be selected unless they have a name
2805 if (isRadio && !element.name)
2806 ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
2807
2808 // Set up two computeds to update the binding:
2809
2810 // The first responds to changes in the checkedValue value and to element clicks
2811 ko.dependentObservable(updateModel, null, { disposeWhenNodeIsRemoved: element });
2812 ko.utils.registerEventHandler(element, "click", updateModel);
2813
2814 // The second responds to changes in the model value (the one associated with the checked binding)
2815 ko.dependentObservable(updateView, null, { disposeWhenNodeIsRemoved: element });
2816
2817 shouldSet = true;
2818 }
2819 };
2820 ko.expressionRewriting.twoWayBindings['checked'] = true;
2821
2822 ko.bindingHandlers['checkedValue'] = {
2823 'update': function (element, valueAccessor) {
2824 element.value = ko.utils.unwrapObservable(valueAccessor());
2825 }
2826 };
2827
2828 })();var classesWrittenByBindingKey = '__ko__cssValue';
2829 ko.bindingHandlers['css'] = {
2830 'update': function (element, valueAccessor) {
2831 var value = ko.utils.unwrapObservable(valueAccessor());
2832 if (typeof value == "object") {
2833 ko.utils.objectForEach(value, function(className, shouldHaveClass) {
2834 shouldHaveClass = ko.utils.unwrapObservable(shouldHaveClass);
2835 ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
2836 });
2837 } else {
2838 value = String(value || ''); // Make sure we don't try to store or set a non-string value
2839 ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
2840 element[classesWrittenByBindingKey] = value;
2841 ko.utils.toggleDomNodeCssClass(element, value, true);
2842 }
2843 }
2844 };
2845 ko.bindingHandlers['enable'] = {
2846 'update': function (element, valueAccessor) {
2847 var value = ko.utils.unwrapObservable(valueAccessor());
2848 if (value && element.disabled)
2849 element.removeAttribute("disabled");
2850 else if ((!value) && (!element.disabled))
2851 element.disabled = true;
2852 }
2853 };
2854
2855 ko.bindingHandlers['disable'] = {
2856 'update': function (element, valueAccessor) {
2857 ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
2858 }
2859 };
2860 // For certain common events (currently just 'click'), allow a simplified data-binding syntax
2861 // e.g. click:handler instead of the usual full-length event:{click:handler}
2862 function makeEventHandlerShortcut(eventName) {
2863 ko.bindingHandlers[eventName] = {
2864 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
2865 var newValueAccessor = function () {
2866 var result = {};
2867 result[eventName] = valueAccessor();
2868 return result;
2869 };
2870 return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindings, viewModel, bindingContext);
2871 }
2872 }
2873 }
2874
2875 ko.bindingHandlers['event'] = {
2876 'init' : function (element, valueAccessor, allBindings, viewModel, bindingContext) {
2877 var eventsToHandle = valueAccessor() || {};
2878 ko.utils.objectForEach(eventsToHandle, function(eventName) {
2879 if (typeof eventName == "string") {
2880 ko.utils.registerEventHandler(element, eventName, function (event) {
2881 var handlerReturnValue;
2882 var handlerFunction = valueAccessor()[eventName];
2883 if (!handlerFunction)
2884 return;
2885
2886 try {
2887 // Take all the event args, and prefix with the viewmodel
2888 var argsForHandler = ko.utils.makeArray(arguments);
2889 viewModel = bindingContext['$data'];
2890 argsForHandler.unshift(viewModel);
2891 handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
2892 } finally {
2893 if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
2894 if (event.preventDefault)
2895 event.preventDefault();
2896 else
2897 event.returnValue = false;
2898 }
2899 }
2900
2901 var bubble = allBindings.get(eventName + 'Bubble') !== false;
2902 if (!bubble) {
2903 event.cancelBubble = true;
2904 if (event.stopPropagation)
2905 event.stopPropagation();
2906 }
2907 });
2908 }
2909 });
2910 }
2911 };
2912 // "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
2913 // "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
2914 ko.bindingHandlers['foreach'] = {
2915 makeTemplateValueAccessor: function(valueAccessor) {
2916 return function() {
2917 var modelValue = valueAccessor(),
2918 unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
2919
2920 // If unwrappedValue is the array, pass in the wrapped value on its own
2921 // The value will be unwrapped and tracked within the template binding
2922 // (See https://github.com/SteveSanderson/knockout/issues/523)
2923 if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
2924 return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
2925
2926 // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
2927 ko.utils.unwrapObservable(modelValue);
2928 return {
2929 'foreach': unwrappedValue['data'],
2930 'as': unwrappedValue['as'],
2931 'includeDestroyed': unwrappedValue['includeDestroyed'],
2932 'afterAdd': unwrappedValue['afterAdd'],
2933 'beforeRemove': unwrappedValue['beforeRemove'],
2934 'afterRender': unwrappedValue['afterRender'],
2935 'beforeMove': unwrappedValue['beforeMove'],
2936 'afterMove': unwrappedValue['afterMove'],
2937 'templateEngine': ko.nativeTemplateEngine.instance
2938 };
2939 };
2940 },
2941 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
2942 return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
2943 },
2944 'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
2945 return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindings, viewModel, bindingContext);
2946 }
2947 };
2948 ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
2949 ko.virtualElements.allowedBindings['foreach'] = true;
2950 var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
2951 var hasfocusLastValue = '__ko_hasfocusLastValue';
2952 ko.bindingHandlers['hasfocus'] = {
2953 'init': function(element, valueAccessor, allBindings) {
2954 var handleElementFocusChange = function(isFocused) {
2955 // Where possible, ignore which event was raised and determine focus state using activeElement,
2956 // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
2957 // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
2958 // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
2959 // from calling 'blur()' on the element when it loses focus.
2960 // Discussion at https://github.com/SteveSanderson/knockout/pull/352
2961 element[hasfocusUpdatingProperty] = true;
2962 var ownerDoc = element.ownerDocument;
2963 if ("activeElement" in ownerDoc) {
2964 var active;
2965 try {
2966 active = ownerDoc.activeElement;
2967 } catch(e) {
2968 // IE9 throws if you access activeElement during page load (see issue #703)
2969 active = ownerDoc.body;
2970 }
2971 isFocused = (active === element);
2972 }
2973 var modelValue = valueAccessor();
2974 ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'hasfocus', isFocused, true);
2975
2976 //cache the latest value, so we can avoid unnecessarily calling focus/blur in the update function
2977 element[hasfocusLastValue] = isFocused;
2978 element[hasfocusUpdatingProperty] = false;
2979 };
2980 var handleElementFocusIn = handleElementFocusChange.bind(null, true);
2981 var handleElementFocusOut = handleElementFocusChange.bind(null, false);
2982
2983 ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
2984 ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
2985 ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
2986 ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
2987 },
2988 'update': function(element, valueAccessor) {
2989 var value = !!ko.utils.unwrapObservable(valueAccessor()); //force boolean to compare with last value
2990 if (!element[hasfocusUpdatingProperty] && element[hasfocusLastValue] !== value) {
2991 value ? element.focus() : element.blur();
2992 ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
2993 }
2994 }
2995 };
2996 ko.expressionRewriting.twoWayBindings['hasfocus'] = true;
2997
2998 ko.bindingHandlers['hasFocus'] = ko.bindingHandlers['hasfocus']; // Make "hasFocus" an alias
2999 ko.expressionRewriting.twoWayBindings['hasFocus'] = true;
3000 ko.bindingHandlers['html'] = {
3001 'init': function() {
3002 // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
3003 return { 'controlsDescendantBindings': true };
3004 },
3005 'update': function (element, valueAccessor) {
3006 // setHtml will unwrap the value if needed
3007 ko.utils.setHtml(element, valueAccessor());
3008 }
3009 };
3010 var withIfDomDataKey = ko.utils.domData.nextKey();
3011 // Makes a binding like with or if
3012 function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
3013 ko.bindingHandlers[bindingKey] = {
3014 'init': function(element) {
3015 ko.utils.domData.set(element, withIfDomDataKey, {});
3016 return { 'controlsDescendantBindings': true };
3017 },
3018 'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
3019 var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
3020 dataValue = ko.utils.unwrapObservable(valueAccessor()),
3021 shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
3022 isFirstRender = !withIfData.savedNodes,
3023 needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
3024
3025 if (needsRefresh) {
3026 if (isFirstRender) {
3027 withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
3028 }
3029
3030 if (shouldDisplay) {
3031 if (!isFirstRender) {
3032 ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
3033 }
3034 ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
3035 } else {
3036 ko.virtualElements.emptyNode(element);
3037 }
3038
3039 withIfData.didDisplayOnLastUpdate = shouldDisplay;
3040 }
3041 }
3042 };
3043 ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
3044 ko.virtualElements.allowedBindings[bindingKey] = true;
3045 }
3046
3047 // Construct the actual binding handlers
3048 makeWithIfBinding('if');
3049 makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
3050 makeWithIfBinding('with', true /* isWith */, false /* isNot */,
3051 function(bindingContext, dataValue) {
3052 return bindingContext['createChildContext'](dataValue);
3053 }
3054 );
3055 ko.bindingHandlers['options'] = {
3056 'init': function(element) {
3057 if (ko.utils.tagNameLower(element) !== "select")
3058 throw new Error("options binding applies only to SELECT elements");
3059
3060 // Remove all existing <option>s.
3061 while (element.length > 0) {
3062 element.remove(0);
3063 }
3064
3065 // Ensures that the binding processor doesn't try to bind the options
3066 return { 'controlsDescendantBindings': true };
3067 },
3068 'update': function (element, valueAccessor, allBindings) {
3069 function selectedOptions() {
3070 return ko.utils.arrayFilter(element.options, function (node) { return node.selected; });
3071 }
3072
3073 var selectWasPreviouslyEmpty = element.length == 0;
3074 var previousScrollTop = (!selectWasPreviouslyEmpty && element.multiple) ? element.scrollTop : null;
3075
3076 var unwrappedArray = ko.utils.unwrapObservable(valueAccessor());
3077 var includeDestroyed = allBindings.get('optionsIncludeDestroyed');
3078 var captionPlaceholder = {};
3079 var captionValue;
3080 var previousSelectedValues;
3081 if (element.multiple) {
3082 previousSelectedValues = ko.utils.arrayMap(selectedOptions(), ko.selectExtensions.readValue);
3083 } else {
3084 previousSelectedValues = element.selectedIndex >= 0 ? [ ko.selectExtensions.readValue(element.options[element.selectedIndex]) ] : [];
3085 }
3086
3087 if (unwrappedArray) {
3088 if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
3089 unwrappedArray = [unwrappedArray];
3090
3091 // Filter out any entries marked as destroyed
3092 var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
3093 return includeDestroyed || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
3094 });
3095
3096 // If caption is included, add it to the array
3097 if (allBindings['has']('optionsCaption')) {
3098 captionValue = ko.utils.unwrapObservable(allBindings.get('optionsCaption'));
3099 // If caption value is null or undefined, don't show a caption
3100 if (captionValue !== null && captionValue !== undefined) {
3101 filteredArray.unshift(captionPlaceholder);
3102 }
3103 }
3104 } else {
3105 // If a falsy value is provided (e.g. null), we'll simply empty the select element
3106 unwrappedArray = [];
3107 }
3108
3109 function applyToObject(object, predicate, defaultValue) {
3110 var predicateType = typeof predicate;
3111 if (predicateType == "function") // Given a function; run it against the data value
3112 return predicate(object);
3113 else if (predicateType == "string") // Given a string; treat it as a property name on the data value
3114 return object[predicate];
3115 else // Given no optionsText arg; use the data value itself
3116 return defaultValue;
3117 }
3118
3119 // The following functions can run at two different times:
3120 // The first is when the whole array is being updated directly from this binding handler.
3121 // The second is when an observable value for a specific array entry is updated.
3122 // oldOptions will be empty in the first case, but will be filled with the previously generated option in the second.
3123 var itemUpdate = false;
3124 function optionForArrayItem(arrayEntry, index, oldOptions) {
3125 if (oldOptions.length) {
3126 previousSelectedValues = oldOptions[0].selected ? [ ko.selectExtensions.readValue(oldOptions[0]) ] : [];
3127 itemUpdate = true;
3128 }
3129 var option = document.createElement("option");
3130 if (arrayEntry === captionPlaceholder) {
3131 ko.utils.setTextContent(option, allBindings.get('optionsCaption'));
3132 ko.selectExtensions.writeValue(option, undefined);
3133 } else {
3134 // Apply a value to the option element
3135 var optionValue = applyToObject(arrayEntry, allBindings.get('optionsValue'), arrayEntry);
3136 ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
3137
3138 // Apply some text to the option element
3139 var optionText = applyToObject(arrayEntry, allBindings.get('optionsText'), optionValue);
3140 ko.utils.setTextContent(option, optionText);
3141 }
3142 return [option];
3143 }
3144
3145 function setSelectionCallback(arrayEntry, newOptions) {
3146 // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
3147 // That's why we first added them without selection. Now it's time to set the selection.
3148 if (previousSelectedValues.length) {
3149 var isSelected = ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[0])) >= 0;
3150 ko.utils.setOptionNodeSelectionState(newOptions[0], isSelected);
3151
3152 // If this option was changed from being selected during a single-item update, notify the change
3153 if (itemUpdate && !isSelected)
3154 ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
3155 }
3156 }
3157
3158 var callback = setSelectionCallback;
3159 if (allBindings['has']('optionsAfterRender')) {
3160 callback = function(arrayEntry, newOptions) {
3161 setSelectionCallback(arrayEntry, newOptions);
3162 ko.dependencyDetection.ignore(allBindings.get('optionsAfterRender'), null, [newOptions[0], arrayEntry !== captionPlaceholder ? arrayEntry : undefined]);
3163 }
3164 }
3165
3166 ko.utils.setDomNodeChildrenFromArrayMapping(element, filteredArray, optionForArrayItem, null, callback);
3167
3168 // Determine if the selection has changed as a result of updating the options list
3169 var selectionChanged;
3170 if (element.multiple) {
3171 // For a multiple-select box, compare the new selection count to the previous one
3172 // But if nothing was selected before, the selection can't have changed
3173 selectionChanged = previousSelectedValues.length && selectedOptions().length < previousSelectedValues.length;
3174 } else {
3175 // For a single-select box, compare the current value to the previous value
3176 // But if nothing was selected before or nothing is selected now, just look for a change in selection
3177 selectionChanged = (previousSelectedValues.length && element.selectedIndex >= 0)
3178 ? (ko.selectExtensions.readValue(element.options[element.selectedIndex]) !== previousSelectedValues[0])
3179 : (previousSelectedValues.length || element.selectedIndex >= 0);
3180 }
3181
3182 // Ensure consistency between model value and selected option.
3183 // If the dropdown was changed so that selection is no longer the same,
3184 // notify the value or selectedOptions binding.
3185 if (selectionChanged)
3186 ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
3187
3188 // Workaround for IE bug
3189 ko.utils.ensureSelectElementIsRenderedCorrectly(element);
3190
3191 if (previousScrollTop && Math.abs(previousScrollTop - element.scrollTop) > 20)
3192 element.scrollTop = previousScrollTop;
3193 }
3194 };
3195 ko.bindingHandlers['options'].optionValueDomDataKey = ko.utils.domData.nextKey();
3196 ko.bindingHandlers['selectedOptions'] = {
3197 'after': ['options', 'foreach'],
3198 'init': function (element, valueAccessor, allBindings) {
3199 ko.utils.registerEventHandler(element, "change", function () {
3200 var value = valueAccessor(), valueToWrite = [];
3201 ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
3202 if (node.selected)
3203 valueToWrite.push(ko.selectExtensions.readValue(node));
3204 });
3205 ko.expressionRewriting.writeValueToProperty(value, allBindings, 'selectedOptions', valueToWrite);
3206 });
3207 },
3208 'update': function (element, valueAccessor) {
3209 if (ko.utils.tagNameLower(element) != "select")
3210 throw new Error("values binding applies only to SELECT elements");
3211
3212 var newValue = ko.utils.unwrapObservable(valueAccessor());
3213 if (newValue && typeof newValue.length == "number") {
3214 ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
3215 var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
3216 ko.utils.setOptionNodeSelectionState(node, isSelected);
3217 });
3218 }
3219 }
3220 };
3221 ko.expressionRewriting.twoWayBindings['selectedOptions'] = true;
3222 ko.bindingHandlers['style'] = {
3223 'update': function (element, valueAccessor) {
3224 var value = ko.utils.unwrapObservable(valueAccessor() || {});
3225 ko.utils.objectForEach(value, function(styleName, styleValue) {
3226 styleValue = ko.utils.unwrapObservable(styleValue);
3227 element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
3228 });
3229 }
3230 };
3231 ko.bindingHandlers['submit'] = {
3232 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
3233 if (typeof valueAccessor() != "function")
3234 throw new Error("The value for a submit binding must be a function");
3235 ko.utils.registerEventHandler(element, "submit", function (event) {
3236 var handlerReturnValue;
3237 var value = valueAccessor();
3238 try { handlerReturnValue = value.call(bindingContext['$data'], element); }
3239 finally {
3240 if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
3241 if (event.preventDefault)
3242 event.preventDefault();
3243 else
3244 event.returnValue = false;
3245 }
3246 }
3247 });
3248 }
3249 };
3250 ko.bindingHandlers['text'] = {
3251 'init': function() {
3252 // Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications).
3253 // It should also make things faster, as we no longer have to consider whether the text node might be bindable.
3254 return { 'controlsDescendantBindings': true };
3255 },
3256 'update': function (element, valueAccessor) {
3257 ko.utils.setTextContent(element, valueAccessor());
3258 }
3259 };
3260 ko.virtualElements.allowedBindings['text'] = true;
3261 ko.bindingHandlers['uniqueName'] = {
3262 'init': function (element, valueAccessor) {
3263 if (valueAccessor()) {
3264 var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
3265 ko.utils.setElementName(element, name);
3266 }
3267 }
3268 };
3269 ko.bindingHandlers['uniqueName'].currentIndex = 0;
3270 ko.bindingHandlers['value'] = {
3271 'after': ['options', 'foreach'],
3272 'init': function (element, valueAccessor, allBindings) {
3273 // Always catch "change" event; possibly other events too if asked
3274 var eventsToCatch = ["change"];
3275 var requestedEventsToCatch = allBindings.get("valueUpdate");
3276 var propertyChangedFired = false;
3277 if (requestedEventsToCatch) {
3278 if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
3279 requestedEventsToCatch = [requestedEventsToCatch];
3280 ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
3281 eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
3282 }
3283
3284 var valueUpdateHandler = function() {
3285 propertyChangedFired = false;
3286 var modelValue = valueAccessor();
3287 var elementValue = ko.selectExtensions.readValue(element);
3288 ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'value', elementValue);
3289 }
3290
3291 // Workaround for https://github.com/SteveSanderson/knockout/issues/122
3292 // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
3293 var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
3294 && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
3295 if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
3296 ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
3297 ko.utils.registerEventHandler(element, "blur", function() {
3298 if (propertyChangedFired) {
3299 valueUpdateHandler();
3300 }
3301 });
3302 }
3303
3304 ko.utils.arrayForEach(eventsToCatch, function(eventName) {
3305 // The syntax "after<eventname>" means "run the handler asynchronously after the event"
3306 // This is useful, for example, to catch "keydown" events after the browser has updated the control
3307 // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
3308 var handler = valueUpdateHandler;
3309 if (ko.utils.stringStartsWith(eventName, "after")) {
3310 handler = function() { setTimeout(valueUpdateHandler, 0) };
3311 eventName = eventName.substring("after".length);
3312 }
3313 ko.utils.registerEventHandler(element, eventName, handler);
3314 });
3315 },
3316 'update': function (element, valueAccessor) {
3317 var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
3318 var newValue = ko.utils.unwrapObservable(valueAccessor());
3319 var elementValue = ko.selectExtensions.readValue(element);
3320 var valueHasChanged = (newValue !== elementValue);
3321
3322 if (valueHasChanged) {
3323 var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
3324 applyValueAction();
3325
3326 if (valueIsSelectOption) {
3327 if (newValue !== ko.selectExtensions.readValue(element)) {
3328 // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
3329 // because you're not allowed to have a model value that disagrees with a visible UI selection.
3330 ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
3331 } else {
3332 // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
3333 // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
3334 // to apply the value as well.
3335 setTimeout(applyValueAction, 0);
3336 }
3337 }
3338 }
3339 }
3340 };
3341 ko.expressionRewriting.twoWayBindings['value'] = true;
3342 ko.bindingHandlers['visible'] = {
3343 'update': function (element, valueAccessor) {
3344 var value = ko.utils.unwrapObservable(valueAccessor());
3345 var isCurrentlyVisible = !(element.style.display == "none");
3346 if (value && !isCurrentlyVisible)
3347 element.style.display = "";
3348 else if ((!value) && isCurrentlyVisible)
3349 element.style.display = "none";
3350 }
3351 };
3352 // 'click' is just a shorthand for the usual full-length event:{click:handler}
3353 makeEventHandlerShortcut('click');
3354 // If you want to make a custom template engine,
3355 //
3356 // [1] Inherit from this class (like ko.nativeTemplateEngine does)
3357 // [2] Override 'renderTemplateSource', supplying a function with this signature:
3358 //
3359 // function (templateSource, bindingContext, options) {
3360 // // - templateSource.text() is the text of the template you should render
3361 // // - bindingContext.$data is the data you should pass into the template
3362 // // - you might also want to make bindingContext.$parent, bindingContext.$parents,
3363 // // and bindingContext.$root available in the template too
3364 // // - options gives you access to any other properties set on "data-bind: { template: options }"
3365 // //
3366 // // Return value: an array of DOM nodes
3367 // }
3368 //
3369 // [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
3370 //
3371 // function (script) {
3372 // // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
3373 // // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
3374 // }
3375 //
3376 // This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
3377 // If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
3378 // and then you don't need to override 'createJavaScriptEvaluatorBlock'.
3379
3380 ko.templateEngine = function () { };
3381
3382 ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
3383 throw new Error("Override renderTemplateSource");
3384 };
3385
3386 ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
3387 throw new Error("Override createJavaScriptEvaluatorBlock");
3388 };
3389
3390 ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
3391 // Named template
3392 if (typeof template == "string") {
3393 templateDocument = templateDocument || document;
3394 var elem = templateDocument.getElementById(template);
3395 if (!elem)
3396 throw new Error("Cannot find template with ID " + template);
3397 return new ko.templateSources.domElement(elem);
3398 } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
3399 // Anonymous template
3400 return new ko.templateSources.anonymousTemplate(template);
3401 } else
3402 throw new Error("Unknown template type: " + template);
3403 };
3404
3405 ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
3406 var templateSource = this['makeTemplateSource'](template, templateDocument);
3407 return this['renderTemplateSource'](templateSource, bindingContext, options);
3408 };
3409
3410 ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
3411 // Skip rewriting if requested
3412 if (this['allowTemplateRewriting'] === false)
3413 return true;
3414 return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
3415 };
3416
3417 ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
3418 var templateSource = this['makeTemplateSource'](template, templateDocument);
3419 var rewritten = rewriterCallback(templateSource['text']());
3420 templateSource['text'](rewritten);
3421 templateSource['data']("isRewritten", true);
3422 };
3423
3424 ko.exportSymbol('templateEngine', ko.templateEngine);
3425
3426 ko.templateRewriting = (function () {
3427 var memoizeDataBindingAttributeSyntaxRegex = /(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi;
3428 var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
3429
3430 function validateDataBindValuesForRewriting(keyValueArray) {
3431 var allValidators = ko.expressionRewriting.bindingRewriteValidators;
3432 for (var i = 0; i < keyValueArray.length; i++) {
3433 var key = keyValueArray[i]['key'];
3434 if (allValidators.hasOwnProperty(key)) {
3435 var validator = allValidators[key];
3436
3437 if (typeof validator === "function") {
3438 var possibleErrorMessage = validator(keyValueArray[i]['value']);
3439 if (possibleErrorMessage)
3440 throw new Error(possibleErrorMessage);
3441 } else if (!validator) {
3442 throw new Error("This template engine does not support the '" + key + "' binding within its templates");
3443 }
3444 }
3445 }
3446 }
3447
3448 function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, nodeName, templateEngine) {
3449 var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
3450 validateDataBindValuesForRewriting(dataBindKeyValueArray);
3451 var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray, {'valueAccessors':true});
3452
3453 // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
3454 // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
3455 // extra indirection.
3456 var applyBindingsToNextSiblingScript =
3457 "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()},'" + nodeName.toLowerCase() + "')";
3458 return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
3459 }
3460
3461 return {
3462 ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
3463 if (!templateEngine['isTemplateRewritten'](template, templateDocument))
3464 templateEngine['rewriteTemplate'](template, function (htmlString) {
3465 return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
3466 }, templateDocument);
3467 },
3468
3469 memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
3470 return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
3471 return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[4], /* tagToRetain: */ arguments[1], /* nodeName: */ arguments[2], templateEngine);
3472 }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
3473 return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", /* nodeName: */ "#comment", templateEngine);
3474 });
3475 },
3476
3477 applyMemoizedBindingsToNextSibling: function (bindings, nodeName) {
3478 return ko.memoization.memoize(function (domNode, bindingContext) {
3479 var nodeToBind = domNode.nextSibling;
3480 if (nodeToBind && nodeToBind.nodeName.toLowerCase() === nodeName) {
3481 ko.applyBindingAccessorsToNode(nodeToBind, bindings, bindingContext);
3482 }
3483 });
3484 }
3485 }
3486 })();
3487
3488
3489 // Exported only because it has to be referenced by string lookup from within rewritten template
3490 ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
3491 (function() {
3492 // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
3493 // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
3494 //
3495 // Two are provided by default:
3496 // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
3497 // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
3498 // without reading/writing the actual element text content, since it will be overwritten
3499 // with the rendered template output.
3500 // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
3501 // Template sources need to have the following functions:
3502 // text() - returns the template text from your storage location
3503 // text(value) - writes the supplied template text to your storage location
3504 // data(key) - reads values stored using data(key, value) - see below
3505 // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
3506 //
3507 // Optionally, template sources can also have the following functions:
3508 // nodes() - returns a DOM element containing the nodes of this template, where available
3509 // nodes(value) - writes the given DOM element to your storage location
3510 // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
3511 // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
3512 //
3513 // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
3514 // using and overriding "makeTemplateSource" to return an instance of your custom template source.
3515
3516 ko.templateSources = {};
3517
3518 // ---- ko.templateSources.domElement -----
3519
3520 ko.templateSources.domElement = function(element) {
3521 this.domElement = element;
3522 }
3523
3524 ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
3525 var tagNameLower = ko.utils.tagNameLower(this.domElement),
3526 elemContentsProperty = tagNameLower === "script" ? "text"
3527 : tagNameLower === "textarea" ? "value"
3528 : "innerHTML";
3529
3530 if (arguments.length == 0) {
3531 return this.domElement[elemContentsProperty];
3532 } else {
3533 var valueToWrite = arguments[0];
3534 if (elemContentsProperty === "innerHTML")
3535 ko.utils.setHtml(this.domElement, valueToWrite);
3536 else
3537 this.domElement[elemContentsProperty] = valueToWrite;
3538 }
3539 };
3540
3541 var dataDomDataPrefix = ko.utils.domData.nextKey() + "_";
3542 ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
3543 if (arguments.length === 1) {
3544 return ko.utils.domData.get(this.domElement, dataDomDataPrefix + key);
3545 } else {
3546 ko.utils.domData.set(this.domElement, dataDomDataPrefix + key, arguments[1]);
3547 }
3548 };
3549
3550 // ---- ko.templateSources.anonymousTemplate -----
3551 // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
3552 // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
3553 // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
3554
3555 var anonymousTemplatesDomDataKey = ko.utils.domData.nextKey();
3556 ko.templateSources.anonymousTemplate = function(element) {
3557 this.domElement = element;
3558 }
3559 ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
3560 ko.templateSources.anonymousTemplate.prototype.constructor = ko.templateSources.anonymousTemplate;
3561 ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
3562 if (arguments.length == 0) {
3563 var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
3564 if (templateData.textData === undefined && templateData.containerData)
3565 templateData.textData = templateData.containerData.innerHTML;
3566 return templateData.textData;
3567 } else {
3568 var valueToWrite = arguments[0];
3569 ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
3570 }
3571 };
3572 ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
3573 if (arguments.length == 0) {
3574 var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
3575 return templateData.containerData;
3576 } else {
3577 var valueToWrite = arguments[0];
3578 ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
3579 }
3580 };
3581
3582 ko.exportSymbol('templateSources', ko.templateSources);
3583 ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
3584 ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
3585 })();
3586 (function () {
3587 var _templateEngine;
3588 ko.setTemplateEngine = function (templateEngine) {
3589 if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
3590 throw new Error("templateEngine must inherit from ko.templateEngine");
3591 _templateEngine = templateEngine;
3592 }
3593
3594 function invokeForEachNodeInContinuousRange(firstNode, lastNode, action) {
3595 var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
3596 while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
3597 nextInQueue = ko.virtualElements.nextSibling(node);
3598 action(node, nextInQueue);
3599 }
3600 }
3601
3602 function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
3603 // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
3604 // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
3605 // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
3606 // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
3607 // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
3608
3609 if (continuousNodeArray.length) {
3610 var firstNode = continuousNodeArray[0],
3611 lastNode = continuousNodeArray[continuousNodeArray.length - 1],
3612 parentNode = firstNode.parentNode,
3613 provider = ko.bindingProvider['instance'],
3614 preprocessNode = provider['preprocessNode'];
3615
3616 if (preprocessNode) {
3617 invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node, nextNodeInRange) {
3618 var nodePreviousSibling = node.previousSibling;
3619 var newNodes = preprocessNode.call(provider, node);
3620 if (newNodes) {
3621 if (node === firstNode)
3622 firstNode = newNodes[0] || nextNodeInRange;
3623 if (node === lastNode)
3624 lastNode = newNodes[newNodes.length - 1] || nodePreviousSibling;
3625 }
3626 });
3627
3628 // Because preprocessNode can change the nodes, including the first and last nodes, update continuousNodeArray to match.
3629 // We need the full set, including inner nodes, because the unmemoize step might remove the first node (and so the real
3630 // first node needs to be in the array).
3631 continuousNodeArray.length = 0;
3632 if (!firstNode) { // preprocessNode might have removed all the nodes, in which case there's nothing left to do
3633 return;
3634 }
3635 if (firstNode === lastNode) {
3636 continuousNodeArray.push(firstNode);
3637 } else {
3638 continuousNodeArray.push(firstNode, lastNode);
3639 ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
3640 }
3641 }
3642
3643 // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
3644 // whereas a regular applyBindings won't introduce new memoized nodes
3645 invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
3646 if (node.nodeType === 1 || node.nodeType === 8)
3647 ko.applyBindings(bindingContext, node);
3648 });
3649 invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
3650 if (node.nodeType === 1 || node.nodeType === 8)
3651 ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
3652 });
3653
3654 // Make sure any changes done by applyBindings or unmemoize are reflected in the array
3655 ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
3656 }
3657 }
3658
3659 function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
3660 return nodeOrNodeArray.nodeType ? nodeOrNodeArray
3661 : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
3662 : null;
3663 }
3664
3665 function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
3666 options = options || {};
3667 var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
3668 var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
3669 var templateEngineToUse = (options['templateEngine'] || _templateEngine);
3670 ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
3671 var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
3672
3673 // Loosely check result is an array of DOM nodes
3674 if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
3675 throw new Error("Template engine must return an array of DOM nodes");
3676
3677 var haveAddedNodesToParent = false;
3678 switch (renderMode) {
3679 case "replaceChildren":
3680 ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
3681 haveAddedNodesToParent = true;
3682 break;
3683 case "replaceNode":
3684 ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
3685 haveAddedNodesToParent = true;
3686 break;
3687 case "ignoreTargetNode": break;
3688 default:
3689 throw new Error("Unknown renderMode: " + renderMode);
3690 }
3691
3692 if (haveAddedNodesToParent) {
3693 activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
3694 if (options['afterRender'])
3695 ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
3696 }
3697
3698 return renderedNodesArray;
3699 }
3700
3701 ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
3702 options = options || {};
3703 if ((options['templateEngine'] || _templateEngine) == undefined)
3704 throw new Error("Set a template engine before calling renderTemplate");
3705 renderMode = renderMode || "replaceChildren";
3706
3707 if (targetNodeOrNodeArray) {
3708 var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
3709
3710 var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
3711 var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
3712
3713 return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
3714 function () {
3715 // Ensure we've got a proper binding context to work with
3716 var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
3717 ? dataOrBindingContext
3718 : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
3719
3720 // Support selecting template as a function of the data being rendered
3721 var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
3722
3723 var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
3724 if (renderMode == "replaceNode") {
3725 targetNodeOrNodeArray = renderedNodesArray;
3726 firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
3727 }
3728 },
3729 null,
3730 { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
3731 );
3732 } else {
3733 // 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
3734 return ko.memoization.memoize(function (domNode) {
3735 ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
3736 });
3737 }
3738 };
3739
3740 ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
3741 // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
3742 // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
3743 var arrayItemContext;
3744
3745 // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
3746 var executeTemplateForArrayItem = function (arrayValue, index) {
3747 // Support selecting template as a function of the data being rendered
3748 arrayItemContext = parentBindingContext['createChildContext'](arrayValue, options['as'], function(context) {
3749 context['$index'] = index;
3750 });
3751 var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
3752 return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
3753 }
3754
3755 // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
3756 var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
3757 activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
3758 if (options['afterRender'])
3759 options['afterRender'](addedNodesArray, arrayValue);
3760 };
3761
3762 return ko.dependentObservable(function () {
3763 var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
3764 if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
3765 unwrappedArray = [unwrappedArray];
3766
3767 // Filter out any entries marked as destroyed
3768 var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
3769 return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
3770 });
3771
3772 // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
3773 // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
3774 ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
3775
3776 }, null, { disposeWhenNodeIsRemoved: targetNode });
3777 };
3778
3779 var templateComputedDomDataKey = ko.utils.domData.nextKey();
3780 function disposeOldComputedAndStoreNewOne(element, newComputed) {
3781 var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
3782 if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
3783 oldComputed.dispose();
3784 ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
3785 }
3786
3787 ko.bindingHandlers['template'] = {
3788 'init': function(element, valueAccessor) {
3789 // Support anonymous templates
3790 var bindingValue = ko.utils.unwrapObservable(valueAccessor());
3791 if (typeof bindingValue == "string" || bindingValue['name']) {
3792 // It's a named template - clear the element
3793 ko.virtualElements.emptyNode(element);
3794 } else {
3795 // It's an anonymous template - store the element contents, then clear the element
3796 var templateNodes = ko.virtualElements.childNodes(element),
3797 container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
3798 new ko.templateSources.anonymousTemplate(element)['nodes'](container);
3799 }
3800 return { 'controlsDescendantBindings': true };
3801 },
3802 'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
3803 var templateName = ko.utils.unwrapObservable(valueAccessor()),
3804 options = {},
3805 shouldDisplay = true,
3806 dataValue,
3807 templateComputed = null;
3808
3809 if (typeof templateName != "string") {
3810 options = templateName;
3811 templateName = ko.utils.unwrapObservable(options['name']);
3812
3813 // Support "if"/"ifnot" conditions
3814 if ('if' in options)
3815 shouldDisplay = ko.utils.unwrapObservable(options['if']);
3816 if (shouldDisplay && 'ifnot' in options)
3817 shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
3818
3819 dataValue = ko.utils.unwrapObservable(options['data']);
3820 }
3821
3822 if ('foreach' in options) {
3823 // Render once for each data point (treating data set as empty if shouldDisplay==false)
3824 var dataArray = (shouldDisplay && options['foreach']) || [];
3825 templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
3826 } else if (!shouldDisplay) {
3827 ko.virtualElements.emptyNode(element);
3828 } else {
3829 // Render once for this single data point (or use the viewModel if no data was provided)
3830 var innerBindingContext = ('data' in options) ?
3831 bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
3832 bindingContext; // Given no explicit 'data' value, we retain the same binding context
3833 templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
3834 }
3835
3836 // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
3837 disposeOldComputedAndStoreNewOne(element, templateComputed);
3838 }
3839 };
3840
3841 // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
3842 ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
3843 var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
3844
3845 if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
3846 return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
3847
3848 if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
3849 return null; // Named templates can be rewritten, so return "no error"
3850 return "This template engine does not support anonymous templates nested within its templates";
3851 };
3852
3853 ko.virtualElements.allowedBindings['template'] = true;
3854 })();
3855
3856 ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
3857 ko.exportSymbol('renderTemplate', ko.renderTemplate);
3858
3859 ko.utils.compareArrays = (function () {
3860 var statusNotInOld = 'added', statusNotInNew = 'deleted';
3861
3862 // Simple calculation based on Levenshtein distance.
3863 function compareArrays(oldArray, newArray, options) {
3864 // For backward compatibility, if the third arg is actually a bool, interpret
3865 // it as the old parameter 'dontLimitMoves'. Newer code should use { dontLimitMoves: true }.
3866 options = (typeof options === 'boolean') ? { 'dontLimitMoves': options } : (options || {});
3867 oldArray = oldArray || [];
3868 newArray = newArray || [];
3869
3870 if (oldArray.length <= newArray.length)
3871 return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, options);
3872 else
3873 return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, options);
3874 }
3875
3876 function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, options) {
3877 var myMin = Math.min,
3878 myMax = Math.max,
3879 editDistanceMatrix = [],
3880 smlIndex, smlIndexMax = smlArray.length,
3881 bigIndex, bigIndexMax = bigArray.length,
3882 compareRange = (bigIndexMax - smlIndexMax) || 1,
3883 maxDistance = smlIndexMax + bigIndexMax + 1,
3884 thisRow, lastRow,
3885 bigIndexMaxForRow, bigIndexMinForRow;
3886
3887 for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
3888 lastRow = thisRow;
3889 editDistanceMatrix.push(thisRow = []);
3890 bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
3891 bigIndexMinForRow = myMax(0, smlIndex - 1);
3892 for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
3893 if (!bigIndex)
3894 thisRow[bigIndex] = smlIndex + 1;
3895 else if (!smlIndex) // Top row - transform empty array into new array via additions
3896 thisRow[bigIndex] = bigIndex + 1;
3897 else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
3898 thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
3899 else {
3900 var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
3901 var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
3902 thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
3903 }
3904 }
3905 }
3906
3907 var editScript = [], meMinusOne, notInSml = [], notInBig = [];
3908 for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
3909 meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
3910 if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
3911 notInSml.push(editScript[editScript.length] = { // added
3912 'status': statusNotInSml,
3913 'value': bigArray[--bigIndex],
3914 'index': bigIndex });
3915 } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
3916 notInBig.push(editScript[editScript.length] = { // deleted
3917 'status': statusNotInBig,
3918 'value': smlArray[--smlIndex],
3919 'index': smlIndex });
3920 } else {
3921 --bigIndex;
3922 --smlIndex;
3923 if (!options['sparse']) {
3924 editScript.push({
3925 'status': "retained",
3926 'value': bigArray[bigIndex] });
3927 }
3928 }
3929 }
3930
3931 if (notInSml.length && notInBig.length) {
3932 // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
3933 // smlIndexMax keeps the time complexity of this algorithm linear.
3934 var limitFailedCompares = smlIndexMax * 10, failedCompares,
3935 a, d, notInSmlItem, notInBigItem;
3936 // Go through the items that have been added and deleted and try to find matches between them.
3937 for (failedCompares = a = 0; (options['dontLimitMoves'] || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
3938 for (d = 0; notInBigItem = notInBig[d]; d++) {
3939 if (notInSmlItem['value'] === notInBigItem['value']) {
3940 notInSmlItem['moved'] = notInBigItem['index'];
3941 notInBigItem['moved'] = notInSmlItem['index'];
3942 notInBig.splice(d,1); // This item is marked as moved; so remove it from notInBig list
3943 failedCompares = d = 0; // Reset failed compares count because we're checking for consecutive failures
3944 break;
3945 }
3946 }
3947 failedCompares += d;
3948 }
3949 }
3950 return editScript.reverse();
3951 }
3952
3953 return compareArrays;
3954 })();
3955
3956 ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
3957
3958 (function () {
3959 // Objective:
3960 // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
3961 // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
3962 // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
3963 // 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
3964 // previously mapped - retain those nodes, and just insert/delete other ones
3965
3966 // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
3967 // You can use this, for example, to activate bindings on those nodes.
3968
3969 function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
3970 // Map this array value inside a dependentObservable so we re-map when any dependency changes
3971 var mappedNodes = [];
3972 var dependentObservable = ko.dependentObservable(function() {
3973 var newMappedNodes = mapping(valueToMap, index, ko.utils.fixUpContinuousNodeArray(mappedNodes, containerNode)) || [];
3974
3975 // On subsequent evaluations, just replace the previously-inserted DOM nodes
3976 if (mappedNodes.length > 0) {
3977 ko.utils.replaceDomNodes(mappedNodes, newMappedNodes);
3978 if (callbackAfterAddingNodes)
3979 ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
3980 }
3981
3982 // Replace the contents of the mappedNodes array, thereby updating the record
3983 // of which nodes would be deleted if valueToMap was itself later removed
3984 mappedNodes.splice(0, mappedNodes.length);
3985 ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
3986 }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return !ko.utils.anyDomNodeIsAttachedToDocument(mappedNodes); } });
3987 return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
3988 }
3989
3990 var lastMappingResultDomDataKey = ko.utils.domData.nextKey();
3991
3992 ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
3993 // Compare the provided array against the previous one
3994 array = array || [];
3995 options = options || {};
3996 var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
3997 var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
3998 var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
3999 var editScript = ko.utils.compareArrays(lastArray, array, options['dontLimitMoves']);
4000
4001 // Build the new mapping result
4002 var newMappingResult = [];
4003 var lastMappingResultIndex = 0;
4004 var newMappingResultIndex = 0;
4005
4006 var nodesToDelete = [];
4007 var itemsToProcess = [];
4008 var itemsForBeforeRemoveCallbacks = [];
4009 var itemsForMoveCallbacks = [];
4010 var itemsForAfterAddCallbacks = [];
4011 var mapData;
4012
4013 function itemMovedOrRetained(editScriptIndex, oldPosition) {
4014 mapData = lastMappingResult[oldPosition];
4015 if (newMappingResultIndex !== oldPosition)
4016 itemsForMoveCallbacks[editScriptIndex] = mapData;
4017 // Since updating the index might change the nodes, do so before calling fixUpContinuousNodeArray
4018 mapData.indexObservable(newMappingResultIndex++);
4019 ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode);
4020 newMappingResult.push(mapData);
4021 itemsToProcess.push(mapData);
4022 }
4023
4024 function callCallback(callback, items) {
4025 if (callback) {
4026 for (var i = 0, n = items.length; i < n; i++) {
4027 if (items[i]) {
4028 ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
4029 callback(node, i, items[i].arrayEntry);
4030 });
4031 }
4032 }
4033 }
4034 }
4035
4036 for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
4037 movedIndex = editScriptItem['moved'];
4038 switch (editScriptItem['status']) {
4039 case "deleted":
4040 if (movedIndex === undefined) {
4041 mapData = lastMappingResult[lastMappingResultIndex];
4042
4043 // Stop tracking changes to the mapping for these nodes
4044 if (mapData.dependentObservable)
4045 mapData.dependentObservable.dispose();
4046
4047 // Queue these nodes for later removal
4048 nodesToDelete.push.apply(nodesToDelete, ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode));
4049 if (options['beforeRemove']) {
4050 itemsForBeforeRemoveCallbacks[i] = mapData;
4051 itemsToProcess.push(mapData);
4052 }
4053 }
4054 lastMappingResultIndex++;
4055 break;
4056
4057 case "retained":
4058 itemMovedOrRetained(i, lastMappingResultIndex++);
4059 break;
4060
4061 case "added":
4062 if (movedIndex !== undefined) {
4063 itemMovedOrRetained(i, movedIndex);
4064 } else {
4065 mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
4066 newMappingResult.push(mapData);
4067 itemsToProcess.push(mapData);
4068 if (!isFirstExecution)
4069 itemsForAfterAddCallbacks[i] = mapData;
4070 }
4071 break;
4072 }
4073 }
4074
4075 // Call beforeMove first before any changes have been made to the DOM
4076 callCallback(options['beforeMove'], itemsForMoveCallbacks);
4077
4078 // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
4079 ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
4080
4081 // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
4082 for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
4083 // Get nodes for newly added items
4084 if (!mapData.mappedNodes)
4085 ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
4086
4087 // Put nodes in the right place if they aren't there already
4088 for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
4089 if (node !== nextNode)
4090 ko.virtualElements.insertAfter(domNode, node, lastNode);
4091 }
4092
4093 // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
4094 if (!mapData.initialized && callbackAfterAddingNodes) {
4095 callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
4096 mapData.initialized = true;
4097 }
4098 }
4099
4100 // If there's a beforeRemove callback, call it after reordering.
4101 // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
4102 // some sort of animation, which is why we first reorder the nodes that will be removed. If the
4103 // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
4104 // Perhaps we'll make that change in the future if this scenario becomes more common.
4105 callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
4106
4107 // Finally call afterMove and afterAdd callbacks
4108 callCallback(options['afterMove'], itemsForMoveCallbacks);
4109 callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
4110
4111 // Store a copy of the array items we just considered so we can difference it next time
4112 ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
4113 }
4114 })();
4115
4116 ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
4117 ko.nativeTemplateEngine = function () {
4118 this['allowTemplateRewriting'] = false;
4119 }
4120
4121 ko.nativeTemplateEngine.prototype = new ko.templateEngine();
4122 ko.nativeTemplateEngine.prototype.constructor = ko.nativeTemplateEngine;
4123 ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
4124 var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
4125 templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
4126 templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
4127
4128 if (templateNodes) {
4129 return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
4130 } else {
4131 var templateText = templateSource['text']();
4132 return ko.utils.parseHtmlFragment(templateText);
4133 }
4134 };
4135
4136 ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
4137 ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
4138
4139 ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
4140 (function() {
4141 ko.jqueryTmplTemplateEngine = function () {
4142 // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
4143 // doesn't expose a version number, so we have to infer it.
4144 // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
4145 // which KO internally refers to as version "2", so older versions are no longer detected.
4146 var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
4147 if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
4148 return 0;
4149 // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
4150 try {
4151 if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
4152 // Since 1.0.0pre, custom tags should append markup to an array called "__"
4153 return 2; // Final version of jquery.tmpl
4154 }
4155 } catch(ex) { /* Apparently not the version we were looking for */ }
4156
4157 return 1; // Any older version that we don't support
4158 })();
4159
4160 function ensureHasReferencedJQueryTemplates() {
4161 if (jQueryTmplVersion < 2)
4162 throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
4163 }
4164
4165 function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
4166 return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
4167 }
4168
4169 this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
4170 options = options || {};
4171 ensureHasReferencedJQueryTemplates();
4172
4173 // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
4174 var precompiled = templateSource['data']('precompiled');
4175 if (!precompiled) {
4176 var templateText = templateSource['text']() || "";
4177 // Wrap in "with($whatever.koBindingContext) { ... }"
4178 templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
4179
4180 precompiled = jQuery['template'](null, templateText);
4181 templateSource['data']('precompiled', precompiled);
4182 }
4183
4184 var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
4185 var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
4186
4187 var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
4188 resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
4189
4190 jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
4191 return resultNodes;
4192 };
4193
4194 this['createJavaScriptEvaluatorBlock'] = function(script) {
4195 return "{{ko_code ((function() { return " + script + " })()) }}";
4196 };
4197
4198 this['addTemplate'] = function(templateName, templateMarkup) {
4199 document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "<" + "/script>");
4200 };
4201
4202 if (jQueryTmplVersion > 0) {
4203 jQuery['tmpl']['tag']['ko_code'] = {
4204 open: "__.push($1 || '');"
4205 };
4206 jQuery['tmpl']['tag']['ko_with'] = {
4207 open: "with($1) {",
4208 close: "} "
4209 };
4210 }
4211 };
4212
4213 ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
4214 ko.jqueryTmplTemplateEngine.prototype.constructor = ko.jqueryTmplTemplateEngine;
4215
4216 // Use this one by default *only if jquery.tmpl is referenced*
4217 var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
4218 if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
4219 ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
4220
4221 ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
4222 })();
4223 }));
4224 }());
4225 })();