下面的简单示例对表单上的字段重新排序。每次您点击一行旁边的“顶部”按钮时,它都应该将其移动到列表的顶部。这些按钮似乎以一些奇怪的方式起作用,但为了争论,我将描述一种。从底部开始单击每个按钮。您会发现 console.log 表明 field.order 始终为 1,但当您到达最后两个时 UI 并不完全匹配;它们在文本框中保持为“10”和“20”,这是错误的,但它们的顺序仍然正确切换。
这是一个 ko 错误还是我错过了什么?
注意:您应该能够将代码直接复制并粘贴到 html 文件中并运行它。
<html>
<head>
<script src="http://knockoutjs.com/js/knockout-2.0.0.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function Field(name, order)
{
this.name = name;
this.order = order;
}
function Form() {
this.name = ko.observable("Test");
this.fields = ko.observableArray();
this.fields.push(new Field("field a", 10));
this.fields.push(new Field("field b", 20));
this.fields.push(new Field("field c", 30));
this.fields.push(new Field("field d", 40));
this.fields.push(new Field("field e", 50));
this.fields.push(new Field("field f", 60));
}
function AppViewModel() {
var self = this;
self.selectedForm = ko.observable(new Form());
reorderItems = function () {
self.selectedForm().fields.sort(
function (left, right) {
return (left.order == right.order)
? 0 : ((left.order < right.order) ? -1 : 1)
});
}
fieldMove = function (field) {
// find field in parent
var fldIdx = self.selectedForm().fields().indexOf(field);
field.order = 1;
console.log(field.order);
field.name = field.name + field.order;
// re-order the items
reorderItems();
}
}
$(document).ready(function () {
// Activates knockout.js
ko.applyBindings(new AppViewModel());
});
</script>
</head>
<body>
<div class="form" data-bind="with: selectedForm">
<!-- ko foreach: fields -->
<div class="field">
<span data-bind="html: name"></span>
<input data-bind="value: order"></input>
<button data-bind="click: fieldMove">Top</button>
</div>
<!-- /ko -->
</div>
</body>