How to create a computed observable array in Knockout

后端 未结 5 1168
小蘑菇
小蘑菇 2021-01-07 16:25

I would like to know how to create a computed observable array.

In my view model, I have 2 observable arrays, and I would like to have a computed observable array

5条回答
  •  粉色の甜心
    2021-01-07 16:37

    I know this is an old question but I thought I'd throw my answer in there:

    var u = ko.utils.unwrapObservable;
    
    ko.observableArray.fn.filter = function (predicate) {
        var target = this;
    
        var computed = ko.computed(function () {
            return ko.utils.arrayFilter(target(), predicate);
        });
    
        var observableArray = new ko.observableArray(u(computed));
    
        computed.subscribe(function (newValue) { observableArray(newValue); });
    
        return observableArray;
    };
    

提交回复
热议问题