I seem to have stumbled into an interesting anomoly with KnockoutJS.
I have an object with an ko.obseravableArray in it.
I can programmatically, before I apply bindings add items to the array. When the UI updates it looks correct. Then when I click on a button to add an item to the array it appears as if nothing has happened. However, when I remove an item from the array the UI then updates.
var Feature = function (desription, price)
{
var self = this;
var _description = desription;
self.description = ko.observable(_description);
var _price = price;
self.price = ko.observable(_price);
}
var ItemFeature = function(feature)
{
var self = this;
var _feature = feature;
self.feature = ko.observable(_feature);
}
var Item = function ()
{
var self = this;
self.featuresList = [
new Feature("Feature 1", 1.50),
new Feature("Feature 2", 2.00)
];
self.features = ko.observableArray();
self.addNewFeature = function () {
self.features().push(new ItemFeature(self.featuresList[0]));
}
self.removeFeature = function (sender) {
self.features.remove(sender);
}
}
var _viewModel = new Item();
_viewModel.addNewFeature();
ko.applyBindings(_viewModel);
And the markup:
<table>
<thead><tr>
<th>Feature</th>
<th>Cost</th>
</tr></thead>
<tbody data-bind="foreach: features">
<tr>
<td><select data-bind="options: $root.featuresList, value: feature, optionsText:'description'"></select></td>
<td data-bind="text: feature().description"></td>
<td data-bind="text: feature().price"></td>
<td><a href="#" data-bind="click: $root.removeFeature">Remove</a></td>
</tr>
</tbody>
</table>
<a href="#" data-bind="click: addNewFeature">Add a feature</a>
I have also put together an example of this.
http://jsfiddle.net/Q6J6a/7/
I feel like I’m missing something small, but it’s not jumping out at me.
You want to do:
rather than:
So, you want to call
pushon the observableArray and not the underlying array, so that it notifies subscribers.http://jsfiddle.net/rniemeyer/Q6J6a/8/