如何使用 Knockout.js 将项目添加/插入到 ObservableArray 的某个位置

发布于 2024-12-03 09:41:44 字数 306 浏览 0 评论 0原文

我发现的所有淘汰示例似乎都使用类似以下内容将新项目添加到 ObservableArray 的末尾:

viewModel.SomeItems.push(someNewItem);

这当然会将项目放在数组的末尾。

如何将项目添加到 ObservableArray 的某个位置?

例如。像这样的东西:

viewModel.SomeItems.push(someNewItem, indexToInsertItAt);

All the knockout examples I have found seem to add a new item to the end of an ObservableArray using something like:

viewModel.SomeItems.push(someNewItem);

This of course places the item at the end of the array.

How to I add an item to the ObservableArray at a certain position?

eg. something like:

viewModel.SomeItems.push(someNewItem, indexToInsertItAt);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蓝天 2024-12-10 09:41:44

您应该能够使用本机 JavaScript splice 方法 -

viewModel.SomeItems.splice(2,0,someNewItem);

此处的文档 - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice

此处示例(并非针对淘汰赛) - 如何将项目插入到数组中的特定索引处?

来自淘汰赛文档 -

对于修改数组内容的函数,例如push和
splice, KO 的方法自动触发依赖跟踪
机制,以便所有注册的侦听器都收到更改通知,
并且您的用户界面会自动更新。

You should be able to use the native JavaScript splice method -

viewModel.SomeItems.splice(2,0,someNewItem);

Docs here - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice

Example here (not Knockout specific) - How to insert an item into an array at a specific index?

From the Knockout docs -

For functions that modify the contents of the array, such as push and
splice, KO’s methods automatically trigger the dependency tracking
mechanism so that all registered listeners are notified of the change,
and your UI is automatically updated.

街角卖回忆 2024-12-10 09:41:44

对于敲除使用

viewModel.SomeItems.unshift(someNewItem);

另请参阅:http://knockoutjs.com/documentation/observableArrays.html

For knockout use

viewModel.SomeItems.unshift(someNewItem);

See also: http://knockoutjs.com/documentation/observableArrays.html

撩发小公举 2024-12-10 09:41:44

我制作了这个扩展功能,它对我来说效果很好。如果我添加到稀疏数组的末尾,则 Splice 对我不起作用。

ko.observableArray.fn.setAt = function(index, value) {
    this.valueWillMutate();
    this()[index] = value;
    this.valueHasMutated();
}

这甚至适用于:

var a = ko.observableArray(['a', 'b', 'c']);
a.setAt(42, 'the answer');

I made this extension function which worked nicely for me. Splice wasn't working for me if I was adding to the end of a sparse array.

ko.observableArray.fn.setAt = function(index, value) {
    this.valueWillMutate();
    this()[index] = value;
    this.valueHasMutated();
}

This even works with:

var a = ko.observableArray(['a', 'b', 'c']);
a.setAt(42, 'the answer');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文