javascript - Typescript 无法推送到 knockout 可观察数组,因为即使在初始化后也未定义

标签 javascript asp.net-mvc typescript knockout.js undefined

我正在使用带有 typescript 的 asp.net MVC 5。在我的 View 模型中,我试图将 ajax 调用中接收的数据从我的 api 推送到我的 knockoutObservable 数组。即使我的数组已初始化(或者至少我认为应该如此)。

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>

}

还有另一个问题,任何人都可以解释一下如何使用位于其他文件夹中而不是具有上述 View 模型的文件中的 ReservationDay.ts 类。 My folders img

提前谢谢您!

最佳答案

因为ajax成功中的this并不引用Calendar的实例,而是引用ajax设置对象。

您可以通过在 ajax 外部添加对 Calendar 实例的引用来解决此问题:

getMonthCalendar(date: Date) {
    var self = this;

    $.ajax({
      ........
      ........
      success: (data, textStatus, xhr) => {
        if (data.length > 0) {
         for (var i = 0; i < data.length; i++) {
            self.days.push((new ReservationDay(data[i].date,data[i].place,data[i].avaibleSlots, data[i].instructorId));
          }
        }
      }
    })
}

或者

您可以使用context输入ajax设置。这将设置所有 ajax 回调的自定义上下文。

$.ajax({
      url: 'myApiUrl' + month,
      type: 'GET',
      context: this,
      success: (data, textStatus, xhr) => {
         console.log(this.days); // refers to the "Calendar" instance
      }
      ....
  });

Here's a fiddle for testing

<小时/>

要在结构中导入 ReservationDay 类,您可以执行以下操作:

import {ReservationDay} from "../viewmodel/calendar"

关于javascript - Typescript 无法推送到 knockout 可观察数组,因为即使在初始化后也未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46863279/

相关文章:

angular - 错误错误 : StaticInjectorError Angular 6

javascript - 如何从字符串中解析 XML

c# - User.Identity 在 ClaimsIdentity 和 WindowsIdentity 之间波动

c# - Kendo MVC DropDownListFor 不会将所选值绑定(bind)到模型

c# - 重新发送模型会重置 asp.net mvc 中的值吗?

angular - 如何测试 Angular 2 双向绑定(bind)输入值

javascript - 返回 Promises 数组的函数类型应该是什么

javascript 逗号未编码

javascript - Angular JS 中的依赖问题

javascript - Toggle JavaScript 中的可见性