2014-07-18 82 views
3

我正在订购屏幕上,正常的主/细节方案。Knockout JS没有绑定

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

但是,当我想添加一个新行 - 敲除似乎完全忽略新增行。

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

<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

在你的淘汰赛模型currentRecord是可观察到的,所以你需要引用它像这样:

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

+0

为了记录在案,我总是进行这种监督。如果有疑问,请加上括号:) – DaveRead

+0

非常感谢戴夫。你结束了我的3天痛苦:) – Andrew

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/