且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

KnockoutJS ObservableArray数据分组

更新时间:2023-12-05 13:16:16

KO中没有其他任何东西可以使这一切变得简单.

There is not anything else built into KO to make this any easier.

有很多方法可以使这项工作.例如,您可以将observableArrays扩展为具有distinct函数.然后,您可以像这样创建observableArray:

There are many ways that you could make this work. For example, you could extend observableArrays to have a distinct function. Then, you can just create your observableArray like:

this.people = ko.observableArray([
       new Person("Jimmy", "Friend"),
       new Person("George", "Friend"),
       new Person("Zippy", "Enemy")
]).distinct('type');

distinct函数可能类似于:

ko.observableArray.fn.distinct = function(prop) {
    var target = this;
    target.index = {};
    target.index[prop] = ko.observable({});    

    ko.computed(function() {
        //rebuild index
        var propIndex = {};

        ko.utils.arrayForEach(target(), function(item) {
            var key = ko.utils.unwrapObservable(item[prop]);
            if (key) {
                propIndex[key] = propIndex[key] || [];
                propIndex[key].push(item);            
            }
        });   

        target.index[prop](propIndex);
    });

    return target;
};    

它支持链接,因此您可以使用不同的属性多次调用distinct.

It supports chaining so you could call distinct multiple times with different properties.

此处提供示例: http://jsfiddle.net/rniemeyer/mXVtN/

这确实会在每次更改时重建索引一次,因此,如果您有大量的项目列表,则可能需要探索其他方法(手动订阅)以从索引"数组中添加/删除项目.

This does rebuild the index once on each change, so if you have a huge list of items, then you would want to potentially explore other ways (manual subscriptions) for adding/removing items from the "index" arrays.