与knockoutjs绑定的麻烦

时间:2013-07-20 13:47:18

标签: javascript knockout.js

我是knockoutjs的新手,我的绑定无效。没有显示任何内容。

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="content-type" content="text/xml; charset=utf-8" />
    <title></title>
    <script type='text/javascript' src='jquery-1.10.2.min.js'></script>
    <script type='text/javascript' src='knockout-2.3.0.js'></script>
    <script type='text/javascript' src='a.js'></script>
</head>
    <body>

    <table>
        <tbody data-bind="foreach: Timelines">
            <tr>
                <td data-bind="text: Name"></td>
            </tr>
        </tbody>
    </table>


    </body>
</html>

a.js:

    function Event(EventId, TimelineId, Date, Description) {
        var self = this;
        self.EventId = EventId;
        self.TimelineId = TimelineId;
        self.Date = Date;
        self.Description = Description;
    }

    function Timeline(TimelineId, Name, Color, PublicName) {
        var self = this;
        self.TimelineId = TimelineId;
        self.Name = ko.observable(Name);
        self.Color = ko.observable(Color);
        self.PublicName = ko.observable(PublicName);

        self.Events = ko.observableArray();
    }

    function TimelinesViewModel() {
        var self = this;
        self.Timelines = ko.observableArray([
            new Timeline(1, 'Elso', 'lightgreen', 'abc'),
            new Timeline(2, 'Masodik', 'pink', 'def')
        ]);
        self.StartDate = new Date();
        self.EndDate = new Date();
    }

    ko.applyBindings(new TimelinesViewModel());

我做错了什么?

1 个答案:

答案 0 :(得分:3)

因为您已在标头中包含a.js,所以在加载DOM之前会执行它。

但是在加载DOM之后需要调用ko.applyBindings(参见文档:Activating Knockout section)。

所以你有两个选择:

<script type='text/javascript' src='a.js'></script>移到body后的table内。

或者等待DOM加载的事件(例如使用jQuery):

$(function(){
    ko.applyBindings(new TimelinesViewModel());
});