gpt4 book ai didi

javascript - 为什么这个绑定(bind)的 knockout 元素变得未定义?

转载 作者:行者123 更新时间:2023-12-01 01:47:17 26 4
gpt4 key购买 nike

使用 TypeScript 和 Knockout 构建页面。当页面加载时, View 模型创建并向“vehicles”对象数组分配一个值。

vehicles: KnockoutObservableArray<Vehicle>;

constructor() {
// uses and API to fetch data into a "vehicleData" array
this.vehicles = ko.observableArray(vehicleData);
}

在页面本身中,它绑定(bind)到一个包含“删除”按钮的元素:

<div data-bind="foreach: vehicles">
<div data-bind="text: model"></div>
<button data-bind="click: $parent.removeVehicle">Remove</button>
</div>

这一切都很好。我不明白的是调用removeVehicles 时会发生什么。这是:

removeVehicle(vehicle): void {
this.vehicles.remove(vehicle);
}

它按预期传入参数,但当它尝试删除时,它声称“车辆”不再存在。

Uncaught TypeError: Cannot read property 'remove' of undefined
at Object.VehicleManagementViewModel.removeVehicle
at HTMLButtonElement.<anonymous> (knockout-latest.js:99)

是什么导致数组变得未定义?当 HTML 元素正确绑定(bind)到它时,它怎么可能是未定义的呢?

最佳答案

如果您以这种方式引用 View 模型中的函数,this 将被 Knockout 覆盖。

您可以将 View 模型中的函数定义为箭头函数。这样,this 将继续引用 View 模型类。

所以你可以改变:

removeVehicle(vehicle): void {
this.vehicles.remove(vehicle);
}

致:

removeVehicle = (vehicle) => {
this.vehicles.remove(vehicle);
}

关于javascript - 为什么这个绑定(bind)的 knockout 元素变得未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51858432/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com