trigger computed to be recalculated when observableArray element property is changed

别说谁变了你拦得住时间么 提交于 2019-12-24 16:24:39

问题


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.



来源:https://stackoverflow.com/questions/23253469/trigger-computed-to-be-recalculated-when-observablearray-element-property-is-cha

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!