KnockoutJS UI在第一次加载时没有绑定

时间:2014-06-24 09:03:36

标签: jquery knockout.js

这是我对knockoutjs的第一次尝试。代码如下。 getJSON调用正在运行。我可以在Fiddler中看到响应,并且我已经使用JSLint进行了验证(即JSON响应)。我可以看到数组正在Chrome控制台中填充,但由于某种原因,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/GetJSON?viewID=@ViewBag.ViewID", 
                      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>

1 个答案:

答案 0 :(得分:1)

使用observables函数更新ko:

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

同样在你的绑定中,删除括号(你绑定到observable的值而不是observable本身):

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

最后,您需要在 之后调用{/ 1>} 将您的html渲染为将加载的html绑定到您的视图模型(将脚本放在html之后) ,或使用事件在准备好文件时调用它。)