knockoutjs-rails 2.3.0 → 3.0.0

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