与knockoutjs结合故障(Troubles with knockoutjs binding)

2019-10-18 09:24发布

我是新来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());

我究竟做错了什么?

Answer 1:

因为你已经包括了a.js在头加载DOM之前被执行。

ko.applyBindings需要DOM被加载后,被称为(见文档: 激活淘汰赛部分 )。

所以,你有两个选择:

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

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

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


文章来源: Troubles with knockoutjs binding