【问题标题】:KnockoutJS binding to child array not being observed未观察到 KnockoutJS 绑定到子数组
【发布时间】:2015-02-15 15:59:15
【问题描述】:

我正在使用 knockoutjs,这是我的问题: 我有一个具有子属性和子数组的对象。 我想将发布者添加到我的产品中。 我可以添加多个产品,效果很好。 我什至可以添加发布者,如果我调试它,我可以看到对象具有新元素。但是,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());

【问题讨论】:

    标签: knockout.js javascript-databinding


    【解决方案1】:

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

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

    一切都应该正常

    【讨论】:

    • 我太接近了!感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2014-10-01
    • 2017-11-25
    • 2012-11-02
    • 1970-01-01
    • 2013-05-23
    • 2017-07-26
    • 2013-10-26
    • 2011-06-13
    相关资源
    最近更新 更多