【发布时间】:2013-02-24 08:52:33
【问题描述】:
我对淘汰计算的 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 对象,并且 此代码首先打开可观察对象,然后创建其 Clean Js 对象,而不是通过 Stringify它将创建 JSON。现在我认为在展开可观察对象期间,我计算的可观察对象的年龄可观察对象依赖性增加,现在它正在评估用户何时更改年龄属性。
如果我的解释是正确的,我该如何避免呢?
【问题讨论】:
-
年龄必须是可观察的吗?您似乎不想观察该数据的变化。
标签: javascript jquery knockout.js