gpt4 book ai didi

knockout.js - ES5 knockout 到 ES6 knockout

转载 作者:行者123 更新时间:2023-12-02 08:25:29 27 4
gpt4 key购买 nike

我想认真学习更多关于 ES6 的知识。我一直在网上做一些例子,虽然我得到了大部分例子,但有时我什至不知道从哪里开始。请注意,我对这个 ES6 和 Knockout 的东西 super 菜鸟,想通过从他们的网站上拿一个 Knockout 的例子并将其重写为 ES6 来了解更多。我尝试使用类和扩展类,但对于我来说,我无法让它工作。任何人都可以告诉我如何将下面的代码重写为带有类等的 ES6。如果不需要重写它,请告诉我并说明原因。非常感谢并帮助我了解更多信息。

// Class to represent a row in the seat reservations grid
function SeatReservation(name, initialMeal) {
var self = this;
self.name = name;
self.meal = ko.observable(initialMeal);
}

// Overall viewmodel for this screen, along with initial state
function ReservationsViewModel() {
var self = this;

// Non-editable catalog data - would come from the server
self.availableMeals = [
{ mealName: "Standard (sandwich)", price: 0 },
{ mealName: "Premium (lobster)", price: 34.95 },
{ mealName: "Ultimate (whole zebra)", price: 290 }
];

// Editable data
self.seats = ko.observableArray([
new SeatReservation("Steve", self.availableMeals[0]),
new SeatReservation("Bert", self.availableMeals[0])
]);
}

ko.applyBindings(new ReservationsViewModel());

HTML

<h2>Your seat reservations</h2>

<table>
<thead><tr>
<th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
</tr></thead>
<!-- Todo: Generate table body -->
<tbody data-bind="foreach: seats">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: meal().mealName"></td>
<td data-bind="text: meal().price"></td>
</tr>
</tbody>
</table>

最佳答案

首先要注意的是:您的 ES5 代码将在 ES6 设置中正常工作。

我手头没有可用于测试的 knockout ,但 ES6 风格的类看起来像

class SeatReservation {
constructor(name, initialMeal) {
this.name = name;
this.meal = ko.observable(initialMeal);
}
}

class ReservationsViewModel {
constructor() {
// Non-editable catalog data - would come from the server
this.availableMeals = [
{ mealName: "Standard (sandwich)", price: 0 },
{ mealName: "Premium (lobster)", price: 34.95 },
{ mealName: "Ultimate (whole zebra)", price: 290 }
];

// Editable data
this.seats = ko.observableArray([
new SeatReservation("Steve", this.availableMeals[0]),
new SeatReservation("Bert", this.availableMeals[0])
]);
}
}

例如,new ReservationsViewModel().seats()[0].name 将为您提供“Steve”。

关于knockout.js - ES5 knockout 到 ES6 knockout ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32626745/

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