为什么Simple Knockout js在桌面上不起作用并且在Fiddle中工作

时间:2013-11-18 22:08:12

标签: knockout.js

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script src="jquery.js"/>
<script src="knockoutdebug.js"/>
<script type='text/javascript'>

// Class to represent a row in the seat reservations grid
function SeatReservation(papers) {
    var self = this;
    //self.name = name;
    self.papers = ko.observable(papers);
}

// Overall viewmodel for this screen, along with initial state
function ReservationsViewModel() {
    var self = this;

    // Non-editable catalog data - would come from the server
    self.availableMeals = [
        {   title: "Ethics in HCI", 
            authors: "Rolf" , 
            abstract:"Users ."
        },
        { title: "HCI", authors: "Lynnl"  },
        { title: "Eth", authors: "Rolson"  }
    ];    

    // Editable data
    self.seats = ko.observableArray([
        new SeatReservation( self.availableMeals[0]),
        new SeatReservation(self.availableMeals[1])
    ]);
}

ko.applyBindings(new ReservationsViewModel());
</script>
</head>
<body>
<p>
  <input type="search" id="skyquery" name="q" placeholder="scientific search" autofocus />
  <input type="submit" id="skysubmit" value="Ignite!" />
</p>
<table>
    <tbody data-bind="foreach: seats">
        <tr data-bind="text: papers().title"/>
        <tr data-bind="text: papers().authors"/>
        <tr data-bind="text: papers().abstract"/>
    </tbody>
    <tbody></tbody>
</table>

</body>
</html>

这是我使用Knockout示例代码创建的代码。但是,冷杉没有任何错误。什么都没发生。但是,当我尝试他们的小提琴时,它工作得很好。

2 个答案:

答案 0 :(得分:2)

可能是因为ko.applyBindings(new ReservationsViewModel());在DOM渲染之前正在执行。成功:

$(document).ready(function() {
    ko.applyBindings(new ReservationsViewModel());
});

答案 1 :(得分:1)

在创建DOM元素(具有ko.applyBindings属性)之后,需要调用

data-bind

要解决此问题,您可以将script标记移至页面底部或将其包装在$(document).ready()中。

也许它在jsfiddle工作的原因是因为它设置为运行JavaScript onDOMReady。