0

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.

JSFiddle with description

My problem illustrated on http://jsfiddle.net/96vdD/7/ and described here:

Three people pass through the foreach. Adding three divs 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 peoples 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.

Problem

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.

Question

How can I have Knockout ignore !visible elements when applying the class="last" rule?

1 Answer 1

4

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/

Sign up to request clarification or add additional context in comments.

2 Comments

However, why would I need to create a computed array? I think using just ko.utils.arrayFilter does the job too (jsfiddle.net/96vdD/10). What is the added value of storing this in a computed array?
If the people array changes (items added or removed), the computed version will also updated the html but ko.utils.arrayFilter version will not. The purpose of computed observables is that they track changes within other observables used for the computation and notify subscribers according to that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.