knockout.jsjavascript-databinding

KnockoutJS binding to child array not being observed


I am working with knockoutjs and here is my problem: I have an object that has child properties and a child array. I want to add Publishers to my Products. I can add multiple products and it works great. I can even add publishers, and if I debug it, I can see the object has the new elements. However, the UI is not updating to display the new publisher that was added.

I have created a JSFiddle here

Here is the 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>

Here is the 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());

Solution

  • In your addPublisher method you don't need to use parenthesis on publishers to get the underlying array. Simply change the method to

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

    and everything should be working