Repository navigation
Expand file tree
/
Copy pathtest-module.ts
More file actions
1475 lines (1173 loc) · 57.4 KB
/
Copy pathtest-module.ts
File metadata and controls
1475 lines (1173 loc) · 57.4 KB
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
import * as ko from "knockout";
declare var $: any;
function test_creatingVMs() {
const myViewModel = {
personName: ko.observable('Bob'),
personAge: ko.observable(123)
};
ko.applyBindings(myViewModel);
ko.applyBindings(myViewModel, document.body, (ctx) => { ctx.x = "test"; });
ko.applyBindings(myViewModel, document.getElementById('someElementId')!);
myViewModel.personName();
myViewModel.personName('Mary');
myViewModel.personAge(50);
const subscription = myViewModel.personName.subscribe(newValue => {
alert("The person's new name is " + newValue);
});
// arrayChange event works for any observable
myViewModel.personName.extend({ trackArrayChanges: true });
myViewModel.personName.subscribe(changes => {
console.log(changes[0].value.toUpperCase());
}, myViewModel, "arrayChange");
ko.when<string>(myViewModel.personName, value => {
console.log("personName has a value of ", value.toUpperCase());
});
ko.when(() => {
return !myViewModel.personName();
}).then(x => {
if (x === true) {
console.log("personName is clear");
} else {
throw Error("Should never happen");
}
});
subscription.dispose();
}
function test_computed() {
class AppViewModel {
public firstName = ko.observable("Bob");
public lastName = ko.observable("Smith");
public fullName = ko.pureComputed(() => this.firstName() + " " + this.lastName());
}
class MyViewModel {
public firstName = ko.observable("Planet");
public lastName = ko.observable("Earth");
public fullName = ko.pureComputed({
read: () => this.firstName() + " " + this.lastName(),
write: (value) => {
const lastSpacePos = value.lastIndexOf(" ");
if (lastSpacePos > 0) {
this.firstName(value.substring(0, lastSpacePos));
this.lastName(value.substring(lastSpacePos + 1));
}
}
});
}
class MyViewModel1 {
public price = ko.observable(25.99);
public formattedPrice = ko.pureComputed({
read: () => "$" + this.price().toFixed(2),
write: value => {
const num = parseFloat(value.replace(/[^\.\d]/g, ""));
this.price(isNaN(num) ? 0 : num);
}
});
}
class MyViewModel2 {
public acceptedNumericValue = ko.observable(123);
public lastInputWasValid = ko.observable(true);
public attemptedValue = ko.computed<number, this>({
read: this.acceptedNumericValue,
write: function (value) {
if (isNaN(value))
this.lastInputWasValid(false);
else {
this.lastInputWasValid(true);
this.acceptedNumericValue(value);
}
},
owner: this
});
}
ko.applyBindings(new MyViewModel());
}
class GetterViewModel {
private _selectedRange = ko.observable();
public range = ko.observable();
}
function testGetter() {
const model = new GetterViewModel();
model.range.subscribe((range: number) => {
console.log(range);
});
}
function test_observableArrays() {
const myObservableArray = ko.observableArray<string>();
myObservableArray.push('Some value');
const anotherObservableArray = ko.observableArray([
{ name: "Bungle", type: "Bear", age: 10 },
{ name: "George", type: "Hippo", age: 20 },
{ name: "Zippy", type: "Unknown", age: 25 }
]);
const multiTypeObservableArray = ko.observableArray<string | number | undefined>();
anotherObservableArray.subscribe(changes => {
console.log(changes[0].value.name.toUpperCase());
}, null, "arrayChange");
myObservableArray().length;
myObservableArray()[0];
myObservableArray.indexOf('Blah');
myObservableArray.push('Some new value');
myObservableArray.push('v1', 'v2', 'v3');
myObservableArray.pop();
myObservableArray.unshift('Some new value');
myObservableArray.shift();
myObservableArray.reverse();
myObservableArray.sort();
myObservableArray.sort((left, right) => left == right ? 0 : (left < right ? -1 : 1));
myObservableArray.splice(1, 3);
myObservableArray.remove('Blah');
anotherObservableArray.remove(item => item.age < 18);
multiTypeObservableArray.removeAll(['Chad', 132, undefined]);
myObservableArray.removeAll();
myObservableArray.destroy('Blah');
anotherObservableArray.destroy(someItem => someItem.age < 18);
multiTypeObservableArray.destroyAll(['Chad', 132, undefined]);
myObservableArray.destroyAll();
ko.utils.arrayForEach(anotherObservableArray(), item => {
console.log(item.name);
});
}
// You have to extend knockout for your own handlers
declare module "knockout" {
export interface BindingHandlers {
yourBindingName: ko.BindingHandler;
slideVisible: ko.BindingHandler;
allowBindings: ko.BindingHandler;
withProperties: ko.BindingHandler;
randomOrder: ko.BindingHandler;
}
}
function test_bindings() {
const currentProfit = ko.observable(150000);
ko.applyBindings({
people: [
{ firstName: 'Bert', lastName: 'Bertington' },
{ firstName: 'Charles', lastName: 'Charlesforth' },
{ firstName: 'Denise', lastName: 'Dentiste' }
]
});
const viewModel = { availableCountries: ko.observableArray(['France', 'Germany', 'Spain']) };
viewModel.availableCountries.push('China');
ko.bindingHandlers.yourBindingName = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
return { "controlsDescendantBindings": true };
}
};
ko.bindingHandlers.slideVisible = {
update: function (element, valueAccessor, allBindingsAccessor) {
const
value = valueAccessor(), allBindings = allBindingsAccessor(),
valueUnwrapped = ko.utils.unwrapObservable(value),
duration = allBindings.slideDuration || 400;
if (valueUnwrapped == true)
$(element).slideDown(duration);
else
$(element).slideUp(duration);
},
init: function (element, valueAccessor) {
const value = ko.utils.unwrapObservable(valueAccessor());
$(element).toggle(value);
}
};
ko.bindingHandlers.hasFocus = {
init: function (element, valueAccessor) {
$(element)
.focus(() => {
const value = valueAccessor();
value(true);
})
.blur(() => {
const value = valueAccessor();
value(false);
});
},
update: function (element, valueAccessor) {
var value = valueAccessor();
if (ko.utils.unwrapObservable(value))
element.focus();
else
element.blur();
}
};
ko.bindingHandlers.allowBindings = {
init: function (elem, valueAccessor) {
var shouldAllowBindings = ko.utils.unwrapObservable(valueAccessor());
return { controlsDescendantBindings: !shouldAllowBindings };
}
};
ko.bindingHandlers.withProperties = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
const
newProperties = valueAccessor(),
innerBindingContext = bindingContext.extend(newProperties);
ko.applyBindingsToDescendants(innerBindingContext, element);
return { controlsDescendantBindings: true };
}
};
ko.bindingHandlers.withProperties = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var newProperties = valueAccessor(),
childBindingContext = bindingContext.createChildContext(viewModel);
ko.utils.extend(childBindingContext, newProperties);
ko.applyBindingsToDescendants(childBindingContext, element);
return { controlsDescendantBindings: true };
}
};
ko.bindingHandlers.randomOrder = {
init: function (elem, valueAccessor) {
var child = ko.virtualElements.firstChild(elem),
childElems = [];
while (child) {
childElems.push(child);
child = ko.virtualElements.nextSibling(child);
}
ko.virtualElements.emptyNode(elem);
while (childElems.length) {
var randomIndex = Math.floor(Math.random() * childElems.length),
chosenChild = childElems.splice(randomIndex, 1);
ko.virtualElements.prepend(elem, chosenChild[0]);
}
}
};
let node: Node = new Node(), containerElem: Element = new Element(),
nodeToInsert: Node = new Node(), insertAfter: Node = new Node(), nodeToPrepend: Node = new Node(), arrayOfNodes: Node[] = [];
ko.virtualElements.emptyNode(containerElem);
ko.virtualElements.firstChild(containerElem);
ko.virtualElements.insertAfter(containerElem, nodeToInsert, insertAfter);
ko.virtualElements.nextSibling(node);
ko.virtualElements.prepend(containerElem, nodeToPrepend);
ko.virtualElements.setDomNodeChildren(containerElem, arrayOfNodes);
}
// Have to define your own extenders
declare module "knockout" {
export interface ObservableArrayFunctions<T> {
filterByProperty(propName: string, matchValue: boolean): ko.Computed<any>;
}
export interface ExtendersOptions {
numeric: number;
required: string;
logChange: string;
}
export interface ExtendersOptions<T> {
validate(v: T): boolean;
}
}
function test_more() {
const viewModel = {
firstName: ko.observable("Bert"),
lastName: ko.observable("Smith"),
pets: ko.observableArray(["Cat", "Dog", "Fish"]),
type: "Customer",
hasALotOfPets: <any>null
};
viewModel.hasALotOfPets = ko.computed(() => viewModel.pets().length > 2);
const plainJs = ko.toJS(viewModel);
var petsInitials = plainJs.pets.map(x => x.charAt(0));
ko.extenders.logChange = function (target: ko.Subscribable, option: string) {
target.subscribe((newValue: string) => {
console.log(option + ": " + newValue);
});
return target;
};
ko.extenders.numeric = function (target: ko.Subscribable, precision: number) {
var result = ko.computed<any>({
read: target,
write: (newValue) => {
var current = target(),
roundingMultiplier = Math.pow(10, precision),
newValueAsNum = isNaN(newValue) ? 0 : parseFloat(newValue),
valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
if (valueToWrite !== current) {
target(valueToWrite);
} else {
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
});
result(target());
return result;
};
class AppViewModel {
myNumberOne: ko.Observable<number>;
myNumberTwo: ko.Observable<number>;
constructor(one: number, two: number) {
this.myNumberOne = ko.observable(one).extend({ numeric: 0 });
this.myNumberTwo = ko.observable(two).extend({ numeric: 2 });
}
}
ko.applyBindings(new AppViewModel(221.2234, 123.4525));
ko.extenders.required = function (target: any, overrideMessage: string) {
target.hasError = ko.observable();
target.validationMessage = ko.observable();
function validate(newValue: any) {
target.hasError(newValue ? false : true);
target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
}
validate(target());
target.subscribe(validate);
return target;
};
class AppViewModel2 {
firstName: ko.Observable<string>;
lastName: ko.Observable<string>;
constructor(first: string, last: string) {
this.firstName = ko.observable(first).extend({ required: "Please enter a first name" });
this.lastName = ko.observable(last).extend({ required: "" });
}
test() {
const first: string = "test";
this.firstName = ko.observable(first).extend({ required: "Please enter a first name", logChange: "first name", validate: v => !!v.match(/^.+$/) });
}
}
ko.applyBindings(new AppViewModel2("Bob", "Smith"));
let name = "";
const upperCaseName = ko.computed(() => name.toUpperCase()).extend({ throttle: 500 });
class AppViewModel3 {
// Observable<string | undefined> since there's no initial value
public instantaneousValue = ko.observable<string>();
public throttledValue = ko.computed(this.instantaneousValue)
.extend({ throttle: 400 });
public loggedValues = ko.observableArray<string>([]);
public throttledValueLogger = ko.computed(() => {
const val = this.instantaneousValue();
if (val && val !== '')
this.loggedValues.push(val);
});
}
class GridViewModel {
public pageSize = ko.observable(20);
public pageIndex = ko.observable(1);
public currentPageData = ko.observableArray();
constructor() {
ko.computed(() => {
const params = { page: this.pageIndex(), size: this.pageSize() };
$.getJSON('/Some/Json/Service', params, this.currentPageData);
});
}
}
function setPageSize(this: GridViewModel, newPageSize: number) {
this.pageSize(newPageSize);
this.pageIndex(1);
};
var grid = new GridViewModel();
ko.computed(function (this: GridViewModel) {
var params = { page: this.pageIndex(), size: this.pageSize() };
$.getJSON('/Some/Json/Service', params, this.currentPageData);
}, grid).extend({ throttle: 1 });
const removeDom = document.querySelector(".remove");
if (removeDom) {
removeDom.addEventListener("click", function (this: HTMLElement) {
viewModel.pets.remove(ko.dataFor(this));
});
removeDom.addEventListener("click", function (this: HTMLElement) {
viewModel.pets.remove(ko.dataFor(this));
});
}
ko.observableArray.fn.filterByProperty = function (propName: string, matchValue: boolean) {
return ko.pureComputed(() => {
const allItems = this(), matchingItems = [];
for (let current of allItems) {
if (ko.utils.unwrapObservable(current[propName]) === matchValue)
matchingItems.push(current);
}
return matchingItems;
});
}
class Task {
public title: ko.Observable<string>;
public done: ko.Observable<boolean>;
constructor(title: string, done: boolean) {
this.title = ko.observable(title);
this.done = ko.observable(done);
}
}
class AppViewModel4 {
public tasks = ko.observableArray([
new Task('Find new desktop background', true),
new Task('Put shiny stickers on laptop', false),
new Task('Request more reggae music in the office', true)
]);
public doneTasks = this.tasks.filterByProperty("done", true);
constructor() {
this.doneTasks = ko.computed(() => {
const all = this.tasks(), done = [];
for (let cur of all)
if (cur.done())
done.push(cur);
return done;
}, this);
}
}
ko.applyBindings(new AppViewModel4());;
}
// Define your own functions
declare module "knockout" {
export interface SubscribableFunctions<T> {
publishOn(topic: string): this;
subscribeTo(topic: string): this;
}
export interface BindingHandlers {
isolatedOptions: BindingHandler;
}
}
function test_misc(this: any) {
// define dummy vars
let callback: any;
let target: any;
let topic: any;
let vm: any;
let value: any;
const postbox = new ko.subscribable();
postbox.subscribe(callback, target, topic);
postbox.subscribe(function (this: typeof vm, newValue: string) {
this.latestTopic(newValue);
}, vm, "mytopic");
postbox.notifySubscribers(value, "mytopic");
ko.subscribable.fn.publishOn = function (topic: string) {
this.subscribe(function (newValue) {
postbox.notifySubscribers(newValue, topic);
});
return this;
};
this.myObservable = ko.observable("myValue").publishOn("myTopic");
ko.subscribable.fn.subscribeTo = function (this: any, topic: string) {
postbox.subscribe(this, null, topic);
return this;
};
this.observableFromAnotherVM = ko.observable().subscribeTo("myTopic");
postbox.subscribe(function (this: ko.Subscribable, newValue: string) {
this(newValue);
}, this, topic);
ko.bindingHandlers.isolatedOptions = {
init: function (element, valueAccessor) {
var args = arguments;
ko.computed({
read: () => {
ko.utils.unwrapObservable(valueAccessor());
ko.bindingHandlers.options.update.apply(this, args as any);
},
owner: this,
disposeWhenNodeIsRemoved: element
});
}
};
ko.subscribable.fn.publishOn = function (topic: string) {
this.subscribe(function (newValue) {
postbox.notifySubscribers(newValue, topic);
});
return this;
};
this.myObservable = ko.observable("myValue").publishOn("myTopic");
var x = ko.observableArray([1, 2, 3]);
let element = new HTMLElement();
ko.utils.domNodeDisposal.addDisposeCallback(element, el => {
$(el).datepicker("destroy");
});
this.observableFactory = function (readonly: boolean = false): ko.Subscribable<number> {
if (readonly) {
return ko.computed(() => 3);
} else {
return ko.observable(3);
}
}
}
function test_subscribableRetainsType() {
// See https://github.com/knockout/knockout/issues/2555
// Subscribable<T> should preserve type T when called, not return any
let sub: ko.Subscribable<number> = ko.observable(5);
let value = sub();
// This will fail to compile if value is 'any' instead of 'number',
// because 'true extends false' is never true, making the type 'never',
// and 'never' is not assignable to 'true'.
type IsNotAny<T> = 0 extends (1 & T) ? false : true;
const check: IsNotAny<typeof value> = true;
// Subscribable<T> also supports writing a value
let wsub: ko.Subscribable<number> = ko.observable(5);
wsub(10);
}
function test_customObservable() {
// See https://github.com/knockout/knockout/issues/2072
var modelAttributeObservable = (model: any, attribute: any): ko.Observable => {
// Check the attribute exists
if (!(attribute in model)) {
throw new ReferenceError(attribute + ' is not an attribute of the supplied model');
}
// Set up the attribute observable cache
model._koObservables || (model._koObservables = {});
// If we already have a cached observable then just return it
if (attribute in model._koObservables) {
return model._koObservables[attribute];
}
// Create our observable getter/setter function
var observableAttribute = <ko.Observable>(function (this: any): any {
if (arguments.length > 0) {
observableAttribute.valueWillMutate();
model[attribute] = arguments[0];
return this;
} else {
// The caller only needs to be notified of changes if they did a "read" operation
ko.computedContext.registerDependency(observableAttribute);
return observableAttribute.peek();
}
});
// Create a function to fetch the attribute value that
// is in the correct context so it has access to the model.
observableAttribute.peek = function () {
return model[attribute];
}
// Register to listen to change events on the model attribute
model.on('change:' + attribute, function () {
observableAttribute.valueHasMutated();
});
// Initialise the observableAttribute as a subscribable
// Then override the prototype to make it a subclass
ko.subscribable.fn.init(observableAttribute);
(<any>observableAttribute).__proto__ = observableAttribute_fn;
// setup the deferred update extender if needed
ko.options['deferUpdates'] && ko.extenders['deferred'](observableAttribute, true);
// Cache the observableAttribute function and return it
return (model._koObservables[attribute] = observableAttribute);
};
// Setup the prototype for the observableAttribute as a subclass of subscribable
var observableAttribute_fn = {
__proto__: ko.subscribable['fn'],
valueHasMutated: function (this: ko.Observable) { this.notifySubscribers(this.peek()); },
valueWillMutate: function (this: ko.Observable) { this.notifySubscribers(this.peek(), 'beforeChange'); },
// Make KO treat the observableAttribute function as an observable
__ko_proto__: ko.observable
};
}
function test_allBindingsAccessor() {
ko.bindingHandlers.allBindingsAccessorTest = {
init: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) => {
var allBindings = allBindingsAccessor();
var hasBinding = allBindingsAccessor.has("myBindingName");
var myBinding = allBindingsAccessor.get("myBindingName");
var fnAccessorBinding = allBindingsAccessor().myBindingName;
},
update: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) => {
var allBindings = allBindingsAccessor();
var hasBinding = allBindingsAccessor.has("myBindingName");
var myBinding = allBindingsAccessor.get("myBindingName");
var fnAccessorBinding = allBindingsAccessor().myBindingName;
}
};
}
function test_Components() {
// test all possible ko.components.register() overloads
function test_Register() {
// reused parameters
const nodeArray = [new Node, new Node];
const singleNode = new Node;
const viewModelFn = function (params: any) { return <any>null; }
class ViewModelClass { }
// ------- viewmodel overloads:
// viewModel as inline function (commonly used in examples)
ko.components.register("name", { template: "string-template", viewModel: viewModelFn });
// viewModel as a Class
ko.components.register("name", { template: "string-template", viewModel: ViewModelClass });
// viewModel from shared instance
ko.components.register("name", { template: "string-template", viewModel: { instance: null } });
// viewModel from createViewModel factory method
ko.components.register("name", { template: "string-template", viewModel: { createViewModel: function (params: any, componentInfo: ko.components.ComponentInfo) { return null; } } });
// viewModel from an AMD module
ko.components.register("name", { template: "string-template", viewModel: { require: "module" } });
// ------- template overloads
// template from named element
ko.components.register("name", { template: { element: "elementID" }, viewModel: viewModelFn });
// template using single Node
ko.components.register("name", { template: { element: singleNode }, viewModel: viewModelFn });
// template using Node array
ko.components.register("name", { template: nodeArray, viewModel: viewModelFn });
// template using an AMD module
ko.components.register("name", { template: { require: "text!module" }, viewModel: viewModelFn });
// Empty config for registering custom elements that are handled by name convention
ko.components.register('name', { /* No config needed */ });
}
function test_DefaultLoader() {
ko.components.defaultLoader.getConfig("name", (config: ko.components.Config) => { config.synchronous = true; });
}
}
function testUnwrapUnion(this: any) {
let possibleObs: ko.Observable<number> | number = this.getValue();
const num = ko.unwrap(possibleObs);
}
function testToJS() {
const obj: {
foo: string
bar: string
} = ko.toJS({ foo: ko.observable(''), bar: '' })
const arr: {
foo: string
bar: string
}[] = ko.toJS([{ foo: ko.observable(''), bar: '' }])
const observableArr: {
foo: string
bar: string
}[] = ko.toJS(ko.observableArray([
ko.observable({ foo: ko.observable(''), bar: '' }),
ko.observable({ foo: ko.observable(''), bar: ko.observable('') })
]))
const plainObservableWithArray: {
foo: string
bar: string
}[] = ko.toJS(ko.observable([
ko.observable({ foo: ko.observable(''), bar: '' }),
ko.observable({ foo: ko.observable(''), bar: '' })
]))
// const recursive: string = ko.toJS(ko.observable(ko.observable(ko.observable(''))))
const recursiveObj: {
foo: {
bar: string
}
} = ko.toJS(
ko.observable({
foo: ko.observable({ bar: ko.observable('') })
})
)
const builtins: {
date: Date
regexp: RegExp
func: (v: string) => string
} = ko.toJS({
date: new Date(),
regexp: /foo/,
func: (v: string) => ''
})
}
// *****************************
// Template and Databinding Tests
// *****************************
declare module "knockout" {
export interface TemplateOptions<T> {
showParams?: boolean;
templateOptions?: any;
templateRenderingVariablesInScope?: any;
}
}
class DummyTemplateSource {
constructor(private engine: DummyTemplateEngine, public id: string) { }
text(): string;
text(val: string): void;
text(val?: string) {
if (arguments.length > 0) {
this.engine.inMemoryTemplates[this.id] = val;
}
else {
return this.engine.inMemoryTemplates[this.id];
}
}
data(): any;
data(val: any): void;
data(val?: any) {
if (arguments.length > 0) {
this.engine.inMemoryTemplateData[this.id] = val;
}
else {
return this.engine.inMemoryTemplateData[this.id];
}
}
}
class DummyTemplateEngine extends ko.templateEngine {
public inMemoryTemplates: { [key: string]: any } = {};
public inMemoryTemplateData: { [key: string]: any } = {};
constructor(templates?: { [key: string]: any }) {
super();
this.inMemoryTemplateData = templates || {};
}
public makeTemplateSource(template: string | Node, templateDocument?: Document): ko.TemplateSource {
if (typeof template === "string") {
return new DummyTemplateSource(this, template); // Named template comes from the in-memory collection
}
else if ((template.nodeType == 1) || (template.nodeType == 8)) {
return new ko.templateSources.anonymousTemplate(template); // Anonymous
}
else {
throw new Error("Unrecognized template source");
}
}
public renderTemplateSource(templateSource: ko.TemplateSource, bindingContext: ko.BindingContext<any>, options?: ko.TemplateOptions<any>, templateDocument?: Document): Node[] {
const data = bindingContext['$data'];
options = options || {};
let templateText = templateSource.text() as string | Function;
if (typeof templateText == "function")
templateText = templateText(data, options) as string;
templateText = options.showParams ? templateText + ", data=" + data + ", options=" + options : templateText;
var templateOptions = options.templateOptions; // Have templateOptions in scope to support [js:templateOptions.foo] syntax
var result;
//with (bindingContext)
{
//with (data || {})
{
//with (options.templateRenderingVariablesInScope || {})
{
// Dummy [renderTemplate:...] syntax
result = templateText.replace(/\[renderTemplate\:(.*?)\]/g, function (match, templateName) {
return ko.renderTemplate(templateName, data, options || {});
});
var evalHandler = function (match: string, script: any) {
try {
var evalResult = eval(script);
return (evalResult === null) || (evalResult === undefined) ? "" : evalResult.toString();
} catch (ex: any) {
throw new Error("Error evaluating script: [js: " + script + "]\n\nException: " + ex.toString());
}
}
// Dummy [[js:...]] syntax (in case you need to use square brackets inside the expression)
result = result.replace(/\[\[js\:([\s\S]*?)\]\]/g, evalHandler);
// Dummy [js:...] syntax
result = result.replace(/\[js\:([\s\S]*?)\]/g, evalHandler);
}
}
}
// Use same HTML parsing code as real template engine so as to trigger same combination of IE weirdnesses
// Also ensure resulting nodelist is an array to mimic what the default templating engine does, so we see the effects of not being able to remove dead memo comment nodes.
return ko.utils.arrayPushAll([], ko.utils.parseHtmlFragment(result));
}
public rewriteTemplate(template: string | Node, rewriterCallback: (val: string) => any) {
// Only rewrite if the template isn't a function (can't rewrite those)
var templateSource = new ko.templateSources.anonymousTemplate(template as any); //this.makeTemplateSource(template);
if (typeof templateSource.text() != "function")
return ko.templateEngine.prototype.rewriteTemplate.call(this, template, rewriterCallback);
}
public createJavaScriptEvaluatorBlock(script: string): string {
return "[js:" + script + "]";
};
}
let testNode: any;
ko.setTemplateEngine(new ko.nativeTemplateEngine());
ko.setTemplateEngine(new DummyTemplateEngine({ x: [document.createElement("div"), document.createElement("span")] }));
ko.renderTemplate("x", null);
var threw = false;
ko.setTemplateEngine(undefined);
try { ko.renderTemplate("someTemplate", {}) }
catch (ex) { threw = true }
ko.setTemplateEngine(new DummyTemplateEngine({ someTemplate: "ABC" }));
ko.renderTemplate("someTemplate", null, null, testNode);
ko.setTemplateEngine(new DummyTemplateEngine({ emptyTemplate: "" }));
ko.renderTemplate("emptyTemplate", null, null, testNode);
var passedElement, passedDataItem;
var myCallback = function (elementsArray: Node[], dataItem: any) {
passedElement = elementsArray[0];
passedDataItem = dataItem;
}
var myModel = {};
ko.setTemplateEngine(new DummyTemplateEngine({ someTemplate: "ABC" }));
ko.renderTemplate("someTemplate", myModel, { afterRender: myCallback }, testNode);
var dependency = ko.observable("A");
ko.setTemplateEngine(new DummyTemplateEngine({ someTemplate: () => "Value = " + dependency() }));
ko.renderTemplate("someTemplate", null, null, testNode);
dependency("B");
var observable = ko.observable("A"), count = 0;
var myCallback = function (elementsArray: Node[], dataItem: any) {
observable(); // access observable in callback
};
var myTemplate = function () {
return "Value = " + (++count);
};
ko.setTemplateEngine(new DummyTemplateEngine({ someTemplate: myTemplate }));
ko.renderTemplate("someTemplate", {}, { afterRender: myCallback }, testNode);
observable("B");
var observable = ko.observable("A");
ko.setTemplateEngine(new DummyTemplateEngine({
someTemplate: function (data: string) {
return "Value = " + data;
}
}));
ko.renderTemplate("someTemplate", observable, null, testNode);
observable("B");
var dependency = ko.observable("A");
var template = { someTemplate: () => "Value = " + dependency() };
ko.setTemplateEngine(new DummyTemplateEngine(template));
ko.renderTemplate("someTemplate", null, null, testNode);
testNode.parentNode.removeChild(testNode);
dependency("B");
ko.setTemplateEngine(new DummyTemplateEngine({ someTemplate: "template output" }));
testNode.innerHTML = "<div data-bind='template:\"someTemplate\"'></div>";
ko.applyBindings(null, testNode);
ko.setTemplateEngine(new DummyTemplateEngine({ someTemplate: "result = [js: childProp]" }));
testNode.innerHTML = "<div data-bind='template: { name: \"someTemplate\", data: someProp }'></div>";
ko.applyBindings({ someProp: { childProp: 123 } }, testNode);
ko.setTemplateEngine(new DummyTemplateEngine({ someTemplate: "result = [js: childProp]" }));
testNode.innerHTML = "<div data-bind='template: { name: \"someTemplate\", data: someProp }'></div>";
var myData = ko.observable({ childProp: 123 });
ko.applyBindings({ someProp: myData }, testNode);
// Now mutate and notify
myData().childProp = 456;
myData.valueHasMutated();
var innerObservable = ko.observable("some value");
ko.setTemplateEngine(new DummyTemplateEngine({ someTemplate: "result = [js: childProp()]" }));
testNode.innerHTML = "<div data-bind='template: { name: \"someTemplate\", data: someProp }'></div>";
ko.applyBindings({ someProp: { childProp: innerObservable } }, testNode);