Kla*_*Nji 8 ko.observablearray knockout.js typescript
在TypeScript类中初始化Knockout observableArray的正确方法是什么?
我正在做这样的事情:
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);
}
Run Code Online (Sandbox Code Playgroud)
看起来很简单,但当我尝试按指示访问代理商属性时,执行挂起.我错过了什么?
Bor*_*kov 13
这条线是你的错误所在:
agencies[i]
Run Code Online (Sandbox Code Playgroud)
当您访问一个可观察的数组时,它实际上包含在一个函数中,因此您可以访问它:
agencies()[i]
Run Code Online (Sandbox Code Playgroud)
也帮自己一个忙,并从以下网址下载Knockout定义:https: //github.com/borisyankov/DefinitelyTyped
然后使用类型声明属性:
module ViewModel {
export class IndexPageViewModel {
agencies: KnockoutObservableArray;
constructor () {
this.agencies = ko.observableArray([]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我只是在TypeScript 1.3中做到了这一点(尽管它也可以在旧版本中使用):
pendingAddAssociations: KnockoutObservableArray<ControllerModel> = ko.observableArray<ControllerModel>([]);
Run Code Online (Sandbox Code Playgroud)
以您的示例为例,如果您具有代理商类。
export class IndexPageViewModel {
agencies: KnockoutObservableArray<Agency>;
constructor () {
this.agencies = ko.observableArray<Agency>([]);
}
}
Run Code Online (Sandbox Code Playgroud)
我还发现您可以强制转换为任何对象。this.agencies = <any>[];如果您使用的是Knockout ES5插件,这将非常有用。
| 归档时间: |
|
| 查看次数: |
8443 次 |
| 最近记录: |