2014-01-24 53 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

相關問題