trigger computed to be recalculated when observabl

2019-08-15 00:32发布

问题:

I have observableArray with elements (elements are not observables, but some unobservable objects). I have also computed variable that depands on observableArray. If I push elements into array, then everything works (I mean - computed variable is recalculated).

However, if I change some properties of observableArray single items, then computed is not recalculated:

var myObsArr = ko.observableArray();

// myObsArr is loaded using ko.mapping.fromJS with data from server
// but I am using custom mapping that won't create observables for observableArray items, part of my custom mapping (the one that corresponds to observable item) is something like this:
 create: function (options) {
    // here are some manipulations and
    return ko.toJS(options.data); //doesn't create observables for observableArry items
}

var computedArr = ko.computed(function() {
   var t = self.myObsArr();
   // do manipulations on t and return manipulated array
});

// later I need to change some elements of observable array, for example:
myObsArr[0].Month = "Mar"; //doesn't trigger computed to be recalculated

How to trigger computed to be recalculated when any object inside observable array is changed?

回答1:

You can call valueHasMutated method on your myObsArr after modifying one of its elements. It will trigger the knockout dependency tracking and your computedArr will be notified about the change:

myObsArr[0].Month = "Mar";
myObsArr.valueHasMutated();

However you have to remember to call this every time you change an item in array so you are probably better to turn your Month into an ko.observable because in this case the ko change tracking will pick the changes automatically and it will notify your computed without any additional code.



标签: knockout.js