8

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?

4

2 回答 2

13

这一行是您的错误所在:

agencies[i]

当你访问一个可观察数组时,它实际上被包装在一个函数中,所以你可以像这样访问它:

agencies()[i]

也请帮自己一个忙,并从以下网址下载 Knockout 定义: https ://github.com/borisyankov/DefinitelyTyped

然后用类型声明你的属性:

module ViewModel {

    export class IndexPageViewModel {

        agencies: KnockoutObservableArray;

        constructor () {
            this.agencies = ko.observableArray([]);
        }
    }
}
于 2012-10-31T22:42:21.630 回答
5

我只是在 TypeScript 1.3 中做到了这一点(尽管它也应该在旧版本中工作):

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

对于您的示例,如果您有一个代理类。

export class IndexPageViewModel {

        agencies: KnockoutObservableArray<Agency>;

        constructor () {
            this.agencies = ko.observableArray<Agency>([]);
        }
    }

我还发现,this.agencies = <any>[];如果您使用Knockout ES5 插件,您可以转换为任何内容。

于 2014-12-31T15:44:33.810 回答