可观察数组在knockout.js 中推送多个对象 [英] Observable array push multiple Objects in knockout.js

查看:28
本文介绍了可观察数组在knockout.js 中推送多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ko 里有没有同时推送多个元素的选项?

Is there any option in ko, which pushes multiple elements at same time?

我有两个元素需要插入到一个名为 StatesList 的可观察数组中,我无法继续.我如何才能同时添加它们.

I have two elements which needs to be inserted into a observable array called StatesList, I can not proceed further. How can I add them both.

见下图:

var model1 = jQuery.parseJSON(ko.toJSON(argsToPost));
var model = jQuery.parseJSON(ko.toJSON(self.StateModel));

我需要将两者都添加到我的 ObservableArray

i need to add both to my ObservableArray

self.StatesList.push(model);
self.StatesList.push(model1);

这是插入不同的记录,我想同时插入两个对象

This is inserting into different records, I want to insert both objects at the same time

推荐答案

我们确实有 ko.utils.arrayPushAll(array, valuesToPush) 作为您可以使用的实用函数.虽然它不能直接从 observableArrays 中使用.

We do have ko.utils.arrayPushAll(array, valuesToPush) as a utility function that you can use. It is not available directly off of observableArrays though.

如果您将 pushAll 添加到 observableArrays,您可能希望对底层数组进行操作(在您的情况下为 this()),然后在该数组上调用 valueHasMutated()observableArray 最后.这将确保 observableArray 的订阅者只收到一次最终结果而不是每次推送的通知.

If you add your pushAll to observableArrays, you would want to operate on the underlying array (this() in your case) and then call valueHasMutated() on the observableArray at the end. This will ensure that subscribers to the observableArray are only notified once with the end result rather than with each push.

在 KO 核心中,它也需要事先调用 valueWillMutate().

In KO core, it would need to call valueWillMutate() beforehand as well.

重点是我不建议使用您发布的代码,因为它会在每次推送时发出通知,如果您推送许多项目,这可能会对性能产生影响.

The point was that I would not recommend using the code that you posted, as it will notify on every push, which can have a performance impact if you are pushing many items.

在核心中,我们可能会执行以下操作:

ko.observableArray.fn.pushAll = function(valuesToPush) {
    var underlyingArray = this();
    this.valueWillMutate();
    ko.utils.arrayPushAll(underlyingArray, valuesToPush);
    this.valueHasMutated();
    return this;  //optional
};

同样的讨论发生在 John PapaRP Niemeyer 之间.可以在此处找到该链接.因此,仅在此处发布有用的提示作为答案.

The same discussion happened between John Papa and RP Niemeyer. The link can be found here. Hence, posted only useful tips as an answer here.

这篇关于可观察数组在knockout.js 中推送多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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