没有观察到KnockoutJS绑定到子数组

时间:2015-02-15 15:59:16

标签: knockout.js javascript-databinding

我正在使用knockoutjs,这是我的问题: 我有一个具有子属性和子数组的对象。 我想将Publishers添加到我的产品中。 我可以添加多个产品,效果很好。 我甚至可以添加发布者,如果我调试它,我可以看到该对象具有新元素。但是,UI未更新以显示已添加的新发布者。

我创建了JSFiddle here

这是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());

1 个答案:

答案 0 :(得分:1)

addPublisher方法中,您不需要在publishers上使用括号来获取基础数组。只需将方法更改为

即可
self.addPublisher = function(product) { 
    product.publishers.push(new Publisher("test",""));
}

并且一切都应该正常工作