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

查看:411
本文介绍了如何使用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?

来自Knockout文档 -

From the Knockout docs -


对于修改数组内容的函数,例如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天全站免登陆