开发者

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 }) 
  开发者_StackOverflow}
}

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜