2016-03-03 112 views
1

好吧,我試過閱讀文檔;我試過改變我的設置;我嘗試了所有我能想象到的,但我無法讓我的foreach循環工作。淘汰賽foreach只是不工作

var Entry = function(item) { 
    this.id = item.id; 
    this.locations = item.locations; 
    this.read = ko.observableArray(item.read); 
    this.subentries = ko.observableArray(item.subentries); 
    this.creator = item.creator; 
    this.created = item.created; 
    this.entry = item.entry; 
} 

function managerLogModel() { 

    var self = this; 

    // declare the different components 


    // log entries 
    this.entries = ko.observableArray(); 

    this.loadData = function(data) { 
     for(i=0;i<data.length;++i) { 
      self.entries().push(new Entry(data[i])); 
     } 
    } 

...more functions that I don't believe are affecting, since I'm getting 
    the console to log the desired data: [Entry, Entry, Entry,...] 

} 

一切似乎在後端工作。在this.loadData之後,我做了一個console.log(self.entries()),我得到了一個Entry對象列表。

但是,在模板中,我無法獲得任何工作。我試過了:

<div data-bind:"foreach:$data">test</div> 
<div data-bind:"foreach:$data.entries">test</div> 
<div data-bind="foreach:$data">test</div> 
<div data-bind="foreach:$data.entries">test</div> 

有趣的是,這在我實施Entry模型之前完美地工作。我可以將JSON加載到self.entries(數據)中,模板將正確呈現數據(儘管我必須使用data-bind:not data-bind =)

任何人都可以指出我正確的方向嗎?

編輯:奇怪的語法如下所示;僅適用於數據綁定:的foreach:

<!-- ko foreach: paginated --> 

    <div class="entry" data-bind:"foreach:entries"> 

     <div class="entry-header"> 

.... 
+0

你試過''

test
?另外,當你推送時,沒有「條目」上的parens,或者Knockout不會注意到你已經改變了任何東西。 –

+1

好吧,我有它的工作。謝謝!它是無括號和data-bind =「foreach:entries」的組合。如果你想提交答案,我會很樂意接受它。 – Craig

回答

1

data-bind總是跟着=$data用於裏面 a foreach,所以你不想那樣。 如果您將push添加到observableArray的內容中,則Knockout不會注意到這些更改。您必須將push指向observableArray本身。

所以,你要

<div data-bind="foreach: entries">test</div> 

self.entries.push(new Entry(data[i])); 
+0

這是一件很好的事情:知道re:push到observableArray本身,但是這裏有一些有趣的東西:我使用了一個包含<! - foreach:entries - > paginator的片段,第一個數據綁定必須是數據綁定的,結合 「的foreach:條目」。它不適用於data-bind =「foreach:entries」 – Craig

+0

如果你使用的是虛擬元素,它就是'<! - ko foreach:entries - >',根本沒有'data-bind'。在HTML標記中,使用冒號應該是語法錯誤。我從來沒有嘗試在虛擬中使用'data-bind'而不是'ko'。 –

+0

看我上面的編輯看到的語法;它絕對沒有記錄在我見過的任何地方。 – Craig