当源未定义时,这是KnockoutJS绑定的正确行为吗?

时间:2015-12-25 21:01:38

标签: knockout.js binding

我遇到了一个我需要从概念上理解的问题。我找不到文件或任何其他信息来源来解决我对此行为的不安:

预计会出现这种情况吗?当我有一个基于另一个observable设置为空对象的计算observable时,引用一个尚未存在的属性,在视图中没有任何东西被渲染/绑定,viewModel数据根本就不知道这个未定义属性的存在......它&# 39;常见的情况是你有一个observable初始化为一个空对象,以后将它设置为一个非空对象,你可能需要从中访问非空对象的属性。

与以下链接中讨论的内容形成鲜明对比(是吗?):

KnockoutJS binding when source is null/undefined

Simplifying and Cleaning Up Views in KnockoutJS

请查看以下代码段(和评论):

运行脚本并单击行为按钮!



var viewModel = function() {
  var self = this;
  //not empty object literal observable initialized
  self.object = ko.observable({p1: "Born ready"});
  self.objectP1 = ko.pureComputed(function() {
    return self.object().p1;
  });

  //empty object literal observable initialized
  self.objectEmptyOnInit = ko.observable({});
  
  //computed observable based on a (undefined) property, is simply discarded, not rendered in view, not present in viewModel $data
  self.objectP1EmptyOnInit = ko.pureComputed(function() {
    return self.objectEmptyOnInit().p1;
  });
  
  //same behavior as this computed observable, returning explicitly undefined
  self.objectP2EmptyOnInit = ko.pureComputed(function() {
    return undefined;
  });


  self.debugInfo = function(item) {
    return ko.toJSON(item);
  };


};

ko.applyBindings(new viewModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<span data-bind="text: objectP1"></span>
<br />
<span data-bind="text: objectP1EmptyOnInit"></span>
<br />
<button data-bind="click: function() { $root.objectEmptyOnInit({p1: 'Look Im born!'}) }">Give birth to objectEmptyOnInit</button>

<div style="border: white dotted thin; clear: both">
  <h4>Debug viewModel $data</h4>
  <pre data-bind="text: debugInfo($data)"></pre>
  <div data-bind="visible: objectEmptyOnInit()">
  <span>Not a clue about objectP1EmptyOnInit</span>
  </div>
  <div data-bind="visible: objectEmptyOnInit().p1">
  <span>Here comes objectP1EmptyOnInit</span>
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

这是一个淘汰赛的默认行为。计算的可观察量足够智能,以避免由源自空对象的未定义属性引起的错误。该片段证明了这一点。它只是有效。