2013-08-07 49 views
-2

我有下面的代碼在我的視圖模型:怪「沒有定義」的錯誤

CA = function (clientNum) { 
    this.CAName = null; 
    this.CAAdress = null; 
    this.CAIdNum = null; 
    this.CAContact = null; 
    this.CANote = null; 
    this.CAType = null; 
    this.clNum = clientNum; 
}, 
viewModelNewCredit = function() { 
    var 
    creditRows = ko.observableArray(), 
     showView = ko.observable(), 
     sessionTicket = ko.observable(), 
     loggedUser = ko.observable() 
     newCreditRows = function() { 
      console.log(this.clientNum()); 
      this.creditRows.push(new CA(this.clientNum())); 
      console.log(creditRows()); 
     }, 

     remove = function (ca) { 
      this.creditRows.remove(ca); 
     }; 
    return { 
     creditRows: creditRows, 
     showView: showView, 
     sessionTicket: sessionTicket, 
     loggedUser: loggedUser, 
     viewModelNewCredit: viewModelNewCredit, 
     remove: remove 
    }; 
}, 

,在我的HTML我有:

<tbody data-bind="foreach: creditRows"> 
    <tr> 
     <td> 
      <select name="CAType" id="CAType" data-bind="value: CAType" style="width: 8em;"> 
       <option>1</option> 
       <option>2</option> 
       <option>3</option> 
       <option>4</option> 
      </select> 
     </td> 
     <td> 
      <input type="text" name="CAName" id="CAName" data-bind="value: CAName" style="width: 15em;"> 
     </td> 
     <td> 
      <input type="text" name="CAAdress" data-bind="value: CAAdress" style="width: 15em;"> 
     </td> 
     <td> 
      <input type="text" name="CAIdNum" data-bind="value: CAIdNum" style="width: 6em;"> 
     </td> 
     <td> 
      <input type="text" name="CAContact" data-bind="value: CAContact" style="width: 10em;"> 
     </td> 
     <td> 
      <input type="text" name="CANote" data-bind="value: CANote" style="width: 15em;"> 
     </td> 
     <td> 
      <img src="/projMonitoring/js/images/close.jpg" alt="Close" data-bind="click: remove.bind($parent)"> 
     </td> 
    </tr> 
</tbody> 
</table> 
<button type="button" id="newRow" class="button" data-bind="click: newCreditRows">Add new row</button> 
<button type="button" id="OpenModal" class="button" data-bind="click: openModal">Open Modal</button> 

這行代碼: <img src="/projMonitoring/js/images/close.jpg" alt="Close" data-bind="click: remove.bind($parent)"> 應該執行功能,但什麼我得到的是:

Error: Unable to parse bindings. Message: ReferenceError: remove is not defined; Bindings value: click: remove.bind($parent)

你有一個想法是怎麼回事?我很確定我錯過了一些非常小的東西,但我無法發現它。

+0

... – NDM

回答

1

您處於foreach的上下文中,所以當您調用remove方法時,您正試圖從您正在遍歷的數組中調用它。相反,你需要調用它的視圖模型:因爲它說...`沒有定義remove`

<img src="/projMonitoring/js/images/close.jpg" alt="Close" data-bind="click: $root.remove"> 
+0

確定,但我現在得到的是:'類型錯誤:this.creditRows是undefined' ( – Slim

+0

)記錄'this',看看它是什麼,我的猜測是窗口範圍。嘗試在你的開頭添加VM構造函數:'var self = this',然後使用'self'來封裝'this'而不是 – Tomer

+0

找到了解決方案!感謝您的幫助! – Slim

0

您需要有一個視圖模型的實例。更改您通過以下方式結合:

var x = new viewModelNewCredit(); 
ko.applyBindings(x); 

有點近似演示在http://jsfiddle.net/gE3a7/