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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7317907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:46:32  来源:igfitidea点击:

How to add/insert an item into an ObservableArray at a certain position with Knockout.js

javascriptmvvmknockout.js

提问by Mark Robinson

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

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

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?

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

eg. something like:

例如。就像是:

viewModel.SomeItems.push(someNewItem, indexToInsertItAt);

回答by ipr101

You should be able to use the native JavaScript splicemethod -

您应该能够使用原生 JavaScriptsplice方法 -

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

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

文档在这里 - 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?

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

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.

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

回答by Travis Cavanaugh

For knockout use

用于淘汰赛

viewModel.SomeItems.unshift(someNewItem);

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

另见:http: //knockoutjs.com/documentation/observableArrays.html

回答by Adam Tegen

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.

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

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');