Knockout Observed Array in TypeScript

What is the correct way to initialize a Knockout observable array in a TypeScript class?

I am doing something like this:

module ViewModel { declare var ko; export class IndexPageViewModel { agencies: any; constructor () { this.agencies = ko.observableArray([]); } } } var ivm = new ViewModel.IndexPageViewModel(); ivm.agencies.push({name: "name", alias : "alias"}); for (var i = 0; i < ivm.agencies.length; i++){ alert(ivm.agencies[i].name); } 

It looks simple enough, but when I try to access the agency property, as indicated, the execution freezes. Did I miss something?

+7
source share
2 answers

In this line you are mistaken:

 agencies[i] 

When you access an observable array, it is actually wrapped in a function, so you will access it like this:

 agencies()[i] 

Also do yourself a favor and download Knockout definitions from: https://github.com/borisyankov/DefinitelyTyped

Then declare your attributes using types:

 module ViewModel { export class IndexPageViewModel { agencies: KnockoutObservableArray; constructor () { this.agencies = ko.observableArray([]); } } } 
+12
source

I just did it in TypeScript 1.3 (although it should work in older versions too):

 pendingAddAssociations: KnockoutObservableArray<ControllerModel> = ko.observableArray<ControllerModel>([]); 

for your example, if you have an agency class.

 export class IndexPageViewModel { agencies: KnockoutObservableArray<Agency>; constructor () { this.agencies = ko.observableArray<Agency>([]); } } 

I also found that you can use any of this.agencies = <any>[]; . This is useful if you are using the ES5 knockout plugin .

+3
source

All Articles