我需要更新可观察的数组元素值。 可观察数组是类对象的集合。 首先我需要通过 id 找出匹配的对象并更新该对象的一些其他属性值。
var Seat = function(no, booked) {
var self = this;
self.No = ko.observable(no);
self.Booked = ko.observable(!!booked);
// Subscribe to the "Booked" property
self.Booked.subscribe(function() {
alert( self.No() );
});
};
var viewModel = {
seats: ko.observableArray( [
new Seat(1, false), new Seat(2, true), new Seat(3, true),
new Seat(4, false), new Seat(5, true), new Seat(6, true),
new Seat(7, false), new Seat(8, true), new Seat(9, true)
] )
};
有人可以建议更新 View 模型的方法吗? 假设我想将 2 号座位的预订值(value)更新为“false”。
最佳答案
knockout 非常简单:
// We're looking for the Seat with this No
var targetNo = 2;
// Search for the seat -> arrayFirst iterates over the array and returns the
// first item that is a match (= callback returns "true")!
var seat = ko.utils.arrayFirst(this.seats(), function(currentSeat) {
return currentSeat.No() == targetNo; // <-- is this the desired seat?
});
// Seat found?
if (seat) {
// Update the "Booked" property of this seat!
seat.Booked(true);
}
关于javascript - 更新 Knockout.js Observable 数组元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11246494/