KnockoutJS ObservableArray数据分组

far*_*ina 14 knockout.js

KnockoutJS是否有功能,而我可以采取以下方式:

    var myArray = ko.observableArray([
      { name: "Jimmy", type: "Friend" },
      { name: "George", type: "Friend" },
      { name: "Zippy", type: "Enemy" }
    ]);
Run Code Online (Sandbox Code Playgroud)

然后在"type"字段上选择distinct,产生如下所示的结果:

(pseudo code)
    var distinct = myArray.distinct('type')
      // Returns array of two arrays
      //  distinct[0] is an array of type=Friend
      //  distinct[1] is an array of type=Enemy 
Run Code Online (Sandbox Code Playgroud)

我知道ko.utils.arrayGetDistinctValues,但这并不完全符合我的要求.我也知道我可以使用ko.utils.arrayGetDistinctValues写几个循环来得到我想要的东西,我只是想知道是否还有其他东西被KnockoutJS烘焙,我忽略了.

RP *_*yer 35

KO中没有任何其他内容可以使这更容易.

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

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

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;
};    
Run Code Online (Sandbox Code Playgroud)

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

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

这确实会在每次更改时重建索引一次,因此如果您有大量项目,那么您可能希望探索其他方式(手动订阅)来添加/删除"索引"数组中的项目.


小智 7

我在jsfiddle中简化了RP Niemeyer的版本,不使用distinct函数.请参考这里:jsfiddle

<ul data-bind="foreach: choices">
<li>
    <h2 data-bind="text: $data"></h2>
    <ul data-bind="foreach: $root.people">
        <!-- ko if: $parent === type() -->
        <li data-bind="text: name"></li>
        <!-- /ko -->
    </ul>
    <hr/>
</li>
Run Code Online (Sandbox Code Playgroud)

var Person = function(name, type) {
   this.name = ko.observable(name);
   this.type = ko.observable(type);    
}

var ViewModel = function() {
    var self = this; 
    this.choices = ["Friend", "Enemy", "Other" ];
    this.people = ko.observableArray([
           new Person("Jimmy", "Friend"),
           new Person("George", "Friend"),
           new Person("Zippy", "Enemy")
    ]);

    this.addPerson = function() {
        self.people.push(new Person("new", "Other"));
    };

    this.removePerson = function(person) {
      self.people.remove(person);  
    };
};


ko.applyBindings(new ViewModel());
Run Code Online (Sandbox Code Playgroud)

谢谢Niemeyer.