javascript - 集合教程中的 ko.observable 变量

标签 javascript knockout.js observable

在分析collections tutorial时,我不明白两点:

  • 为什么我们必须在 SeatReservation 函数中将 initialMeal 变量定义为 ko.observable?如果我删除 ko.observable, View 中的 foreach 循环将不起作用。

  • initialMeal 是一个数组。因此,应该使用ko.observableArray。但是,ko.observableArray 不起作用。

我在这个 example 中发现了类似的模式。你能帮我澄清这个问题吗?谢谢。

查看

<table>
 <thead><tr>
     <th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
 </tr></thead>
 <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>

View 模型

function SeatReservation(name, initialMeal) {
    var self = this;
    self.name = name;
    self.meal = ko.observable(initialMeal);
}

function ReservationsViewModel() {
    var self = this;
    self.availableMeals = [
        { mealName: "Standard (sandwich)", price: 0 },
        { mealName: "Premium (lobster)", price: 34.95 },
        { mealName: "Ultimate (whole zebra)", price: 290 }
    ];    

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

    self.addSeat = function() {
        self.seats.push(new SeatReservation("", self.availableMeals[0]));
    }
}

ko.applyBindings(new ReservationsViewModel());

最佳答案

why do we have to define initialMeal variable as ko.observable in SeatReservation function? If I remove ko.observable, foreach loop in the View doesn't work.

当它不是可观察值时,它不起作用,因为绑定(bind) meal().mealNamemeal().price 仍然需要可观察值。将它们更改为 meal.mealNamemeal.price 并且绑定(bind)将起作用。

请注意,如果您不使用可观察量,则绑定(bind)是单向的,并且如果加载页面后底层模型值发生更改,则绑定(bind)不会更新。

initialMeal is an array. Therefore, ko.observableArray should be used. However, ko.observableArray does not work.

initialMeal 不是一个数组,它是 self.availableMeals 数组中的一个元素,它是一个对象(例如 { mealName: "Standard (sandwich) “,价格:0})。

关于javascript - 集合教程中的 ko.observable 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25233454/

相关文章:

javascript - 压缩 JavaScript

javascript - Knockoutjs <select> 基于另一个 <select> 不工作

angular - 订阅一个主题,第一次在 init 上不起作用

java - 具有多个可观察值的单个观察者

javascript - 使用 Knockout jQuery 更新 HTML DOM 中的位置

error-handling - 如何在可观察 map (rxjs6,ng6)中抛出错误

javascript - Google map /地点地理编码

javascript - JsFiddle 中的代码不起作用

javascript - 如何在 jQuery 或 JavaScript 中使用 for 设置累计值?

forms - 加载 HTML 对象客户端(表单)