Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout observableArray in TypeScript

What is the proper way to initialize a Knockout observableArray 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);
 }

Looks simple enough, but when I attempt to access the agencies property as indicated, execution hangs. Did I miss something?

like image 438
Klaus Nji Avatar asked Oct 31 '12 21:10

Klaus Nji


People also ask

What is Ko ObservableArray?

An observableArray just tracks which objects it holds, and notifies listeners when objects are added or removed.

What is an observable array?

ObservableArray is an array that allows listeners to track changes when they occur. In order to track changes, the internal array is encapsulated and there is no direct access available from the outside. Bulk operations are supported but they always do a copy of the data range.

Which function is used to search or sort an observable array?

The KnockoutJS Observable sort() method sorts all items in the array. By default, items are sorted in an ascending order. For sorting an array in a descending order, use reverse() method on sorted array.


2 Answers

This line is where your mistake is:

agencies[i]

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

agencies()[i]

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

Then declare your attributes with types:

module ViewModel {

    export class IndexPageViewModel {

        agencies: KnockoutObservableArray;

        constructor () {
            this.agencies = ko.observableArray([]);
        }
    }
}
like image 155
Boris Yankov Avatar answered Oct 23 '22 21:10

Boris Yankov


I just did this in TypeScript 1.3 (though 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've also found that you can cast to any this.agencies = <any>[]; This is useful if you are using the Knockout ES5 plugin.

like image 31
AlignedDev Avatar answered Oct 23 '22 22:10

AlignedDev