Automatically add new row to table when editing last

I am trying to add a new row to the end of the table when the user starts typing in the last row. The model is as follows:

function tableRow(number, ownerViewModel) {  
    this.number = ko.observable(number);
    this.remove = function () { ownerViewModel.tableRows.destroy(this); }

    ko.dependentObservable(function () {
        var curval = this.number();
        var rows = ownerViewModel.tableRows();
        if (rows.length > 0) {
            if (curval != '' && this == rows[rows.length - 1]) {
                ownerViewModel.addNewRow();
            }
        }
    }, this);
}

function tableRowsViewModel() {
    var that = this;
    this.tableRows = ko.observableArray([]);
    this.addNewRow = function () {
        this.tableRows.push(new tableRow('', that));
    }
    this.addNewRow();
}

$(document).ready(function () {
    ko.applyBindings(new tableRowsViewModel());
});

And here is the html:

<table>
    <thead>
        <tr>
            <th>
                Number
            </th>
            <th>
            </th>
        </tr>
    </thead>
    <tbody data-bind="template:{name:'tableRow', foreach: tableRows}">
    </tbody>
    <tfoot>
        <tr>
            <td colspan="4">
                <button type="button" data-bind="click: addNewRow">
                    add row
                </button>
            </td>
        </tr>
    </tfoot>
</table>
<script id="tableRow" type="text/html">
    <tr>
        <td>
            <input type="text" style="width:40px;" data-bind="value: number, valueUpdate: 'keyup'" />
        </td>
        <td>
            <button type="button" data-bind="click: function(){ $data.remove(); }">
                delete
            </button>
        </td>
    </tr>
</script>

I also added alert()ko.dependentObservable to the tableRow function:

ko.dependentObservable(function () {
    alert('test');
    var curval = this.number();...

It seems that this function runs 5 times when the tableRows array contains 2 elements, 6 times when there are 3 elements in the array, etc.

Am I doing it right?

+5
source share
1 answer

, , , , tableRows. , , , . , .

dependObservable, . dependObservable, , , . : http://jsfiddle.net/rniemeyer/F5F8S/

, , KO, , , , : http://jsfiddle.net/rniemeyer/MzGDr/

+7

All Articles