如何使用 Knockout.js 在某个位置将项目添加/插入到 ObservableArray 中 [英] How to add/insert an item into an ObservableArray at a certain position with Knockout.js

查看:24
本文介绍了如何使用 Knockout.js 在某个位置将项目添加/插入到 ObservableArray 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现的所有淘汰赛示例似乎都使用以下内容在 ObservableArray 的末尾添加了一个新项目:

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.

如何在 ObservableArray 的某个位置添加一个项目?

例如.类似:

viewModel.SomeItems.push(someNewItem, indexToInsertItAt);

推荐答案

你应该能够使用原生的 JavaScript splice 方法 -

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

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

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

此处的示例(不是特定于 Knockout 的) - 如何插入将项目放入特定索引处的数组?

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

来自淘汰赛文档 -

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

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.

这篇关于如何使用 Knockout.js 在某个位置将项目添加/插入到 ObservableArray 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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