knockout.js绑定更新问题

时间:2012-04-20 13:47:27

标签: knockout.js

下面的简单示例重新排序表单上的字段。每当您点击一行旁边的“顶部”按钮时,它应该将其移动到列表顶部。按钮似乎以一些奇怪的方式起作用,但我会为了争论而描述一个。从底部开始单击每个按钮。你会发现console.log表明field.order总是一个,但是当你到达最后两个时,UI并不完全匹配;它们在文本框中保持为“10”和“20”,这是错误的,但它们的顺序仍然正确切换。

这是一个ko bug还是我错过了什么?

注意:您应该能够将代码直接复制并粘贴到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>

1 个答案:

答案 0 :(得分:2)

我不确定您遇到问题的确切原因,但我设法通过将nameorder的标准属性替换为可观察属性来实现此目的。

working fiddle演示了解决方案