0
下面的簡單示例重新排列表單上的字段。每次你點擊一行旁邊的「頂部」按鈕,它都會將它移動到列表頂部。這些按鈕似乎以幾種奇怪的方式發揮作用,但爲了爭辯起見,我會描述一個按鈕。從底部開始點擊每個按鈕。你會發現console.log表明field.order總是一個,但是到達最後兩個時,UI並不匹配;它們在文本框中保持爲「10」和「20」,但它們的順序仍然正確切換。knockout.js綁定更新問題
這是一個錯誤還是我錯過了什麼?
注意:您應該能夠將代碼直接複製並粘貼到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>
啊,我錯過了,我沒有讓他們觀察到的(http://knockoutjs.com/documentation/observableArrays.html)。我現在更加困惑,爲什麼它的工作。技術上來說,在小提琴的html部分的屬性綁定應該是: – 2012-04-20 19:38:44
其實在這個例子中你不需要括號。如果您使用某些邏輯(如'order()> 3'),則只需使用括號 – 2012-04-20 23:00:51