jaffa
jaffa

Reputation: 27360

How do I append a new row in a list by adding to the item of the previous row in KnockoutJs

If I had a template in KnockoutJs which is a 'foreach' template, when I 'push' the next bit of data onto the observable array shown in a grid, how do I ensure the value of the column is the previous row + 1.

e.g. (simplified)

        Col1
Row 1   5     [ Add Button ]
Row 2   6   <-- auto populated (+1)

Model (simplified):

viewModel = {
   ...
   addRow: function() {                                                         
                this.Rows.push ({ Col1:0 }) 
  }
}

I somehow need to access the previous row and push that data + 1, but when I inspect viewModel.Rows, there is no count or indexer. How do I access this data?

Upvotes: 1

Views: 368

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

You should be able to do this by binding your add button to an anonymous function that passes the current Col1 value.

Would be something like this:

<script id="itemsTmpl" type="text/html">
    <tr>
        <td data-bind="text: id"></td>
        <td>
            <button data-bind="click: function() { viewModel.addItem(id); }">Add Item</button>
        </td>
    </tr>
</script>

With addItem function like this:

var viewModel = {
    items: ko.observableArray([{id: 1}]),
    addItem: function(previousId) {
        this.items.push({
            id: previousId + 1
        });
    }
};

Sample here: http://jsfiddle.net/rniemeyer/6gETk/

This may not be exactly what you need for your app, but the technique should let you pass the necessary data to your bound function.

Upvotes: 1

Related Questions