I have a template binding to an observableArray
<ul data-bind="template: { name: 'defaultTemplate', foreach: itemsArray}"></ul>
...
And i need to refresh data each time by clicking a link
<a data-bind="click: LoadData"><span>Refresh</span></a>
The first version of my viewModel:
function viewModel (){
this.itmesArray = ko.observableArray([]);
self = this;
this.LoadData(){
if('undefined' != typeof MusicArray )
self.itmesArray.removeAll();
LoadDataFromServerAsync(self.itmesArray);
}
//ini
LoadData();
...
}
But the problem is that the data is loaded from server in async, so when i click the link fast with little time interval, then the data may duplicate multi times in my obeservable array.
So i think i need load data to a new array in each refreshing.
Then the second version of viewModel:
function viewModel (){
this.itmesArray = ko.observableArray([]);
self = this;
this.LoadData(){
if('undefined' != typeof MusicArray )
self.itmesArray.removeAll();
var tempArray = new Array();
LoadDataFromServerAsync(tempArray);
self.itmesArray(tempArray);
}
//ini
LoadData();
...
}
And the new problem is that the UI could not sense the changes of array, it seems self.itmesArray(tempArray) will construct a new observableArray object, but the template bindging is still tracking the old observableArray object, I’m not sure about this.
So i want to know how to notify the template/ui binding that my array has changed or is there any other workaround to fix my problem?
Added: Code on jsFiddle http://jsfiddle.net/zzcJC/10/
you can do as Gene suggest. for doing all on client side, you can create a helper object tha encapsulates the logic: it fires the requests, gets the responses, has an “abort” method to stop the request (if the user press “refresh” while still waiting for data), and updating the viewmodel only when all the data is arrived.
I created a jsFiddle: http://jsfiddle.net/saurus/dE6S9/
This uses “setTimeout()” to simulate ajax calls, stores the timeouts ids on an array (you would store the xhr returned by ajax calls), and calling “cancelTimeout()” to abort calls (you will use “xhr.abort or similar).