问题
I've been experimenting with knockoutjs, reworking an existing project.
My current layout has the logic to determine if the rendered <div>
tag is the first or fourth item.
if (index % 4 == 0) addClass('omega');
if (index % 4 == 1) addClass('alpha');
Is there any built-in functionality of knockout that can template similar conditions?
回答1:
A few options for you:
there is work being done to add a
$index
variable when doing aforeach
in KO. This is scheduled to be included in KO 2.1. The pull request is here: https://github.com/SteveSanderson/knockout/pull/182there is a
repeat
binding here: https://github.com/mbest/knockout-repeat that gives you better access to the actual index.if you are using an observableArray, then there is an easy way to create an index each item.
It would look like this:
//track an index on items in an observableArray
ko.observableArray.fn.indexed = function() {
//whenever the array changes, make one loop to update the index on each
this.subscribe(function(newValue) {
if (newValue) {
var item;
for (var i = 0, j = newValue.length; i < j; i++) {
item = newValue[i];
if (!ko.isObservable(item.$index)) {
item.$index = ko.observable();
}
item.$index(i);
}
}
});
this.valueHasMutated();
return this;
};
You would initialize an observableArray to be indexed like:
this.myArray = ko.observableArray().indexed();
Now, when the observable array is manipulated, it will take one pass through the items and correct the index. This is better than inside your foreach
looking up the index of each item each time.
来源:https://stackoverflow.com/questions/9760861/apply-a-class-to-every-nth-template-element-with-knockoutjs