我似乎偶然发现了一个与KnockoutJS有趣的异常情况。
我有一个带有ko.obseravableArray的对象。
我可以通过编程方式,在应用绑定之前将项添加到数组中。当UI更新时,它看起来是正确的。然后,当我单击按钮将项目添加到数组时,它看起来好像什么也没发生。但是,当我从数组中删除项目时,UI会更新。
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);
标记:
<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>
我还举了一个例子。 http://jsfiddle.net/Q6J6a/7/
我觉得我错过了一些小事,但它并没有向我跳出来。
答案 0 :(得分:3)
你想这样做:
self.features.push(new ItemFeature(self.featuresList[0]));
而不是:
self.features().push(new ItemFeature(self.featuresList[0]));
所以,你想在observableArray而不是底层数组上调用push
,以便它通知订阅者。