In this example, Knockout is working as intented. I'm looking for an alternative way of achieving the goal of having a dynamically filled grid with CSS class .last
on every second item. In a way, I'm probably looking for a different approach.
My problem illustrated on http://jsfiddle.net/96vdD/7/ and described here:
Three people
pass through the foreach
. Adding three div
s to the grid. Dynamically, Knockout assigns a css class of last
to every second div
that comes out of the foreach
.
At the same time, each people
s visibility property decides whether or not (s)he will be displayed in the grid.
The CSS will strip the margin of every .last
div
in the grid, to prevent each second div
from being moved to the next 'row'. A common layout technique in CSS.
See what happens when you change Charles' visibility to true
and run the JSFiddle.
The second person in the example, Charles, is not shown in the grid (because his property visible
is set to false
). However, Denise is still moved to the next row. Knockout adds a style="display:none"
to Charles, but also applies the class="last"
rule to him, while ideally I would like Denise to receive the class="last"
as visually she is the second people
in the grid.
How can I have Knockout ignore !visible
elements when applying the class="last"
rule?
You can create a computed array of only visible people:
self.visiblePeople = ko.computed(function() {
return ko.utils.arrayFilter(self.people(), function(person) {
return person.visible;
});
});
then bind on it in your html:
<div class="wrapper" data-bind="foreach: visiblePeople">
Fiddle - http://jsfiddle.net/96vdD/8/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.