Javascript typescript对所有公共变量说;“未定义”;
我得到了以下代码Javascript typescript对所有公共变量说;“未定义”;,javascript,knockout.js,typescript,Javascript,Knockout.js,Typescript,我得到了以下代码 module Absence { export var instance: AbsenceViewModel; export class ViewModel { public items: KnockoutObservableArray<AbsenceItem>; public reloadData() { this.items.removeAll(); } } } 现在当我打电话的时候 Absence
module Absence {
export var instance: AbsenceViewModel;
export class ViewModel {
public items: KnockoutObservableArray<AbsenceItem>;
public reloadData() {
this.items.removeAll();
}
}
}
现在当我打电话的时候
Absence.instance.reloadData();
它在浏览器控制台中显示
无法读取未定义的属性“removeAll”
但是我导入了我的淘汰库和其他需要的东西。所以它是存在的
当我使用内部实例时,比如
Absence.instance.items.removeAll();
我错了什么
编辑:
我在一个单独的JS文件中编写了viewModel的dcklation和实例声明。这些文件将加载到页面中。页面准备好后,我在调试控制台手动实例化ViewModel
的实例。在这里,我调用方法reloadData
。因此,我可以确保在调用方法时所有类都可用。我发现了错误。
我必须创建一个getter来访问该属性
get elements(): KnockoutObservableArray<AbsenceItem> {
return this.items;
}
这对我很有帮助我还不熟悉TypeScript中的
get
机制,所以虽然您能够用它解决您的问题,但我将添加此作为另一个答案,我相信这是解决此问题的一般解决方案
出现以下错误:
无法读取未定义的属性“removeAll”
是因为您没有初始化项
数组。您仅将其声明为ViewModel
类的属性。添加构造函数并以正确的方式初始化属性可以避免此类问题。因此,请将代码更新为:
module Absence {
export var instance: AbsenceViewModel;
export class ViewModel {
public items: KnockoutObservableArray<AbsenceItem>;
constructor(){
this.items = ko.observableArray();
}
public reloadData() {
this.items.removeAll();
}
}
}
模块缺失{
导出变量实例:缺席视图模型;
导出类视图模型{
公共物品:击倒台;
构造函数(){
this.items=ko.observearray();
}
公共重载数据(){
this.items.removeAll();
}
}
}
如果看不到您在哪里初始化实例以及是什么触发了它,就很难说。但从根本上说,问题很可能是您在执行deposition.instance.reloadData()
之前试图使用deposition.instance=new…
使用浏览器中内置的调试器查找。抱歉,我已添加了相关信息。我首先在控制台中手动创建这些。所以类是存在的。我自己创建实例,然后自己调用方法。@Sascha:items在哪里初始化?(例如,items=new KnockoutObservableArray()
?如果您不这样做,这可能就是问题所在。
public reloadData() {
this.elements.removeAll();
}
module Absence {
export var instance: AbsenceViewModel;
export class ViewModel {
public items: KnockoutObservableArray<AbsenceItem>;
constructor(){
this.items = ko.observableArray();
}
public reloadData() {
this.items.removeAll();
}
}
}