2012-12-12 49 views
0

我是KnockoutJs的新手,我試圖在.ascx中將它與ASP.net webforms一起使用。KnockoutJs - 在ViewModel中從視圖中獲取更新值

JsFiddle

<table border="1" cellpadding="0" cellspacing="0"> 
<tr> 
    <td> 
     <input type="button" data-bind="click: addNewRow" style="-moz-border-bottom-colors: blue" value="Add More Lines" /> 
     <input type="button" data-bind="click: addToCart" style="-moz-border-bottom-colors: blue" value="Add Items to Cart" /> 
    </td> 
</tr> 
<tr> 
    <th>Product Number</th> 
    <th>Description</th> 
    <th>Quantity</th> 
</tr> 
<tbody data-bind="foreach: quickEntries"> 
    <tr> 
     <td> 
      <input data-bind="text: $data.ItemPartNumb(), onkeyup: showValue" class="ItemPartNum" height="100" width="500" /> 
     </td> 
     <td> 
      <input data-bind="text: $data.ItemDescription()" class="ItemDescr" height="100" width="500" /> 
     </td> 
     <td> 
      <input data-bind="text: $data.ItemQuanties()" class="ItemQuan" height="100" width="500" /> 
     </td> 
    </tr> 
</tbody> 

視圖模型

<script type="text/javascript"> 

var QuickEntry = function (_itemPartNumb, _itemDescription, _itemQuanities) { 
    this.ItemPartNumb = ko.observable(_itemPartNumb); 
    this.ItemDescription = ko.observable(_itemDescription); 
    this.ItemQuanties = ko.observable(_itemQuanities); 
}; 

function QuickEntriesViewModel() { 

    var self = this; 
    self.quickEntries = ko.observableArray([]); 

    for (var i = 0; i < 10; i++) { 
     self.quickEntries.push(new QuickEntry('Bob','Jack','Steve'));    
    } 

    self.addNewRow = function() { 
     self.quickEntries.push(new QuickEntry()); 
    }; 

    self.showValue = function(quickEntry) { 
     alert(quickEntry.ItemPartNumb); //Nothing show 
    }; 

    self.addToCart = function() { 
     //Error here. How do i access the obserablearray? 
     alert(self.quickEntries.length); 
    }; 

}; 

//This is where you bind the ViewModel 
ko.applyBindings(new QuickEntriesViewModel()); 

的網頁將開始了用10個空的QuickEntry和用戶可以添加更多的線。它爲我創建了一個有10個空行的表格。用戶在表格中輸入一些信息,如項目部件號,說明等等。我會採取這些信息,並呼籲web api POST方法。當我嘗試獲取quickEntries觀察數組時。我什麼都沒有/未定義,當我嘗試onkeyup時。沒有彈出窗口可以讓我看到新的價值。

是不是元素綁定到一個observable會自動更新它的值?一旦其值被更改,如何獲得ViewModel中的可觀察數組值?

感謝

+0

能否請你把你的代碼中的jsfiddle底層數組? (http://jsfiddle.net)[它只是讓你更容易看到你想做什麼。]另外,你的'self.addNewRow'方法只是在你的可觀察數組中添加一個空的'QuickEntry'。這可能是你的問題的根源。 –

+0

我已添加JSFiddle。我想要做的是從10個空的QuickEntry表開始,這樣用戶可以在表中鍵入,然後他們是否需要更多的項目。他們可以點擊addNewRow到表格中。謝謝。 – Jack

+0

這裏是一個工作小提琴:http://jsfiddle.net/s7wJ9/3/ – gbs

回答

0
self.quickEntries() 

將返回所有的光輝數據

+0

你是對的。昨天我發現了。你必須將其視爲功能。 – Jack