我遇到了一种情况,我需要替换可观察数组中某个位置的某个项目。现在我正在使用切片方法在下面进行操作。 Knockout.js 中是否内置了更好的方法来在某个位置执行此操作?我什至考虑进行推送,然后使用 order 属性对该行进行排序,但我有很多行,并且认为这太多了。
var position = ko.utils.arrayIndexOf(self.list(), game);
if (position != -1) {
self.list.remove(self.game);
self.list.splice(position, 0, newGame);
}
带有替换的代码,尝试更新具有名为 Name 的新属性的属性匹配
var game = self.game;
if (game) {
var position = ko.utils.arrayIndexOf(self.list(), game);
if (position != -1) {
if (game.Matchup) {
game.Matchup = new Matchup(response.Data);
game.Modified(true);
}
else if (self.game) {
game = new Matchup(response.Data);
}
self.list.replace(self.list()[position], game);
}
}
HTML
<!-- ko foreach: Games -->
<td class="item-container draggable-item-container clearfix">
<div class="item clearfix draggable-active draggable-item" data-bind="draggableCss: { disabled: $data.Disabled(), matchup: $data.Matchup }, draggableGameHandler : { disabled: !$data.Matchup, disabledDrop: $data.Disabled() }, delegatedClick: $root.members.eventSchedule.editGame.open.bind($data, true, ($data.Matchup && $data.Matchup.Type == '@((int)ScheduleType.Pool)'), $parent.Games)">
<span data-bind="if: $data.Matchup">
<span data-bind="attr: { title: Matchup.Title }"><span data-bind="html: Matchup.Name"></span></span>
</span>
</div>
</td>
<!-- /ko -->
data-bind="html: Matchup.Name"
不会通过替换进行更新。
最佳答案
替换可观察数组中的项目
replace
方法是替换可观察数组中的项目的一种选择。对于您的情况,您可以这样调用它:
list.replace(game, newGame);
当可观察的依赖项发生变化时,绑定(bind)会更新
但是您的问题不仅仅是替换数组中的项目。您已经说过绑定(bind) html: Matchup.Name
没有更新,所以让我们看看什么可能导致它更新:
- 如果
Name
是一个可观察的,修改Name
将导致更新。 - 如果
Matchup
是一个可观察的,修改它会导致更新,但是你必须像Matchup().Name
那样绑定(bind)它并将其更新为game.Matchup(Matchup(response.Data));
. - 用新对象替换可观察数组中的条目(是
Games
还是list
?)将导致整个内部模板重新渲染,显然会替换每个绑定(bind)。
查看您的代码,我可以看到在一种情况下( if (game.Matchup)
),这三件事都没有发生,因此 Knockout 无法知道更新绑定(bind)。前两个显然没有发生,尽管您确实调用 replace
在数组上,它相当于:
list.replace(game, game); // replace the item with itself
foreach
绑定(bind)不会将上述内容视为更改,并且不会更新任何内容。因此,要更新绑定(bind),您需要对可观察对象进行真正的更新。
进一步评论
要获取可观察数组中项目的索引,请使用 indexOf
方法:
var position = self.list.indexOf(game);
要替换特定索引处的项目,请使用 splice
第二个参数为 1
的方法:
self.list.splice(position, 1 /*how many to remove*/, newGame);
关于javascript - 使用 Knockout.js 中的新项目更新可观察数组的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23126127/