-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)"> 应该执行一个函数,但我得到的是:

错误:无法解析绑定。消息:ReferenceError:删除未定义;绑定值:点击:remove.bind($parent)

你知道发生了什么吗?我很确定我错过了一些非常小的东西,但我无法发现它。

4

2 回答 2

1

您处于 foreach 的上下文中,因此当您调用 remove 方法时,您试图在您正在遍历的数组中的元素上调用它。相反,您需要在 ViewModel 上调用它:

<img src="/projMonitoring/js/images/close.jpg" alt="Close" data-bind="click: $root.remove">
于 2013-08-07T13:45:03.557 回答
0

您需要有一个视图模型的实例。通过以下方式更改绑定:

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

有点近似于http://jsfiddle.net/gE3a7/的演示。

于 2013-08-07T13:44:43.813 回答