2014-06-24 47 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 –