[英]Knockout Typescript viewmodel functions are not defined
我遇到一個問題,我無法在視圖中使用在模型中聲明的函數。 在我看來,這些功能確實存在,因此我不確定為什么控制台會告訴我它們不存在。
我在這里提取了我觀點的相關部分:
<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));
我遇到的錯誤(好吧,他們只是說函數是未定義的,但對我來說似乎不應該這樣):
任何建議將不勝感激。
是的,我想通了,這是類型的問題。 顯然,即使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);
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.