-
Notifications
You must be signed in to change notification settings - Fork 1
/
knockout.js
1918 lines (1689 loc) · 87.7 KB
/
knockout.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Knockout JavaScript library v1.2.0pre
// (c) 2010 Steven Sanderson - http://knockoutjs.com/
// License: Ms-Pl (http://www.opensource.org/licenses/ms-pl.html)
(function(window,undefined){
var ko = window["ko"] = {};
// Google Closure Compiler helpers (used only to make the minified file smaller)
ko.exportSymbol = function(publicPath, object) {
var tokens = publicPath.split(".");
var target = window;
for (var i = 0; i < tokens.length - 1; i++)
target = target[tokens[i]];
target[tokens[tokens.length - 1]] = object;
};
ko.exportProperty = function(owner, publicName, object) {
owner[publicName] = object;
};
ko.utils = new (function () {
var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
var isIe6 = /MSIE 6/i.test(navigator.userAgent);
var isIe7 = /MSIE 7/i.test(navigator.userAgent);
return {
fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
arrayForEach: function (array, action) {
for (var i = 0, j = array.length; i < j; i++)
action(array[i]);
},
arrayIndexOf: function (array, item) {
if (typeof array.indexOf == "function")
return array.indexOf(item);
for (var i = 0, j = array.length; i < j; i++)
if (array[i] == item)
return i;
return -1;
},
arrayFirst: function (array, predicate, predicateOwner) {
for (var i = 0, j = array.length; i < j; i++)
if (predicate.call(predicateOwner, array[i]))
return array[i];
return null;
},
arrayRemoveItem: function (array, itemToRemove) {
var index = ko.utils.arrayIndexOf(array, itemToRemove);
if (index >= 0)
array.splice(index, 1);
},
arrayGetDistinctValues: function (array) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++) {
if (ko.utils.arrayIndexOf(result, array[i]) < 0)
result.push(array[i]);
}
return result;
},
arrayMap: function (array, mapping) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++)
result.push(mapping(array[i]));
return result;
},
arrayFilter: function (array, predicate) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++)
if (predicate(array[i]))
result.push(array[i]);
return result;
},
arrayPushAll: function (array, valuesToPush) {
for (var i = 0, j = valuesToPush.length; i < j; i++)
array.push(valuesToPush[i]);
},
emptyDomNode: function (domNode) {
while (domNode.firstChild) {
ko.utils.domData.cleanNodeAndDescendants(domNode.firstChild);
domNode.removeChild(domNode.firstChild);
}
},
setDomNodeChildren: function (domNode, childNodes) {
ko.utils.emptyDomNode(domNode);
if (childNodes) {
ko.utils.arrayForEach(childNodes, function (childNode) {
domNode.appendChild(childNode);
});
}
},
replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
if (nodesToReplaceArray.length > 0) {
var insertionPoint = nodesToReplaceArray[0];
var parent = insertionPoint.parentNode;
for (var i = 0, j = newNodesArray.length; i < j; i++)
parent.insertBefore(newNodesArray[i], insertionPoint);
for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
ko.utils.domData.cleanNodeAndDescendants(nodesToReplaceArray[i]);
parent.removeChild(nodesToReplaceArray[i]);
}
}
},
setOptionNodeSelectionState: function (optionNode, isSelected) {
// IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
if (navigator.userAgent.indexOf("MSIE 6") >= 0)
optionNode.setAttribute("selected", isSelected);
else
optionNode.selected = isSelected;
},
getElementsHavingAttribute: function (rootNode, attributeName) {
if ((!rootNode) || (rootNode.nodeType != 1)) return [];
var results = [];
if (rootNode.getAttribute(attributeName) !== null)
results.push(rootNode);
var descendants = rootNode.getElementsByTagName("*");
for (var i = 0, j = descendants.length; i < j; i++)
if (descendants[i].getAttribute(attributeName) !== null)
results.push(descendants[i]);
return results;
},
stringTrim: function (string) {
return (string || "").replace(stringTrimRegex, "");
},
stringTokenize: function (string, delimiter) {
var result = [];
var tokens = (string || "").split(delimiter);
for (var i = 0, j = tokens.length; i < j; i++) {
var trimmed = ko.utils.stringTrim(tokens[i]);
if (trimmed !== "")
result.push(trimmed);
}
return result;
},
stringStartsWith: function (string, startsWith) {
string = string || "";
if (startsWith.length > string.length)
return false;
return string.substring(0, startsWith.length) === startsWith;
},
evalWithinScope: function (expression, scope) {
if (scope === undefined)
return (new Function("return " + expression))();
with (scope) { return eval("(" + expression + ")"); }
},
domNodeIsContainedBy: function (node, containedByNode) {
if (containedByNode.compareDocumentPosition)
return (containedByNode.compareDocumentPosition(node) & 16) == 16;
while (node != null) {
if (node == containedByNode)
return true;
node = node.parentNode;
}
return false;
},
domNodeIsAttachedToDocument: function (node) {
return ko.utils.domNodeIsContainedBy(node, document);
},
registerEventHandler: function (element, eventType, handler) {
if (typeof jQuery != "undefined")
jQuery(element)['bind'](eventType, handler);
else if (typeof element.addEventListener == "function")
element.addEventListener(eventType, handler, false);
else if (typeof element.attachEvent != "undefined")
element.attachEvent("on" + eventType, function (event) {
handler.call(element, event);
});
else
throw new Error("Browser doesn't support addEventListener or attachEvent");
},
triggerEvent: function (element, eventType) {
if (!(element && element.nodeType))
throw new Error("element must be a DOM node when calling triggerEvent");
if (typeof document.createEvent == "function") {
if (typeof element.dispatchEvent == "function") {
var eventCategory = (eventType == "click" ? "MouseEvents" : "HTMLEvents"); // Might need to account for other event names at some point
var event = document.createEvent(eventCategory);
event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
element.dispatchEvent(event);
}
else
throw new Error("The supplied element doesn't support dispatchEvent");
} else if (typeof element.fireEvent != "undefined") {
// Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
// so to make it consistent, we'll do it manually here
if (eventType == "click") {
if ((element.tagName == "INPUT") && ((element.type.toLowerCase() == "checkbox") || (element.type.toLowerCase() == "radio")))
element.checked = element.checked !== true;
}
element.fireEvent("on" + eventType);
}
else
throw new Error("Browser doesn't support triggering events");
},
unwrapObservable: function (value) {
return ko.isObservable(value) ? value() : value;
},
domNodeHasCssClass: function (node, className) {
var currentClassNames = (node.className || "").split(/\s+/);
return ko.utils.arrayIndexOf(currentClassNames, className) >= 0;
},
toggleDomNodeCssClass: function (node, className, shouldHaveClass) {
var hasClass = ko.utils.domNodeHasCssClass(node, className);
if (shouldHaveClass && !hasClass) {
node.className = (node.className || "") + " " + className;
} else if (hasClass && !shouldHaveClass) {
var currentClassNames = (node.className || "").split(/\s+/);
var newClassName = "";
for (var i = 0; i < currentClassNames.length; i++)
if (currentClassNames[i] != className)
newClassName += currentClassNames[i] + " ";
node.className = ko.utils.stringTrim(newClassName);
}
},
range: function (min, max) {
min = ko.utils.unwrapObservable(min);
max = ko.utils.unwrapObservable(max);
var result = [];
for (var i = min; i <= max; i++)
result.push(i);
return result;
},
makeArray: function(arrayLikeObject) {
var result = [];
for (var i = arrayLikeObject.length - 1; i >= 0; i--){
result.push(arrayLikeObject[i]);
};
return result;
},
isIe6 : isIe6,
isIe7 : isIe7,
getFormFields: function(form, fieldName) {
var fields = ko.utils.makeArray(form.getElementsByTagName("INPUT")).concat(ko.utils.makeArray(form.getElementsByTagName("TEXTAREA")));
var isMatchingField = (typeof fieldName == 'string')
? function(field) { return field.name === fieldName }
: function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
var matches = [];
for (var i = fields.length - 1; i >= 0; i--) {
if (isMatchingField(fields[i]))
matches.push(fields[i]);
};
return matches;
},
parseJson: function (jsonString) {
if (typeof jsonString == "string") {
jsonString = ko.utils.stringTrim(jsonString);
if (jsonString) {
if (window.JSON && window.JSON.parse) // Use native parsing where available
return window.JSON.parse(jsonString);
return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
}
}
return null;
},
stringifyJson: function (data) {
if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
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");
return JSON.stringify(ko.utils.unwrapObservable(data));
},
postJson: function (urlOrForm, data, options) {
options = options || {};
var params = options['params'] || {};
var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
var url = urlOrForm;
// If we were given a form, use its 'action' URL and pick out any requested field values
if((typeof urlOrForm == 'object') && (urlOrForm.tagName == "FORM")) {
var originalForm = urlOrForm;
url = originalForm.action;
for (var i = includeFields.length - 1; i >= 0; i--) {
var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
for (var j = fields.length - 1; j >= 0; j--)
params[fields[j].name] = fields[j].value;
}
}
data = ko.utils.unwrapObservable(data);
var form = document.createElement("FORM");
form.style.display = "none";
form.action = url;
form.method = "post";
for (var key in data) {
var input = document.createElement("INPUT");
input.name = key;
input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
form.appendChild(input);
}
for (var key in params) {
var input = document.createElement("INPUT");
input.name = key;
input.value = params[key];
form.appendChild(input);
}
document.body.appendChild(form);
options['submitter'] ? options['submitter'](form) : form.submit();
setTimeout(function () { form.parentNode.removeChild(form); }, 0);
},
domData: {
uniqueId: 0,
dataStoreKeyExpandoPropertyName: "__ko__" + (new Date).getTime(),
dataStore: {},
get: function (node, key) {
var allDataForNode = ko.utils.domData.getAll(node, false);
return allDataForNode === undefined ? undefined : allDataForNode[key];
},
set: function (node, key, value) {
var allDataForNode = ko.utils.domData.getAll(node, true);
allDataForNode[key] = value;
},
getAll: function (node, createIfNotFound) {
var dataStoreKey = node[ko.utils.domData.dataStoreKeyExpandoPropertyName];
if (!dataStoreKey) {
if (!createIfNotFound)
return undefined;
dataStoreKey = node[ko.utils.domData.dataStoreKeyExpandoPropertyName] = "ko" + ko.utils.domData.uniqueId++;
ko.utils.domData[dataStoreKey] = {};
}
return ko.utils.domData[dataStoreKey];
},
cleanNode: function (node) {
var dataStoreKey = node[ko.utils.domData.dataStoreKeyExpandoPropertyName];
if (dataStoreKey) {
delete ko.utils.domData[dataStoreKey];
node[ko.utils.domData.dataStoreKeyExpandoPropertyName] = null;
}
},
cleanNodeAndDescendants: function (node) {
if ((node.nodeType != 1) && (node.nodeType != 9))
return;
ko.utils.domData.cleanNode(node);
var descendants = node.getElementsByTagName("*");
for (var i = 0, j = descendants.length; i < j; i++)
ko.utils.domData.cleanNode(descendants[i]);
}
}
}
})();
ko.exportSymbol('ko.utils', ko.utils);
ko.exportSymbol('ko.utils.arrayForEach', ko.utils.arrayForEach);
ko.exportSymbol('ko.utils.arrayFirst', ko.utils.arrayFirst);
ko.exportSymbol('ko.utils.arrayFilter', ko.utils.arrayFilter);
ko.exportSymbol('ko.utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
ko.exportSymbol('ko.utils.arrayIndexOf', ko.utils.arrayIndexOf);
ko.exportSymbol('ko.utils.arrayMap', ko.utils.arrayMap);
ko.exportSymbol('ko.utils.arrayPushAll', ko.utils.arrayPushAll);
ko.exportSymbol('ko.utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
ko.exportSymbol('ko.utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
ko.exportSymbol('ko.utils.getFormFields', ko.utils.getFormFields);
ko.exportSymbol('ko.utils.postJson', ko.utils.postJson);
ko.exportSymbol('ko.utils.parseJson', ko.utils.parseJson);
ko.exportSymbol('ko.utils.registerEventHandler', ko.utils.registerEventHandler);
ko.exportSymbol('ko.utils.stringifyJson', ko.utils.stringifyJson);
ko.exportSymbol('ko.utils.range', ko.utils.range);
ko.exportSymbol('ko.utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
ko.exportSymbol('ko.utils.triggerEvent', ko.utils.triggerEvent);
ko.exportSymbol('ko.utils.unwrapObservable', ko.utils.unwrapObservable);
if (!Function.prototype['bind']) {
// 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)
// In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
Function.prototype['bind'] = function (object) {
var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
return function () {
return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
};
};
}
ko.memoization = (function () {
var memos = {};
function randomMax8HexChars() {
return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
}
function generateRandomId() {
return randomMax8HexChars() + randomMax8HexChars();
}
function findMemoNodes(rootNode, appendToArray) {
if (!rootNode)
return;
if (rootNode.nodeType == 8) {
var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
if (memoId != null)
appendToArray.push({ domNode: rootNode, memoId: memoId });
} else if (rootNode.nodeType == 1) {
for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
findMemoNodes(childNodes[i], appendToArray);
}
}
return {
memoize: function (callback) {
if (typeof callback != "function")
throw new Error("You can only pass a function to ko.memoization.memoize()");
var memoId = generateRandomId();
memos[memoId] = callback;
return "<!--[ko_memo:" + memoId + "]-->";
},
unmemoize: function (memoId, callbackParams) {
var callback = memos[memoId];
if (callback === undefined)
throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
try {
callback.apply(null, callbackParams || []);
return true;
}
finally { delete memos[memoId]; }
},
unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
var memos = [];
findMemoNodes(domNode, memos);
for (var i = 0, j = memos.length; i < j; i++) {
var node = memos[i].domNode;
var combinedParams = [node];
if (extraCallbackParamsArray)
ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
ko.memoization.unmemoize(memos[i].memoId, combinedParams);
node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
if (node.parentNode)
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)
}
},
parseMemoText: function (memoText) {
var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
return match ? match[1] : null;
}
};
})();
ko.exportSymbol('ko.memoization', ko.memoization);
ko.exportSymbol('ko.memoization.memoize', ko.memoization.memoize);
ko.exportSymbol('ko.memoization.unmemoize', ko.memoization.unmemoize);
ko.exportSymbol('ko.memoization.parseMemoText', ko.memoization.parseMemoText);
ko.exportSymbol('ko.memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
ko.subscription = function (callback, disposeCallback) {
this.callback = callback;
this.dispose = disposeCallback;
ko.exportProperty(this, 'dispose', this.dispose);
};
ko.subscribable = function () {
var _subscriptions = [];
this.subscribe = function (callback, callbackTarget) {
var boundCallback = callbackTarget ? function () { callback.call(callbackTarget) } : callback;
var subscription = new ko.subscription(boundCallback, function () {
ko.utils.arrayRemoveItem(_subscriptions, subscription);
});
_subscriptions.push(subscription);
return subscription;
};
this.notifySubscribers = function (valueToNotify) {
ko.utils.arrayForEach(_subscriptions.slice(0), function (subscription) {
if (subscription)
subscription.callback(valueToNotify);
});
};
this.getSubscriptionsCount = function () {
return _subscriptions.length;
};
ko.exportProperty(this, 'subscribe', this.subscribe);
ko.exportProperty(this, 'notifySubscribers', this.notifySubscribers);
ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
}
ko.isSubscribable = function (instance) {
return typeof instance.subscribe == "function" && typeof instance.notifySubscribers == "function";
};
ko.exportSymbol('ko.subscribable', ko.subscribable);
ko.exportSymbol('ko.isSubscribable', ko.isSubscribable);
ko.dependencyDetection = (function () {
var _detectedDependencies = [];
return {
begin: function () {
_detectedDependencies.push([]);
},
end: function () {
return _detectedDependencies.pop();
},
registerDependency: function (subscribable) {
if (!ko.isSubscribable(subscribable))
throw "Only subscribable things can act as dependencies";
if (_detectedDependencies.length > 0) {
_detectedDependencies[_detectedDependencies.length - 1].push(subscribable);
}
}
};
})();
ko.observable = function (initialValue) {
var _latestValue = initialValue;
function observable() {
if (arguments.length > 0) {
// Write
_latestValue = arguments[0];
if (arguments[1] !== false)
observable.notifySubscribers(_latestValue);
return this; // Permits chained assignments
}
else {
// Read
ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
return _latestValue;
}
}
observable.__ko_proto__ = ko.observable;
observable.valueHasMutated = function () { observable.notifySubscribers(_latestValue); }
ko.subscribable.call(observable);
ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
return observable;
}
ko.isObservable = function (instance) {
if ((instance === null) || (instance === undefined) || (instance.__ko_proto__ === undefined)) return false;
if (instance.__ko_proto__ === ko.observable) return true;
return ko.isObservable(instance.__ko_proto__); // Walk the prototype chain
}
ko.isWriteableObservable = function (instance) {
// Observable
if ((typeof instance == "function") && instance.__ko_proto__ === ko.observable)
return true;
// Writeable dependent observable
if ((typeof instance == "function") && (instance.__ko_proto__ === ko.dependentObservable) && (instance.hasWriteFunction))
return true;
// Anything else
return false;
}
ko.exportSymbol('ko.observable', ko.observable);
ko.exportSymbol('ko.isObservable', ko.isObservable);
ko.exportSymbol('ko.isWriteableObservable', ko.isWriteableObservable);
ko.observableArray = function (initialValues) {
var result = new ko.observable(initialValues);
ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
result[methodName] = function () {
var underlyingArray = result();
var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
result.valueHasMutated();
return methodCallResult;
};
});
ko.utils.arrayForEach(["slice"], function (methodName) {
result[methodName] = function () {
var underlyingArray = result();
return underlyingArray[methodName].apply(underlyingArray, arguments);
};
});
result.remove = function (valueOrPredicate) {
var underlyingArray = result();
var remainingValues = [];
var removedValues = [];
var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
for (var i = 0, j = underlyingArray.length; i < j; i++) {
var value = underlyingArray[i];
if (!predicate(value))
remainingValues.push(value);
else
removedValues.push(value);
}
result(remainingValues);
return removedValues;
};
result.removeAll = function (arrayOfValues) {
// If you passed zero args, we remove everything
if (arrayOfValues === undefined) {
var allValues = result();
result([]);
return allValues;
}
// If you passed an arg, we interpret it as an array of entries to remove
if (!arrayOfValues)
return [];
return result.remove(function (value) {
return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
});
};
result.destroy = function (valueOrPredicate) {
var underlyingArray = result();
var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
for (var i = underlyingArray.length - 1; i >= 0; i--) {
var value = underlyingArray[i];
if (predicate(value))
underlyingArray[i]["_destroy"] = true;
}
result.valueHasMutated();
};
result.destroyAll = function (arrayOfValues) {
// If you passed zero args, we destroy everything
if (arrayOfValues === undefined)
return result.destroy(function() { return true });
// If you passed an arg, we interpret it as an array of entries to destroy
if (!arrayOfValues)
return [];
return result.destroy(function (value) {
return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
});
};
result.indexOf = function (item) {
var underlyingArray = result();
return ko.utils.arrayIndexOf(underlyingArray, item);
};
result.replace = function(oldItem, newItem) {
var index = result.indexOf(oldItem);
if (index >= 0) {
result()[index] = newItem;
result.valueHasMutated();
}
};
ko.exportProperty(result, "remove", result.remove);
ko.exportProperty(result, "removeAll", result.removeAll);
ko.exportProperty(result, "destroy", result.destroy);
ko.exportProperty(result, "destroyAll", result.destroyAll);
ko.exportProperty(result, "indexOf", result.indexOf);
return result;
}
ko.exportSymbol('ko.observableArray', ko.observableArray);
ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
if (evaluatorFunctionOrOptions && typeof evaluatorFunctionOrOptions == "object") {
// Single-parameter syntax - everything is on this "options" param
options = evaluatorFunctionOrOptions;
} else {
// Multi-parameter syntax - construct the options according to the params passed
options = options || {};
options["read"] = evaluatorFunctionOrOptions || options["read"];
options["owner"] = evaluatorFunctionTarget || options["owner"];
}
// By here, "options" is always non-null
if (typeof options["read"] != "function")
throw "Pass a function that returns the value of the dependentObservable";
var _subscriptionsToDependencies = [];
function disposeAllSubscriptionsToDependencies() {
ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
subscription.dispose();
});
_subscriptionsToDependencies = [];
}
function replaceSubscriptionsToDependencies(newDependencies) {
disposeAllSubscriptionsToDependencies();
ko.utils.arrayForEach(newDependencies, function (dependency) {
_subscriptionsToDependencies.push(dependency.subscribe(evaluate));
});
};
var _latestValue, _hasBeenEvaluated = false;
function evaluate() {
// Don't dispose on first evaluation, because the "disposeWhen" callback might
// e.g., dispose when the associated DOM element isn't in the doc, and it's not
// going to be in the doc until *after* the first evaluation
if ((_hasBeenEvaluated) && typeof options["disposeWhen"] == "function") {
if (options["disposeWhen"]()) {
dependentObservable.dispose();
return;
}
}
try {
ko.dependencyDetection.begin();
_latestValue = options["owner"] ? options["read"].call(options["owner"]) : options["read"]();
} finally {
var distinctDependencies = ko.utils.arrayGetDistinctValues(ko.dependencyDetection.end());
replaceSubscriptionsToDependencies(distinctDependencies);
}
dependentObservable.notifySubscribers(_latestValue);
_hasBeenEvaluated = true;
}
function dependentObservable() {
if (arguments.length > 0) {
if (typeof options["write"] === "function") {
// Writing a value
var valueToWrite = arguments[0];
options["owner"] ? options["write"].call(options["owner"], valueToWrite) : options["write"](valueToWrite);
} else {
throw "Cannot write a value to a dependentObservable unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.";
}
} else {
// Reading the value
if (!_hasBeenEvaluated)
evaluate();
ko.dependencyDetection.registerDependency(dependentObservable);
return _latestValue;
}
}
dependentObservable.__ko_proto__ = ko.dependentObservable;
dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; }
dependentObservable.hasWriteFunction = typeof options["write"] === "function";
dependentObservable.dispose = function () {
disposeAllSubscriptionsToDependencies();
};
ko.subscribable.call(dependentObservable);
if (options['deferEvaluation'] !== true)
evaluate();
ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
return dependentObservable;
};
ko.dependentObservable.__ko_proto__ = ko.observable;
ko.exportSymbol('ko.dependentObservable', ko.dependentObservable);
(function() {
var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
ko.toJS = function(rootObject) {
if (arguments.length == 0)
throw new Error("When calling ko.toJS, pass the object you want to convert.");
// We just unwrap everything at every level in the object graph
return mapJsObjectGraph(rootObject, function(valueToMap) {
// Loop because an observable's value might in turn be another observable wrapper
for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
valueToMap = valueToMap();
return valueToMap;
});
};
ko.toJSON = function(rootObject) {
var plainJavaScriptObject = ko.toJS(rootObject);
return ko.utils.stringifyJson(plainJavaScriptObject);
};
function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
visitedObjects = visitedObjects || new objectLookup();
rootObject = mapInputCallback(rootObject);
var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined);
if (!canHaveProperties)
return rootObject;
var outputProperties = rootObject instanceof Array ? [] : {};
visitedObjects.save(rootObject, outputProperties);
visitPropertiesOrArrayEntries(rootObject, function(indexer) {
var propertyValue = mapInputCallback(rootObject[indexer]);
switch (typeof propertyValue) {
case "boolean":
case "number":
case "string":
case "function":
outputProperties[indexer] = propertyValue;
break;
case "object":
case "undefined":
var previouslyMappedValue = visitedObjects.get(propertyValue);
outputProperties[indexer] = (previouslyMappedValue !== undefined)
? previouslyMappedValue
: mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
break;
}
});
return outputProperties;
}
function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
if (rootObject instanceof Array) {
for (var i = 0; i < rootObject.length; i++)
visitorCallback(i);
} else {
for (var propertyName in rootObject)
visitorCallback(propertyName);
}
};
function objectLookup() {
var keys = [];
var values = [];
this.save = function(key, value) {
var existingIndex = ko.utils.arrayIndexOf(keys, key);
if (existingIndex >= 0)
values[existingIndex] = value;
else {
keys.push(key);
values.push(value);
}
};
this.get = function(key) {
var existingIndex = ko.utils.arrayIndexOf(keys, key);
return (existingIndex >= 0) ? values[existingIndex] : undefined;
};
};
})();
ko.exportSymbol('ko.toJS', ko.toJS);
ko.exportSymbol('ko.toJSON', ko.toJSON);(function () {
// Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
// are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
// that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
ko.selectExtensions = {
readValue : function(element) {
if (element.tagName == 'OPTION') {
if (element['__ko__hasDomDataOptionValue__'] === true)
return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
return element.getAttribute("value");
} else if (element.tagName == 'SELECT')
return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
else
return element.value;
},
writeValue: function(element, value) {
if (element.tagName == 'OPTION') {
switch(typeof value) {
case "string":
case "number":
ko.utils.domData.cleanNode(element);
if ('__ko__hasDomDataOptionValue__' in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
delete element['__ko__hasDomDataOptionValue__'];
}
element.value = value;
break;
default:
// Store arbitrary object using DomData
ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
element['__ko__hasDomDataOptionValue__'] = true;
element.value = "";
break;
}
} else if (element.tagName == 'SELECT') {
for (var i = element.options.length - 1; i >= 0; i--) {
if (ko.selectExtensions.readValue(element.options[i]) == value) {
element.selectedIndex = i;
break;
}
}
} else {
if ((value === null) || (value === undefined))
value = "";
element.value = value;
}
}
};
})();
ko.exportSymbol('ko.selectExtensions', ko.selectExtensions);
ko.exportSymbol('ko.selectExtensions.readValue', ko.selectExtensions.readValue);
ko.exportSymbol('ko.selectExtensions.writeValue', ko.selectExtensions.writeValue);
ko.jsonExpressionRewriting = (function () {
var restoreCapturedTokensRegex = /\[ko_token_(\d+)\]/g;
var javaScriptAssignmentTarget = /^[\_$a-z][\_$a-z0-9]*(\[.*?\])*(\.[\_$a-z][\_$a-z0-9]*(\[.*?\])*)*$/i;
var javaScriptReservedWords = ["true", "false"];
function restoreTokens(string, tokens) {
return string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
return tokens[tokenIndex];
});
}
function isWriteableValue(expression) {
if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
return false;
return expression.match(javaScriptAssignmentTarget) !== null;
}
return {
parseJson: function (jsonString) {
jsonString = ko.utils.stringTrim(jsonString);
if (jsonString.length < 3)
return {};
// We're going to split on commas, so first extract any blocks that may contain commas other than those at the top level
var tokens = [];
var tokenStart = null, tokenEndChar;
for (var position = jsonString.charAt(0) == "{" ? 1 : 0; position < jsonString.length; position++) {
var c = jsonString.charAt(position);
if (tokenStart === null) {
switch (c) {
case '"':
case "'":
case "/":
tokenStart = position;
tokenEndChar = c;
break;
case "{":
tokenStart = position;
tokenEndChar = "}";
break;
case "[":
tokenStart = position;
tokenEndChar = "]";
break;
}
} else if (c == tokenEndChar) {
var token = jsonString.substring(tokenStart, position + 1);
tokens.push(token);
var replacement = "[ko_token_" + (tokens.length - 1) + "]";
jsonString = jsonString.substring(0, tokenStart) + replacement + jsonString.substring(position + 1);
position -= (token.length - replacement.length);
tokenStart = null;
}
}
// Now we can safely split on commas to get the key/value pairs
var result = {};
var keyValuePairs = jsonString.split(",");
for (var i = 0, j = keyValuePairs.length; i < j; i++) {
var pair = keyValuePairs[i];
var colonPos = pair.indexOf(":");
if ((colonPos > 0) && (colonPos < pair.length - 1)) {
var key = ko.utils.stringTrim(pair.substring(0, colonPos));
var value = ko.utils.stringTrim(pair.substring(colonPos + 1));
if (key.charAt(0) == "{")
key = key.substring(1);
if (value.charAt(value.length - 1) == "}")
value = value.substring(0, value.length - 1);
key = ko.utils.stringTrim(restoreTokens(key, tokens));
value = ko.utils.stringTrim(restoreTokens(value, tokens));
result[key] = value;
}
}
return result;
},
insertPropertyAccessorsIntoJson: function (jsonString) {
var parsed = ko.jsonExpressionRewriting.parseJson(jsonString);
var propertyAccessorTokens = [];
for (var key in parsed) {
var value = parsed[key];
if (isWriteableValue(value)) {
if (propertyAccessorTokens.length > 0)
propertyAccessorTokens.push(", ");
propertyAccessorTokens.push(key + " : function(__ko_value) { " + value + " = __ko_value; }");
}
}
if (propertyAccessorTokens.length > 0) {
var allPropertyAccessors = propertyAccessorTokens.join("");