My Appmodel consists of an observable array of comments
self.comments=ko.observableArray([]); // Default Value is an empty array
/*
Here comes some code to initially fill the observable array
with items from an JSON Response
*/
Furthermore I have two computeds which should represent the very first comment and the last comment
self.firstComment = ko.computed(function () {
var sorted = self.comments.sort(function (left, right) {
return left.Id() - right.Id();
});
return sorted[0];
});
self.lastComment = ko.computed(function () {
var sorted = self.comments.sort(function (left, right) {
return left.Id() - right.Id();
});
return sorted[sorted.length - 1];
});
This works perfectly on initializing the application (loading the JSON from Server, build up App model...), but when I add a comment to the array, the computeds do not recognize that the number of array items has changed (as I understood it, an observable array is just an observable where the array properties themselves are observed). So when I do:
self.comments.push(aNewCommentObject);
self.lastComment is still bound to the array item, that it was when the app loaded initially.
I have found this blog post how to force computation by introducing a dummy observable, but I don't like the approach. For what purpose is an observableArray used then and how?
Additional Challenge: I would like to keep the observableArray Items sorted under every circumstance (because its a comment feed which should be just sorted chronologically). I tried to do this whith an computed commentsSorted but also have problems that this does not update when the observableArray has new items, so same problem here. Thats the reason, why I am sorting everytime in firstComment and lastComment.