0
votes

Using the Knockout JS set visible: data-binding on items in an observable array. Is there a way I can get a count in Knockout JS of the number of items specifically with the visible data-binding = true?

I tried something like this (not working):

    var visibleItems = ko.utils.arrayFilter(self.MyItems(), function(item) {
        return item.visible == true;
    });
    var result = visibleItems().length;

In this test, item.visible is undefined. That's what I'm looking for, how can I get to Knockout JS' visible status property value that corresponds to their "data-bind=visible:" Is that accessible somewhere within item?

2
Is item.visible an observable or just a regular property (i.e. do you need item.visible() == true)?Mark
the code above isn't working, item.visible is undefined, that's what I'm really asking. In my html code, I'm saying data-bind="visible:blah". How can I get to the knockout js "visible" property in my ko.computed observable? Surely, it must be accessible somewhere in its APIJohn McMillion
Why are you trying to access the visible binding and not "blah", which you are binding to, and is presumably an observable property on one of your own javascript objects?Mark
I'm trying to get the total count of visible objects. I manipulate it with several different filters.John McMillion
It sounds like it might be easier to have the visibleItems computed array on your root view model and bind to that, instead of showing all the items and setting the visible binding for each one. Then its length will always match the number of items being displayed.Mark

2 Answers

2
votes

Unless items in your observable array self.MyItems have a visible property, what you are trying to do cannot be done. The visible binding within Knockout changes the DOM element's display attribute rather than altering the underlying data.

From the documentation on the visible binding:

  • When the parameter resolves to a false-like value (e.g., the boolean value false, or the numeric value 0, or null, or undefined), the binding sets yourElement.style.display to none, causing it to be hidden. This takes priority over any display style you’ve defined using CSS.

  • When the parameter resolves to a true-like value (e.g., the boolean value true, or a non-null object or array), the binding removes the yourElement.style.display value, causing it to become visible.

1
votes

I believe that you need to use a ko.computed. the reason being is that what you originally had would only get calculated once.

var visibleItems = ko.computed(function () {
    return ko.utils.arrayFilter(self.MyItems(), function(item) {
        return item.visible == true;
    });
});

var result = visibleItems().length;