敲除js绑定的麻烦 [英] Troubles with knockoutjs binding
本文介绍了敲除js绑定的麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是敲门JS的新手,并且绑定不起作用.什么都没有显示.
I'm new to knockoutjs, and my bindings are not working. Nothing is displayed.
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());
我在做什么错了?
推荐答案
因为您已将a.js
包含在标头中,因此在加载DOM之前便已执行该标头.
Because you have included the a.js
in the header it gets executed before the DOM is loaded.
但是ko.applyBindings
需要在加载DOM之后被调用(请参阅文档:激活Knockout部分).
But the ko.applyBindings
needs to be called after the DOM was loaded (see documentation: Activating Knockout section).
因此,您有两个选择:
在table
之后将<script type='text/javascript' src='a.js'></script>
移到body
内.
或者等待DOM加载事件(例如,使用 jQuery ):>
Or wait for the DOM loaded event (for example with using jQuery):
$(function(){
ko.applyBindings(new TimelinesViewModel());
});
这篇关于敲除js绑定的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文