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

查看:126
本文介绍了可观察到的数组在敲出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 to observableArrays,则需要对基础数组(在本例中为this())进行操作,然后最后在observableArray上调用valueHasMutated().这样可以确保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.

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

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