我正在使用 knockoutjs,这是我的问题:我有一个具有子属性和子数组的对象。我想将发布者添加到我的产品中。我可以添加多个产品,效果很好。我什至可以添加发布者,如果我调试它,我可以看到对象具有新元素。但是,UI 不会更新以显示添加的新发布者。
这是HTML:
<h2>Your Products (<span data-bind="text: products().length"></span>)</h2>
<table>
<thead><tr>
<th>Product name</th><th>Price</th><th> Test Bind Name</th><th></th>
</tr></thead>
<tbody data-bind="foreach: products">
<tr>
<td><input data-bind="value: name" /></td>
<td><input data-bind="value: price" /></td>
<td><div data-bind="text: name"></div></td>
<td>
<a href="#" data-bind="click: $root.addPublisher">Add Publisher</a>
<a href="#" data-bind="click: $root.removeProduct">Remove</a>
</td>
</tr>
<!-- ko foreach: publishers -->
<tr>
<td><input data-bind="value: name" /></td>
<td><input data-bind="value: cost" /></td>
<td><div data-bind="text: name"></div></td>
</tr>
<!-- /ko -->
</tbody>
</table>
<button data-bind="click: addProduct, enable: products().length < 5">Add Product</button>
这是JavaScript
function Product(name, price) {
var self = this;
self.name = ko.observable(name);
self.price = price;
self.publishers = ko.observableArray([]);
}
function Publisher(name, cost) {
var self = this;
self.name = ko.observable(name);
self.cost = cost;
}
// Overall viewmodel for this screen, along with initial state
function ProductsViewModel() {
var self = this;
// Editable data
self.products = ko.observableArray([]);
// Operations
self.addProduct = function() {
self.products.push(new Product("", ""));
}
self.removeProduct = function(product) { self.products.remove(product) }
self.addPublisher = function(product) {
product.publishers().push(new Publisher("test",""));
}
}
ko.applyBindings(new ProductsViewModel());