Reputation: 99
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?
Upvotes: 0
Views: 2423
Reputation: 824
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.
Upvotes: 2
Reputation: 7941
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;
Upvotes: 1