2015-12-15 49 views
0

我在使用if和for每個綁定的小細節時遇到了麻煩。我希望有人能指出一些明顯的東西給我。knockout.js:If和foreach綁定,檢查可觀察數組的真值

我有一個空數組,使用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並且元素呈現。那麼爲什麼它在評估爲假之後不重新渲染呢?我是否清空並向陣列添加不當?我認爲這是問題所在,因爲如果我從一個填充數組開始並繼續推送數據,則<ul>不會更新,但Boolean(truthTest().length)的真值爲。任何意見,將不勝感激。

回答

1

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

檢查Fiddle

+0

當然它是如此簡單。哇靠。謝謝。 –