Javascript 更新 Knockout.js Observable 数组元素值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11246494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Updating Knockout.js Observable array element value
提问by Brainchild
I need to update an observable array element value. The observable array is a collection of class objects. First I need to find out matching object by id and update some other property values of the object.
我需要更新一个可观察的数组元素值。可观察数组是类对象的集合。首先,我需要通过 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)
] )
};
Can anyone suggest the approach of updating the view model? Let's say I want to update booked value to "false" for the seat no 2.
任何人都可以建议更新视图模型的方法吗?假设我想将 2 号座位的预订值更新为“false”。
回答by Niko
That's pretty simple with 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);
}
回答by Stipe
viewModel.seats()[self.No()].Booked(true);