Slicky
Slicky

Reputation: 97

ObservableArray binding won't update

Edit: JSFiddle with comments

I'm developing my first SPA using knockoutjs. My situation is:

I created a simple fiddle.js (see here). It shows my problem better than 1000 words. I left out pagination logic for simplicity, but the observable for my list needs to be a computed for various reasons.

ViewMode.

var ViewModel = function() {

    var self = this;
    self.selectedItem = ko.observable();

    self.items = ko.observableArray([
    {
        name: "Item A",
        price: "12.99"
    },
    {
        name: "Item B",
        price: "13.99"
    },
    {
        name: "Item C",
        price: "90.99"
    }]);

    self.paginated = ko.computed(function() {
        // This is where I do some pagination and filtering to the content
        // It's left out here for simplicity. The binding for the list needs
        // to be a computed though.
        return self.items();
    });

    self.selectItem = function(item) {
        self.selectedItem(item);
    };

    self.save = function(item) {
        // Sending data to web api...

        // After the saving, the displaying list does not update to reflect the changes
        // I have made. However, switching entries and checking the changed item shows
        // that my changes have been saved and are stored in the observable.
    }

};

ko.applyBindings(new ViewModel());

View

<!-- ko foreach: paginated -->
<a href="#" data-bind="text: name, click: $parent.selectItem"></a><br />
<!-- /ko -->
<br />
<br />
<div data-bind="visible: selectedItem">
    <!-- ko with: selectedItem -->
    <form>
        <input type="text" data-bind="value: name" />
        <input type="text" data-bind="value: price" />
        <br />
        <button type="button" data-bind="click: $parent.save">Save</button>
    </form>
    <!-- /ko -->
</div>

I hope you can help me out, I don't want to reload all the data from the server for the sake of performance and speed.

Upvotes: 0

Views: 39

Answers (1)

chris vietor
chris vietor

Reputation: 2060

you have to make the properties of the objects in your array observable properties in order to reflect the changes to the UI.

self.items = ko.observableArray([
{
    name: ko.observable("Item A"),
    price: ko.observable("12.99")
},
{
    name: ko.observable("Item B"),
    price: ko.observable("13.99")
},
{
    name: ko.observable("Item C"),
    price: ko.observable("90.99")
}]);

Upvotes: 2

Related Questions