更改observableArray元素的属性时,将计算要重新计算的触发器 [英] trigger computed to be recalculated when observableArray element property is changed

查看:75
本文介绍了更改observableArray元素的属性时,将计算要重新计算的触发器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有observableArray元素(元素不是可观察的元素,而是一些不可观察的对象).我还有在observableArray上展开的computed变量.如果我将元素放入数组,那么一切都会正常(我的意思是-重新计算了计算变量).

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).

但是,如果我更改了observableArray单个项目的某些属性,则不会重新计算计算值:

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?

推荐答案

您可以在修改myObsArr元素之一后在其上调用valueHasMutated方法.它将触发敲除依赖项跟踪,并且您的computedArr会收到有关更改的通知:

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();

但是,每次更改数组中的项时,您都必须记住要调用此函数,因此最好将Month转换为ko.observable,因为在这种情况下,ko更改跟踪将自动选择更改,并且会通知您计算出的内容,而无需任何其他代码.

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.

这篇关于更改observableArray元素的属性时,将计算要重新计算的触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆