Refresh observableArray when items are not observables

前端 未结 5 1220
孤街浪徒
孤街浪徒 2020-12-01 15:58

Basically I have an observableArray and the values for each item are not an observable. This means when I change an item value the UI within a foreach loop of the observable

5条回答
  •  暖寄归人
    2020-12-01 16:15

    I'm using Knockout with deferUpdates and the solution of JotaBe needs an update.

    It seems Knockout detects, on remove/add, that is the same item and so don't refresh the array.

    I have adopted the following solution:

    ko.observableArray.fn.refresh = function (item, index) {
        if (index==null) index = this['indexOf'](item);
        if (index >= 0) {
            this.splice(index, 1, ko.utils.extend({}, item)) // create new item
            //this.splice(index, 1);
            //this.splice(index, 0, item);
        }
    }
    

    and it refresh the array correctly! :-)

    Note I added a second argument to refresh function, for specifying index when index is given, for avoiding indexOf run.

提交回复
热议问题