【问题标题】:Is this the correct behavior of KnockoutJS binding when source is undefined?当源未定义时,这是 KnockoutJS 绑定的正确行为吗?
【发布时间】:2016-03-31 16:49:11
【问题描述】:

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

这是预期的行为吗?当我有一个基于另一个可观察对象设置为空对象的计算可观察对象时,引用一个尚不存在的属性,视图中没有任何内容被渲染/绑定,viewModel 数据根本不知道这个未定义属性的存在......这是一个常见的情况是,您将 observable 初始化为空对象,稍后将其设置为非空对象,您可能需要从中访问非空对象的属性。

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

KnockoutJS binding when source is null/undefined

Simplifying and Cleaning Up Views in KnockoutJS

请查看以下 sn-p(和 cmets):

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

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>

【问题讨论】:

  • 这个问题很难理解。请更明确地说出您期望发生的事情以及每种情况下会发生什么。如果我运行 sn-p 一切都会按我的预期工作。那可能是因为我一直在使用 KO(一个 JS)。如果你更明确,我很乐意帮助你。

标签: knockout.js binding


【解决方案1】:

这是淘汰赛的默认行为。计算出的 observables 足够聪明,可以避免由源自空对象的未定义属性引起的错误。 sn-p 就是证明。它只是工作。

【讨论】:

    猜你喜欢
    • 2012-07-08
    • 2020-06-15
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    相关资源
    最近更新 更多