我对淘汰计算的 observable 和 toJSON 函数有疑问。我创建了一个Fiddle Example。在这个例子中,我有一个模型:
function VM()
{
this.Name = ko.observable("Tom");
this.Age = ko.observable(23);
//I want this computed evaluate only
//when name will change. So i put Name observable
//inside it.
ko.computed(function(){
this.Name();
//send only after dom is initiallized
if(initialized){
Server.Sync(this);
}
}, this).extend({ throttle: 500 });
}
function Server()
{
}
Server.Sync = function(data)
{
alert("send");
var jsonData = ko.toJSON(data); //This is the problamatic code which..
//increases the computed dependency. After executing this code the..
//computed function is now evaluates on Age also which i do not want.
//send jsonData
};
在这个模型中,我希望我的计算值仅在用户更改 Name 可观察属性时进行。在执行Server.Sync函数之前,它的工作正常。在Sync函数中,我通过toJSON函数从 ViewModel 对象创建 JSON 对象,并且此代码首先打开 observables,然后创建它的 Clean Js 对象,而不是通过 Stringify 它将创建 JSON。现在我认为在展开可观察对象期间,我计算的可观察对象的年龄可观察依赖项会增加,现在它正在评估用户何时更改年龄属性。
如果我的解释是正确的,我该如何避免这种情况?