我在viewmodel中有以下代码:
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)">
应该执行一个函数,但我得到的是:
错误:无法解析绑定。消息:ReferenceError:未定义remove;绑定值:单击:remove.bind($ parent)
你知道发生了什么吗?我很确定我错过了一些非常小的东西,但我无法发现它。
答案 0 :(得分:1)
你在foreach的上下文中,所以当你调用remove方法时,你试图在你正在遍历的数组中的元素上调用它。相反,你需要在ViewModel上调用它:
<img src="/projMonitoring/js/images/close.jpg" alt="Close" data-bind="click: $root.remove">
答案 1 :(得分:0)
您需要拥有视图模型的实例。通过以下方式更改绑定:
var x = new viewModelNewCredit();
ko.applyBindings(x);
http://jsfiddle.net/gE3a7/处的某种近似演示。