2014-01-24 54 views
0

这是我第一次尝试一些knockout.js。有一个输入字段,你写入它的值被“发送”到一个列表并显示。然而,它不起作用,我想这与这个事实有关,这个.prodname没有关联到observableArray。但我不知道该怎么做。将输入字段的值添加到observableArray并显示它(knockout.js)

我的代码:

<!DOCTYPE html> 
<html> 
    <head> 
     <script type="text/javascript" src="jquery-1.10.2.min.js"></script> 
     <script type="text/javascript" src="knockout-3.0.0.js"></script> 
     <script type="text/javascript" src="app.js"></script> 
     <link rel="stylesheet" type="text/css" href="lt.css"/> 
     <title>eins</title> 
    </head> 
    <body> 
     <div id="main"> 
     <form data-bind="submit:addValues"> 
      <input type="text" data-bind="value:newprod, valueUpdate='afterkeydown'"></input> 
      <input type="text" data-bind="value:number,valueUpdate='afterkeydown'"></input> 
      <button type="submit">OK</button> 
     </form> 
      <ul data-bind="foreach:productname"> 
      <li data-bind="text : $index"></li> 
       <li data-bind="text:prodname"></li> 
       <li data-bind="text:anzahl"></li> 
      </ul> 
     </div> 
    </body> 
</html> 

而且app.js

$(document).ready(function() { 

    var mymodel = function() { 

     this.newprod = ko.observable(""); 
     this.productname = ko.observableArray(""): 

     this.addValues = function() { 
      this.productname.push(this.newprod()); 
     }; 

    }; 
    ko.applyBindings(new mymodel()); 
}); 

我想这一点,太:

this.productname.push({newprod: this.newprod() }); 

阅读这篇文章后:https://stackoverflow.com/questions/19419438/adding-an-item-to-an-observablearray-in-knockoutjs-when-using-mapping

据像我一样可以告诉,我的代码类似于这个示例: http://knockoutjs.com/examples/betterList.html

但是,我不希望observableArray被预填充。我想要的值来自输入字段。

谢谢你的帮助!

回答

2

你可以这样(see fiddle

您的代码没有在data-bind="foreach:productname"列表,你有,你试图替代属性绑定到视图模型(一个实例)的属性,因为工作的/您想要迭代的数组的可观测量。还有一些其他的东西,比如data-bind="text:prodname",但没有prodname被定义在你的视图模型中的任何地方。我为你清理了一些,希望你可以修改这些代码来满足你的需求。

var mymodel = function() { 
    var self = this; 
    self.newprod = ko.observable(); 
    self.anzahl = ko.observable(); 
    self.productname = ko.observableArray(); 

    self.addValues = function() { 
     self.productname.push(new product(self.newprod(), self.anzahl())); 

     // clear the input boxes for the next entry 
     self.newprod(''); 
     self.anzahl(''); 
    }; 
}; 

function product(name, anz){ 
    var self = this; 
    self.newproduct = ko.observable(name); 
    self.anzahl = ko.observable(anz); 
} 

ko.applyBindings(new mymodel()); 

和HTML

<div id="main"> 
    <form data-bind="submit:addValues"> 
     <input type="text" data-bind="value:newprod"></input> 
     <input type="text" data-bind="value:anzahl"></input> 
     <button type="submit">OK</button> 
    </form> 
    <ul data-bind="foreach:productname"> 
     <li data-bind="text: $index() + 1"></li> 
     <li data-bind="text: newproduct"></li> 
     <li data-bind="text: anzahl"></li> 
    </ul> 
</div> 
+0

啊,好吧,我需要通过一个新的对象在推法......现在我看到它。非常感谢!! – user2791739

相关问题