ES5淘汰赛到ES6淘汰赛

时间:2015-09-17 09:22:14

标签: knockout.js ecmascript-6

我想认真了解有关ES6的更多信息。我一直在网上做一些例子,虽然我得到了大部分内容,但我有时会对哪里开始感到困惑。请注意我在这个ES6和淘汰赛中的超级菜鸟,并希望通过从他们的网站上获取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>

1 个答案:

答案 0 :(得分:5)

首先要做的事情是:您的ES5代码在ES6设置中可以正常工作。

我手边没有淘汰赛进行测试,但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会给你“史蒂夫”。