0

我对淘汰计算的 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。现在我认为在展开可观察对象期间,我计算的可观察对象的年龄可观察依赖项会增加,现在它正在评估用户何时更改年龄属性。

如果我的解释是正确的,我该如何避免这种情况?

4

1 回答 1

2

问题是“这个”变量。您正在访问计算中的主视图模型。引用被传递,当它发生变化时,计算值现在重新评估。

你最好的选择是做这样的事情。

创建一个包含您要传递的数据并将其传递给同步的局部变量。

这是您的小提琴中更新的 JSBin。我从计算中删除了它,并使用局部变量来访问它。

http://jsbin.com/eqejov/9/edit

function VM()
{
  var self = this;
  self.Name = ko.observable("Tom");
    self.Age = ko.observable(23);

var localValue = {
   Name: self.Name(),
   Age: self.Age()
};

    //I want this computed evaluate only 
    //when name will change. So i put Name observable 
    //inside it.
    ko.computed(function(){
       self.Name();
      //send only after dom is initiallized
       if(initialized){   
          Server.Sync(localVariable);
       }
    }).extend({ throttle: 500 });
  }
于 2013-03-08T21:15:28.373 回答