我正在使用帶有打印機的asp.net MVC 5。在我的viewmodel im試圖推動我的數據接收從api調用ajax到我的knockoutObservable數組。即使我的數組是initilize(或者至少我認爲它應該是)。Typescript無法推送到knockoutObservableArray,因爲即使在初始化後仍未定義
Errr : TypeError: Cannot read property 'push' of undefined
這裏是我的代碼:
module Models {
export class ReservationDay {
date: KnockoutObservable<Date>;
place: KnockoutObservable<string>;
avaibleSlots: KnockoutObservable<number>;
instructorId: KnockoutObservable<string>;
constructor(date: Date, place: string, avaibleSlots: number, instructorId: string) {
this.date = ko.observable(date);
this.place = ko.observable(place);
this.avaibleSlots = ko.observable(avaibleSlots);
this.instructorId = ko.observable(instructorId);
}
}
}
module ViewModel {
import ReservationDay = Models.ReservationDay;
export class Calendar {
public days: KnockoutObservableArray<ReservationDay> = ko.observableArray<ReservationDay>();
constructor() {
this.getMonthCalendar(new Date());
}
getMonthCalendar(date: Date) {
var month = date.getMonth() + 1;
$.ajax({
url: 'myApiUrl' + month,
type: 'GET',
dataType: 'json',
async: false,
success(data, textStatus, xhr) {
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
console.log(this.days); // here is undefined
this.days.push(new ReservationDay(data[i].date,data[i].place,data[i].avaibleSlots, data[i].instructorId)); // in this line : error : TypeError: Cannot read property 'push' of undefined
}
console.log("ajax done.");
}
},
error(xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
}
,這裏是我的觀點:
@section Scripts{
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/knockout")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/calendar")
<script type="text/javascript">
$(function() {
var vm = new ViewModel.Calendar(@Model);
ko.applyBindings(vm);
});
</script>
}
而且也是另外一個問題,任何人都可以解釋我如何使用位於ReservationDay.ts類在其他文件夾中不在具有如上所述的視圖模型的文件中。 My folders img
預先感謝您!
謝謝它的工作!你知道馬比是否回答我的第二個問題?如何在分離的文件中創建模型? – Bourni