簡體   English   中英

基因敲除.js:If和foreach綁定,檢查可觀察數組上的真值

[英]knockout.js: the If and foreach bindings, checking for truth value on observable array

我很難理解使用if和每個綁定的一些細節。 我希望有人能指出一些對我來說顯而易見的東西。

我有一個空數組,使用Boolean(observableArray().length)我得到了假。 沒問題 但是我無法在if綁定中使用這種表達式。

如果我從一個空數組開始並將數據推入其中,則不會顯示html元素。 如果我從填充數組開始,則該元素會出現,但在刪除數據時會被刪除,然后在重新添加數據時不會重新出現(?)。

這是一個擺弄這個問題的小提琴: https : //jsfiddle.net/Robinrich/rmn7afpm/25/

這是代碼:

function dataForTest(data) {
  var that = this;
  that.data = data;
}

function testViewModel() {
  var that = this;

  //Truth testing array.
  that.truthTest = ko.observableArray([new dataForTest("data")]);
  that.truFal = ko.observable(Boolean(that.truthTest().length));

  //Data to push and remove.
  var data = new dataForTest("data");

  that.pushData = function() {
    that.truthTest().push(data);
    that.truFal(Boolean(that.truthTest().length));
  }

  that.removeData = function() {
    that.truthTest([]);
    that.truFal(Boolean(that.truthTest().length));
  }
}

ko.applyBindings(new testViewModel());

這是HTML:

<h1> Testing array.length truthiness.</h1>
<button data-bind="click: pushData">Push Data</button>
<button data-bind="click: removeData">Remove Data</button>
<div data-bind="if: truthTest().length">
  <p>Data exists.</p>
  <ul data-bind="foreach: truthTest">
    <li><span data-bind="text: data"></span></li>
  </ul>
</div>
<p> There is data: <span data-bind="text: truFal()"></span>
</p>

我從1個數據實例開始。 數據出現。 這就是我所期望的表達式, if: truthTest().length計算為true,則該元素呈現。 那么,為什么在評估為false后不重新渲染呢? 我是否清空並不正確地添加到陣列? 我認為這是問題所在,因為如果我從填充數組開始並繼續推送數據,則<ul>不會更新,但是Boolean(truthTest().length)的真值是。 任何意見,將不勝感激。

您需要更改that.truthTest().push(data); that.truthTest.push(data);

檢查小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM