更新 Knockout.js Observable 数组元素值 [英] Updating Knockout.js Observable array element value

查看:14
本文介绍了更新 Knockout.js Observable 数组元素值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更新一个可观察的数组元素值.可观察数组是类对象的集合.首先,我需要通过 id 找出匹配的对象并更新该对象的其他一些属性值.

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.

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)
    ] )
};

谁能建议更新视图模型的方法?假设我想将 2 号座位的预订值更新为false".

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.

http://jsfiddle.net/2NMJX/3/

推荐答案

淘汰赛很简单:

// 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);
}

http://jsfiddle.net/2NMJX/4/

这篇关于更新 Knockout.js Observable 数组元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆