How to replace a given index element in knockoutjs

后端 未结 5 613
时光说笑
时光说笑 2020-12-15 04:55

How do you replace a given index in an observableArray with another element.

I have: ViewModel.Elements()[index]

how can i replace it with anot

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 05:01

    Like dvijaz correctly points out, the accepted answer replaces a given value. This can cause problems when the given value is not unique in the array.

    Instead of slicing the array and then gluing the array back together, I did the following which is more readable IMHO:

    ViewModel.Elements()[index] = yourNewElement;
    ViewModel.Elements.valueHasMutated();
    

    Thanks to RP Niemeyer for pointing out how .replace works internally.

    You can also extend observableArray to support this:

    ko.observableArray.fn.replaceIndex = function(index, newValue) {
        this.valueWillMutate();
        this()[index] = newValue;
        this.valueHasMutated();
    };
    

    Which means you can do the following:

    var arr = ko.observableArray([1, 2, 1, 4]);
    arr.replaceIndex(2, 3); 
    console.log(arr()); // logs [1, 2, 3, 4]
    

提交回复
热议问题