Johan Johan - 3 months ago 10
Javascript Question

Determine if observable has changed in computed

I am implementing a cache function in a computed observable.

Is there any way to invalidate the cache below if the

items
collection differs since the last call?

I have seen examples of dirty checking where a serialized version of the observable is used to determine if the collection has changed, but it's too expensive for me, since there may be hundreds of items.

var itemCache;

var manipulatedItems = ko.pureComputed(function(){
var items = someObervable();
if(!itemCache /* || someObervable.hasChangedSinceLastCall */) {
itemCache = heavyWork(items);
}
return itemCache;
});

var heavyWork = function(items){
// do some heavy computing with items
return alteredItems;
};


In my viewmodel:

myViewModel.itemList = ko.pureComputed(function(){
var result = manipulatedItems();
return result;
});

Answer

Since computed observables always cache the last value, there's no reason to store it separately. In fact, storing it separately can cause trouble with getting the latest data in your application.

var manipulatedItems = ko.pureComputed(function () {
    var items = someObervable();
    return heavyWork(items);
});

var heavyWork = function (items) {
    // do some heavy computing with items 
    return alteredItems;
};