Reputation: 1228
I have a table that is being created from a list. I have a button that adds to that list. This is real simple but cant seem to find out what I am missing. Here is my code:
<table>
<thead>
<th>Value</th>
<th>Remove</th>
</thead>
<tbody data-bind="foreach: names">
<tr>
<td>
<span data-bind="text: $data"></span>
</td>
<td>
<img id="Remove" width="20px" height="20px" src="/Content/Images/delete.png" data-bind="click: $parent.removeValue">
</td>
</tr>
</tbody>
</table>
<div>
<h2>
<span data-bind="text: addValueError"></span>
</h2>
<label for="addValue">Add Value</label>
<input id="addValue" type="text" data-bind="value: newValue" />
<img id="add" width="20px" height="20px" src="/Content/Images/add.png" data-bind="click: addNewValue">
</div>
<script type="text/javascript">
var model= new Model($('#someDiv')[0], data);
</script>
JavaScript:
function Model($id, data) {
var self = this;
self.names = ko.observablearray(['1','2','3']);
self.removeValue = function(){
//remove
}
self.addValueError = ko.observable();
self.newValue = ko.observable();
self.addNewValue = function(){
if (self.newValue () != null && self.newValue ().length > 0) {
self.Names().push(self.newValue ());
self.newValue ('');
self.addValueError ('');
} else {
self.addValueError ('Please provide a value to add.');
}
};
ko.applyBindings(self, $id);
}
When I add a value, it is added to the names list but it is not updated in the table. Any ideas?
Upvotes: 0
Views: 3330
Reputation: 1786
Fist off, I woudnt call apply bindings in your viewmodel constructor.
Pass your instance of model into it.
I would remove the != null for your truth check n the add function because you never have it set to null but from the looks it might be undefined or ''
Names
should be
names
Try calling push like this
self.names.push(self.newValue);
You need the observable to notify for the view to update so dont push directly to the underlying array.
Upvotes: 3