Reputation: 2706
Using knockout.js, I have a list of items that I filter on search using ko.utils.arrayFilter.
The filtering part works ok, but then when I delete the search term and the list repopulates as the full list, some of the DOM elements lose their id. How can I make them not lose their id? What am I missing?
In particular, the items with the id "tabsDiv1", "tabsDiv2", etc lose their ids.
Thanks in advance for your help, I'm stumped!
full git repo here with example github pages site: https://github.com/andrewcockerham/UdacityFENDP5NeighborhoodMap
var ViewModel = function() {
var self = this;
this.placeList = ko.observableArray([]);
this.filter = ko.observable("");
this.filteredItems = ko.computed(function() {
var filter = self.filter().toLowerCase();
if (!filter) {
return this.placeList();
} else {
return ko.utils.arrayFilter(self.placeList(), function(item) {
return item.name().toLowerCase().indexOf(filter) !== -1;
});
}
}, this);
Upvotes: 0
Views: 295
Reputation: 134521
The problem is that you're setting the ids of the tabs manually on load instead of letting knockout set it. When knockout renders the page, it will use the current state of the dom elements as templates for your tabs. In this case, your elements had blank ids. I see you apparently had knockout set the id at one point but you commented it out. You should go back and use knockout to add the id if you really needed it.
<div class="tabsDiv col-md-12 col-sm-12" id=""
style="display: none; padding-left: 0px; padding-right: 0px;
border-style: solid;border-width:1px;"
>
<!-- data-bind="attr: { id: 'tabsDiv' + $index() }" -->
...
<script>
window.onload = function() {
// get all tabDiv elements and add id with index to each one
var tabsDivArray = document.getElementsByClassName("tabsDiv");
for (var i = 0; i < tabsDivArray.length; i++) {
var tabsDiv = tabsDivArray[i];
tabsDiv.id = 'tabsDiv' + i.toString();
};
...
This might not be the only problem, but it's a start. You're mixing up a lot of knockout and manual dom manipulation and jquery. You really should try to limit the mixing up to keep it manageable. It would be a tough read for anyone else who came and looked at this.
Upvotes: 2