1

I can't figure out how to work with iterations in foreach of KOjs. What I need is to group contents of an array like this

Var x = [{name: Joel, sex: male}, {name: Eric, sex: male},{name:Elliot, sex:female}, {name:Mary, sex:female}]

So the resulting data-bind foreach would display the sex of the person, but only once as a label. Something like this

-male
Joel
Eric
-female
Elliot
Mary

With normal for loops it is as simple as making a variable that holds last entry's gender, and prints the new one if it changes. Something like

If(this.sex != cachedSex){
 cachedSex=this.sex;
console.log(cachedSex);
}

But I can't figure it out how to make this in KO.js Please give me an advice.

4

2 回答 2

1

Knockout 让您可以使用计算的 observables 以巧妙的方式解决这个问题 :)

如果你想要一个完整的代码示例,这里有一个说明这个解决方案的小提琴

假设你所有的人都被称为people,它是observableArray

var that = this;
this.people = ko.observableArray([{name: Joel, sex: male}, {name: Eric, sex: male},{name:Elliot, sex:female}, {name:Mary, sex:female}])

现在我们只希望男性和女性分开:

this.males = ko.computed(function(){
    return that.people().filter(function(person){
        return person.sex === "male";
    });
});
this.females = ko.computed(function(){
    return that.people().filter(function(person){
        return person.sex === "females ";
    });
});

(当然——如果你经常重复这种代码——用它做一个函数而不是重复你自己:))

然后就可以foreach正常绑定了,一次females又一次males

于 2013-09-08T08:13:18.273 回答
0

本杰明的回答是正确的,但还有另一种方法,无需创建额外的 observableArrays。在视图中,您可以简单地进行 foreach 绑定并在那里放置一些逻辑来处理过滤。它是最简单的方法,但您可能会争辩说,可能会有更适合的替代品,例如 benjamins,具体取决于您的应用程序

男士

这将允许您在视图中进行一些基本过滤。您还可以设置一个自定义绑定处理程序,您可以将其传入过滤器以使其更加高效和干净

于 2013-09-08T13:35:41.577 回答