I’ve got computed function which should basically listen to any changes in observable array (Items). The problem is that Knockout calls this function on initialisation. I know it does it to figure out its dependencies but in my case it’s a problem as it makes ajax request. Is it any solution beside introducing some counter variable to skip calling ajax on the first call?
Thanks.
function MyViewModel(data) {
var self = this;
self.nameToAdd = ko.observable("");
self.Items = ko.observableArray(data.items || []);
self.add = function () {
self.Items.push({ Name: self.nameToAdd()});
self.nameToAdd("");
};
self.remove = function (item) {
self.Items.remove(item);
};
ko.computed(function () {
$.ajax({
url: "myUrl",
type: 'POST',
data: ko.toJSON(self.Items),
contentType: 'application/json'
});
}, self);
}
I think what you really want is to manually subscribe to your Items array so when it is updated you call the ajax function.
The function passed will only be called when a change has occured to the array itself, thus, not being called on initialization. See fiddle for example.