Knockout JS没有约束力

时间:2014-07-18 15:01:32

标签: knockout.js

我正在处理订单屏幕,正常主/细节方案。

我的所有模型都是从服务器中提取出来的,并使用Knockout Mapping插件进行映射。一切正常,包括当我从服务器获得几行时 - 它们都正确显示。

但是当我想添加一个新行时 - Knockout似乎完全忽略了新添加的行。

我在没有服务器端模型的情况下模拟了相同的情况:

<div id="container">My order
<table data-bind="with: currentRecord">
    <tbody data-bind="foreach: Lines">
        <tr>
            <td>
                <button type="button" data-bind="click: $root.newLine">New line</button>
            </td>
            <td data-bind="text: Id"></td>
        </tr>
    </tbody>
</table>

function LineModel(idValue) {
    var self = this;

    self.Id = ko.observable(idValue);
}

function OrderModel() {

    var self = this;

    self.currentRecord = ko.observable();

    self.currentRecord.Lines = ko.observableArray([]);

    self.newLine = function () {
        self.currentRecord.Lines.push(new LineModel(12));
    };

    self.newLine();
}

ko.applyBindings(new OrderModel());

JSFiddle是here

2 个答案:

答案 0 :(得分:2)

在你的Knockout模型中,currentRecord是一个可观察的,所以你需要像这样引用它:

self.currentRecord().Lines.push(new LineModel(12));

答案 1 :(得分:0)

你不知道何时使用括号itus。当我第一次进入ko时,我遭受了很多这种情况,但简单地说,你在下面的行上错过了一组括号。

self.currentRecord.Lines = ko.observableArray([]);  // and
self.newLine = function () {
    self.currentRecord.Lines.push(new LineModel(12));
};

应该是

 self.currentRecord().Lines = ko.observableArray([]); // and
 self.newLine = function () {
    self.currentRecord().Lines.push(new LineModel(12));
};

你还必须为self.currentRecord提供一个扩展对象

self.currentRecord = ko.observable({});

http://jsfiddle.net/84aug/13/