我想创建一个淘汰赛设置,允许用户选择一个列表的子集到另一个列表中。我使用jquery UI selectable选择第一个列表中的项目。选择运行时,我将所选项目中的数据推送到第二个可观察数组中。我有一个绑定到第二个数组的标签,但是当我执行推送时它似乎没有更新。
这是我的代码
<html>
<head>
<title>Sample</title>
<link rel="stylesheet" href="jquery-ui-1.10.3.custom/css/ui-lightness/jquery-ui-1.10.3.custom.min.css"></link>
<style>
.ui-selected
{
border: 1px dotted red;
}
</style>
<script type="text/javascript" src="knockout-2.3.0rc.js"></script>
<script type="text/javascript" src="jquery-1.10.2.js"></script>
<script type="text/javascript" src="jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js"></script>
<script type="text/javascript">
function init()
{
function AppViewModel()
{
this.cars = ko.observableArray(
[
{year: 2004, make: "Chevy", model: "Malibu"},
{year: 1995, make: "Honda", model: "Civic"},
{year: 2004, make: "Chevy", model: "Malibu"},
{year: 1985, make: "Honda", model: "Civic"},
{year: 1984, make: "Chevy", model: "Malibu"},
{year: 1960, make: "Ford", model: "Ram"}
]);
this.selectedCars = ko.observableArray();
this.test=ko.observable("Bob");
}
ko.applyBindings(new AppViewModel());
$("#cars tbody").selectable(
{
filter: "tr",
selected: function( event, ui )
{
var selectedCarRow = ui.selected;
var bindingContext = ko.contextFor(selectedCarRow);
var observableCarData = ko.dataFor(selectedCarRow);
bindingContext.$parent.selectedCars().push(observableCarData.make);
//alert(bindingContext.$parent.selectedCars().length);
//alert(bindingContext.$parent.test());
}
});
}
</script>
</head>
<body onload="init()">
<table id="cars">
<thead><tr><th>Year</th><th>Make</th><th>Model</th></tr></thead>
<tbody data-bind="foreach: cars">
<tr>
<td data-bind="text:year"></td>
<td data-bind="text:make"></td>
<td data-bind="text:model"></td>
</tr>
</tbody>
</table>
<ul data-bind="foreach:selectedCars">
<li data-bind="text:$data"></li>
</ul>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
</body>
</html>
答案 0 :(得分:2)
在大多数情况下,您的代码是正确的。但是有一个小问题。在您编写selected
的可选bindingContext.$parent.selectedCars().push
函数中,这会将对象推入标准数组而不是可观察数组。要进入可观察数组,这些更改将触发敲除事件,您可以将()
放在数组对象上。
bindingContext.$parent.selectedCars.push(observableCarData.make);