gpt4 book ai didi

javascript - knockout : Nested observableArrays and Nested ForEach

转载 作者:行者123 更新时间:2023-11-28 06:41:31 29 4
gpt4 key购买 nike

免责声明 - 我担心这个问题可能是重复的,因为功能看起来很基本,所以我知道我可能会得到一个骗局。但我找不到有效的解决方案

所以我有一个可观察的数组设置如下

self.meetingAttendees = ko.observableArray([
{
AttendeeTypeId: ko.observable(1),
AttendeeNames: ko.observableArray([
{ Name: ko.observable("Nemo"), CurrentEdit: ko.observable(0) }
]),
AttendeeSiteNumber: ko.observable(""),
StudentNames: ko.observableArray([
{ Name: ko.observable("Flava Flave"), CurrentEdit: ko.observable(1) }
]),
Email: ko.observable(""),
Telephone: ko.observable("")
}]);

我的“问题”HTML 是:

<tbody data-bind="foreach: $root.meetingAttendees">
<tr>
<td class="attendeeNameCol textAlignCenter">
<div class="textAlignCenter" data-bind="foreach:{data: AttendeeNames, as: 'Attendee'}">
<input class="formInput" data-bind="textInput: Attendee.Name()"/>
<span class="glyphicon glyphicon-remove nameRemove" data-bind="click:$root.removeName.bind($data,$index(),'AttendeeNames',$parentContext.$index())"></span>
</div>
<span data-bind="visible:$root.meetingAttendees()[$index()].AttendeeTypeId() == 1,click:$root.addName.bind($data,$index(),'AttendeeNames',$index())" class="addAnotherText">(+) Add Another Parent</span>
</td>
</tr>
</tbody>

一切似乎都工作正常,并且使用虚拟数据,它可以正确绑定(bind)。但是,当我将一个元素插入 attendeeNames

self.meetingAttendees()[parentIndex].AttendeeNames().push(
{名称:ko.observable(""),当前编辑:ko.observable(1)}
);

我的 View 没有插入另一个元素。我检查了数组,它确实显示已添加一个元素,因此我认为这是一个绑定(bind)问题。

我的问题是如何正确绑定(bind),以便嵌套的 foreach 语句正确更新和显示嵌套的 observableArrays 中的信息?

最佳答案

因此,AttendeeNames 是一个 knockout 的可观察数组。如果您对其执行 console.log,您会发现返回的是一个函数而不是一个数组。该变量实际上可以通过两种方式使用。

如果您将其称为 AttendeeNames(),您将获得底层数组,而无需任何 knockout 功能。因此,您可以随心所欲地修改这个底层数组,并将其打印出来,看起来数据正在更改,但您的 View 不会更新,因为 knockout 无法知道这些更改。您可以使用 AttendeeNames.valueHasMutated() 手动通知可观察者此更改。请注意它是如何使用 Knockout 功能的 - AttendeeNames 之后没有 ()。有时,如果您认为可能会进行大量更改,并且由于性能原因不想在一切完成之前更新 View ,那么这可能会很有用。

当您调用 AttendeeNames.push() 时,您实际上是在使用 knockout 功能,该功能会将项目添加到底层数组通知 View 它需要更新。

回顾:

以下代码片段具有相同的功能:

AttendeeNames.push(item);

AttendeeNames().push(item);
AttendeeNames.valueHasMutated();

通过使用 () 访问 knockout 可观察量,您将绕过所有 knockout 内容并获取封装的 Javascript 值。

关于javascript - knockout : Nested observableArrays and Nested ForEach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33765424/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com