I am sure this will be an easy answer for someone. I have the following ViewModel:
@{ var initialData = new JavaScriptSerializer().Serialize(Model); } var data = @Html.Raw(initialData); function ViewModel(data) { var self = this; self.Name = ko.observable(data.Name); self.Items = ko.observableArray(data.Items); self.addItem = function() { self.Items.push(""); }; self.removeItem = function(data) { self.Items.remove(data); } } $(document).ready(function() {ko.applyBindings(new ViewModel(data)); });
And the following view:
<div> Name: <span data-bind="text: Name"></span> </div> <div> Items: <button data-bind="click: addItem">Add Item</button> </div> <div> <table> <tbody data-bind="template: { name: 'itemTemplate', foreach: Items }"></tbody> </table> </div> <script type="text/html" id="itemTemplate"> <tr> <td> <input data-bind="value: $data" /> <a href="#" data-bind="click: function() {$parent.removeItem($data)}">Remove Item</a> </td> </tr> </script>
Everything works correctly except removeItem . When new lines are added and “Delete item” is clicked on an empty new line, all new lines will be deleted along with it. I looked at tons of knockout tutorials, trying to get this to work, and my method seems like a real attempt, but obviously ... I have to miss something. Any suggestions?
source share