替换 observableArray 中的项目 [英] Replacing item in observableArray

查看:20
本文介绍了替换 observableArray 中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用新内容替换 observableArray 中项目的所有内容.

I'm trying to replace all of the contents of an item in an observableArray with new content.

var oldLocation = ko.utils.arrayFirst(self.locations(), function (item) {
    return item.id == value.id;
});
self.locations.replace(self.locations.indexOf(oldLocation), new location(value));
self.locations.valueHasMutated();

我也试过

self.locations[self.locations.indexOf(location)] = new fizi.ko.models.location(value);

但是没有任何效果.正在正确检索索引,但未更新项目.

But nothing is working. The index is being properly retrieved but the update of the item isn't happening.

推荐答案

replace 函数接受两个参数,您要替换的项和要替换的新项.您正在传递索引代替要替换的项目,因此它不起作用.

The replace function accepts two parameters, the item you want to replace and the new item you want to replace it with. You are passing in the index in place of the item to replace so it doesn't work.

替换调用应该是:

self.locations.replace(oldLocation, new location(value));

顺便说一句,你不应该在那里需要 valueHasMutated() 调用,它会被 replace() 调用调用.

On a side note, you shouldn't need the valueHasMutated() call there, it will get invoked by the replace() call.

旁注,许多原生 Array 函数可用于可观察数组.它们被转发到底层数组值,根据需要触发突变通知.其中包括:

Side note, many of the native Array functions are available for observable arrays. They are forwarded to the underlying array value triggering notifications of mutations as needed. These include:

poppushreverseshiftsortspliceunshiftslice(只读).

pop, push, reverse, shift, sort, splice, unshift, slice (readonly).

Knockout 提供了这些额外的方法,应在此处(当前为 v3.5.1)记录:

Knockout provides these additional methods which should be documented here (currently v3.5.1):

removeremoveAlldestroydestroyAllindexOf替换排序反转

这篇关于替换 observableArray 中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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