在TypeScript中淘汰出observableArray [英] Knockout observableArray in TypeScript

查看:67
本文介绍了在TypeScript中淘汰出observableArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在TypeScript类中初始化Knockout observableArray的正确方法是什么?

What is the proper way to initialize a Knockout observableArray in a TypeScript class?

我正在做这样的事情:

   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);
 }

看起来很简单,但是当我尝试如图所示访问agency属性时,执行挂起.我错过了什么吗?

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

推荐答案

此行是您的错误所在:

agencies[i]

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

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

agencies()[i]

也请您帮个忙,并从以下位置下载淘汰赛定义: https://github.com/borisyankov/DefinitelyTyped

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

这篇关于在TypeScript中淘汰出observableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆