Here is the HTML code with the data-bind elements:
div data-bind="foreach: clientRequests" id="test2">
<div class="list-group" >
<a href="#" class="list-group-item active"><b data-bind="text: client"></b></a>
<a href="#" class="list-group-item"><b>Priority: </b><b data-bind="text: client_priority"></b></a>
<a href="#" class="list-group-item"><b>Title: </b><b data-bind="text: title"></b></a>
<a href="#" class="list-group-item"><b>Description: </b><b data-bind="text: description"></b></a>
<a href="#" class="list-group-item"><b>Product Area: </b><b data-bind="text: product_area"></b></a>
<a href="#" class="list-group-item"><b>Target Date: </b><b data-bind="text: target_date"></b></a>
<a href="#" class="list-group-item"><b>Ticket URL: </b><b data-bind="text: ticket_url"></b></a>
</div>
</div>
This is how I am passing an array called requestsArray
to the data-bind loop:
ko.cleanNode(document.getElementById('test2'));
ko.applyBindings({
clientRequests: requestsArray
}, document.getElementById('test2'));
Through different AJAX calls, various requestArrays are returned. After the initial page load, an AJAX call fetches one instance of the requestArray which might contain 10 items. The foreach loop works as expected, and all 10 items are displayed on the page. However, in a second AJAX call, the array may only have 5 items. This causes each item to be repeated twice, resulting in a total of 10 items being displayed on the page.
The issue arises from the fact that even though
ko.cleanNode(document.getElementById('test2'))
is invoked before:
ko.applyBindings({
clientRequests: requestsArray
}, document.getElementById('test2'))
with each new array, the number of HTML elements created by each iteration of foreach
continues to increase. In Vue.js, passing a new array for data-binding and looping is destructive and does not retain any elements from the previous iteration over the array.
Using ko.cleanNode
does not resolve this scenario, and while there is an example in the documentation that demonstrates what seems to be the correct procedure, it only removes one HTML element at a time using a button and self.array.remove(this)
. Adapting this to completely clear out all HTML elements created from a foreach
iteration is not straightforward.