我遇到了一个问题,我不能在我的视图中使用我在模型中声明的函数。对我来说,似乎功能确实存在,所以我不确定为什么控制台告诉我它们不存在。
我在这里提取了我的观点的相关部分:
<div class="col-lg-6">
<div class="page-header">
<h3>Examens</h3>
</div>
<!-- ko foreach: examAttempts -->
<div class="panel-header clickable" data-bind="click: () => toggleOpen()">
<h3 class="d-block">
Examen poging #<span data-bind="text: $index"></span>
<span class="pull-right" data-bind="css: { fa: true, 'fa-chevron-left': !open(), 'fa-chevron-down': open() }"></span>
</h3>
</div>
<div class="panel-body" data-bind="visible: open">
<!-- ko foreach: questions -->
<p>
<b><span data-bind="text: formatQuestion($index)"></span></b>
<br />
<span data-bind="text: answer"></span>
<br />
<i>Beantwoord in: <span data-bind="text: time"></span> seconde(s)</i>
</p>
<!-- /ko -->
</div>
<br /><br /><br />
<!-- /ko -->
</div>
这些是我的视图模型(省略了不相关的字段):
class ExamAttempt {
questions: KnockoutObservableArray<ExamQuestion>;
open: KnockoutObservable<boolean>;
constructor(questions: any) {
this.questions = ko.observableArray<ExamQuestion>(questions);
this.open = ko.observable<boolean>(false);
}
public toggleOpen(): void {
this.open(!this.open());
}
}
class ExamQuestion {
question: KnockoutObservable<string>;
answer: KnockoutObservable<string>;
time: KnockoutObservable<number>;
constructor(question: string, answer: string, time: number) {
this.question = ko.observable<string>(question);
this.answer = ko.observable<string>(answer);
this.time = ko.observable<number>(time);
}
public formatQuestion(index: number): string {
return `${index + 1}. ${this.question()}`;
}
}
class EditUserProfileModel {
examAttempts: KnockoutObservableArray<ExamAttempt>;
constructor(params: any) {
this.examAttempts = ko.observableArray<ExamAttempt>(params.examAttempts);
}
}
应用绑定(params
是序列化的页面模型):
ko.applyBindings(new EditUserProfileModel(params));
我得到的错误(嗯,他们只是说函数是未定义的,但对我来说似乎不应该这样):
任何建议都将不胜感激。
答案 0 :(得分:0)
是的我弄清楚了,这是类型的问题。显然,即使params.examAttempts
具有与ExamAttempt
类相同的结构和相同的字段,js / ts也不会将其转换为ExamAttempt
的实例,这是问题所在(因为函数在ExamAttempt
类中定义。我的错!。
@adiga,谢谢你花时间创造一个小提琴。
要修复它,我更改了这一行:
this.examAttempts = ko.observableArray<ExamAttempt>(params.examAttempts)
分为:
this.examAttempts = ko.observableArray<ExamAttempt>(params.examAttempts.map((ea: any) => {
let questions = ea.questions.map((eaq: any) => {
return new ExamQuestion(eaq.question, eaq.answer, eaq.time);
});
return new ExamAttempt(questions);
}));