Knockout observableArray in TypeScript

谁说胖子不能爱 提交于 2019-12-04 20:34:26

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/13168051/knockout-observablearray-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!