简体   繁体   中英

knockout observableArray performance

How to add all values to observableArray in one time? Adding values in loop works very slow in my case. Here is jsfiddle example. jsfiddle

var myArray = ko.observableArray([]);
var valuesToInsert = [1,2,3];
myArray.push.apply(myArray, valuesToInsert);

that's it

Since you're clearing out the entire observable array, one way you can accomplish this is:

var viewModel = {
    name: "base",   
    addingValue:new ko.observable(),
    someArr: new ko.observableArray(["123","432","sdafasd","xrere"]),
    add: function()
    {
        this.someArr.push(this.addingValue());
    },
    updateSomeArr:function()
    {
        var temp = [];

        for(var i=0;i<5;i++)
        {
            temp.push("555565");
        }

        this.someArr(temp);
    }
}

There is already a selected answer, but I thought that the following would help. You can disable the observing behavior by executing your observable array to get the underlying array implementation:

var underlyingArray = viewModel.someArr();

You can then add items to underlyingArray without firing off someArr events. Once you're done adding items, call:

viewModel.someArr.valueHasMutated();

This will cause the event to fire notifying all observables dependent on viewModel.someArr().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM