我似乎偶然发现了 KnockoutJS 的一个有趣的异常现象。
我有一个带有 ko.observableArray 的对象。
我可以在应用绑定之前以编程方式将项目添加到数组中。当 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/
我觉得我错过了一些小东西,但它并没有向我跳出来。