即使在我取消了具有计算属性的对象之后,如果相关的可观察性发生了变化,也会调用计算属性。
我希望,既然我已经使对象无效,它应该被垃圾收集,但看起来Knockout保持了对象的活力,也保持了不再相关的订阅。
淘汰中是否有方法可以做到这一点,即删除对无效对象的订阅,从而使其可用于垃圾收集。我试图查阅它的文件,但没有成功。
这里有一把小提琴来说明这个问题。。
http://jsfiddle.net/qy4sshv6/5/
var Line = function()
{
this.unit = ko.observable();
this.convertFactor = ko.observable();
}
var Measurement = function(line)
{
this.msrmntValue = ko.computed(function(){
var a = 20*line.convertFactor();
document.getElementById("output").innerHTML += "nValue set to " + a;
return a;
});
}
var line = new Line();
line.convertFactor(20);
var msrmnt1 = new Measurement(line);
var msrmnt2 = new Measurement(line);
// Display the value
function SetValue()
{
line.convertFactor(40);
};
function NullifyAndSetValue()
{
msrmnt1 = null;
msrmnt2 = null;
// After the ibjects have been nullified I want that the computed properties should not be recalculated
// and the objects should be garbage collected, but looks like the objects are left in memory indefinitely
// because knockout is still referenceing them.
line.convertFactor(80);
}
您需要使用ko.computed
的dispose
方法。
来自文件:
dispose()
——手动处理计算出的可观察项,清除对依赖项的所有订阅。如果您想停止更新计算的可观测项,或者想为依赖于无法清理的可观测值的计算可观测项清理内存,则此函数非常有用
所以你只需要写:
function NullifyAndSetValue()
{
msrmnt1.msrmntValue.dispose();
msrmnt1 = null;
msrmnt2.msrmntValue.dispose();
msrmnt2 = null;
line.convertFactor(80);
}
演示JSFiddle。