【问题标题】:Issue with ko.toJSON and Computed observableko.toJSON 和 Computed observable 的问题
【发布时间】: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


【解决方案1】:

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

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

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

这是来自您的小提琴的更新 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 });
  }

【讨论】:

  • 顺便说一句,这不会给你最新的值。
猜你喜欢
  • 2018-05-26
  • 1970-01-01
  • 2012-07-15
  • 2017-06-04
  • 2020-05-14
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多