knockout.jstypescriptko.observablearray

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?


Solution

  • 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([]);
            }
        }
    }