2014-06-24 45 views
-1

這是我第一次在knockoutjs上刺傷。代碼如下。 getJSON調用正在工作。我可以在Fiddler中看到響應,並且已經使用JSLint進行了驗證(即JSON響應)。我可以看到該陣列正在Chrome控制檯中進行填充,但出於某種原因,用戶界面未使用從服務器獲取的數據進行更新。任何人都可以看到我錯過了什麼?KnockoutJS UI在第一次加載時沒有約束力

<script type="text/javascript"> 

function Section(data) { 

    this.ID = ko.observable(data.ID); 
    this.Name = ko.observable(data.Name); 
    this.Selected = ko.observable(data.Selected); 
} 

function SectionsViewModel() { 
    var self = this; 
    self.ViewName = ko.observable(); 
    self.Sections = ko.observableArray([]); 

    // Initial load 

    $.getJSON("/Service/view/[email protected]", 
         function (allData) { 
     self.ViewName = allData.ViewName; 
     var mappedSections = $.map(allData.Sections, 
               function (item) { 
                return new Section(item) }); 
     self.Sections = mappedSections; 
    }); 
} 

ko.applyBindings(new SectionsViewModel()); 

</script> 

<h2>Edit View</h2> 

<table class="dataEntryTable"> 
<thead> 
    <tr> 
     <th>ID</th> 
     <th>Name</th> 
     <th>Selected</th> 
    </tr> 
</thead> 
<tbody data-bind="foreach: Sections"> 
    <tr> 
     <td data-bind="text: ID()"></td> 
     <td data-bind="text: Name()"></td> 
     <td><input type="checkbox" data-bind="checked: Selected()" /></td> 
    </tr> 
</tbody> 
</table> 
+0

更新與'self.ViewName(newValue)'而不是'self.ViewName = newValue' –

+0

這已被標記爲不顯示任何研究,不明確或無助。研究工作包括瀏覽knockoutjs網站上的所有教程,並使用VS調試器,Chrome控制檯,JSLint和Fiddler檢查消息鏈的每個部分。這個問題非常清楚,對任何遵循相同路線的人都是最有幫助的。sheesh有些人需要什麼:p –

回答

0

更新KO與觀測功能:

self.ViewName(allData.ViewName); 
var mappedSections = $.map(allData.Sections, function (item) { 
               return new Section(item) }); 
self.Sections(mappedSections); 
在你的綁定

此外,刪除括號(你被綁定到可觀察到的,而不是觀察到本身的價值):

<td data-bind="text: ID"></td> 
<td data-bind="text: Name"></td> 
<td><input type="checkbox" data-bind="checked: Selected" /></td> 

最後,您需要撥打ko.applyBindings(new SectionsViewModel());你的html已經呈現將綁定加載的HTML到你的視圖模型(或者把腳本放在html之後,或者使用事件在文檔準備好時調用它)。

+0

沒有區別我很害怕:( –

+0

@SimonRigby還有一個問題,我更新了。這一次得到了它:) –

+0

仍然一樣..當我早些時候嘗試任何事情來讓它工作時,那些parens在那裏..已經刪除它們..同樣的事情。 V odd –