Search code examples
javascriptajaxknockout.jsko.observablearray

knockout observable array not updating after ajax addition


I have an observable array of a complex object. The initial load is fine, and all the expected data looks fine. Now I am working on POSTing new items to that array. NOTE: The observable array is being loaded via ASP.NET ajax web api call.

posting a new item works fine as far as saving it to the database, but my DOM is not getting updated with the new item and I don't know what I am missing.

Here is the entire ViewModel

    function ClientList() {
    //data
    var self = this;
    self.initialized = ko.observable(false);
    self.clients = ko.observableArray();
    self.userId = ko.observable("");
    self.name = ko.observable("");
    self.logo = ko.observable("");
    self.projects = ko.observableArray();
    self.clientAddress = ko.observableArray();


    self.addClient = function () {
        var client = {
            UserId: self.userId,
            Name: self.name,
            Logo: self.logo,
        }
        client = ko.toJSON(client);
        lucidServer.addClient(client);
        self.clients.push(client);
    }.bind(self);

    (function () {
        $.ajax({
            url: lucidServer.getClients(1),
            success: function (data) {
                ko.mapping.fromJS(data, {}, self.clients);
                self.initialized(true);
            }
        });
    })();
};

function IncompleteStoriesList() {
    //data
    var self = this;
    self.initialized = ko.observable(false);
    self.stories = ko.observableArray();
    (function () {
        $.ajax({
            url: lucidServer.getIncompleteStory(1),
            success: function (data) {
                ko.mapping.fromJS(data, {}, self.stories);
                self.initialized(true);
            }
        });
    })();
};


function ViewModel() {
    var self = this;
    self.clientList = new ClientList();
    self.storyList = new IncompleteStoriesList();
}

ko.applyBindings(new ViewModel());

Here is the particular snippet where I am doing the POST (within the ClientList() function).

self.addClient = function () {
        self.client = {
        UserId: self.userId(),
        Name: self.name(),
        Logo: self.logo(),
        }
    //make client object to send to server
    var client = ko.toJSON(self.client);
    lucidServer.addClient(client);
    //push the self.client to the observablearray of clients
    self.clients.push(self.client);
}.bind(self);

I verified it is JSON that is sitting inside the client variable, and no error messages are getting thrown, so I am confused. After I add an item and refresh the entire page, it will show up in the list.

EDIT: here is the html associated:

<form data-bind="submit: clientList.addClient">
    <div>
        <label>userId</label>
        <input type="text" data-bind="value: clientList.userId" />
    </div>
    <div>
        <label>name</label>
        <input type="text" data-bind="value: clientList.name" />
    </div>
    <div>
        <label>logo</label>
        <input type="text" data-bind="value: clientList.logo" />
    </div>
    <button type="submit">Add</button>

    </form>

    <!-- ko ifnot: clientList.initialized -->
    <span>Loading...</span>
    <!-- /ko -->
    <ul data-bind="template:{name: 'clientList', foreach:clientList.clients}">
    </ul>

And the external template looks like this:

<div id="clientListOutput">

    <li><span data-bind="text: name"></span>
        <div data-bind="template: {foreach: clientAddress}">
            <span data-bind="text: city"></span>
            <span data-bind="text: state"></span>
        </div>
        <hr />
        <ul data-bind="template: {foreach: projects}">
            <li>
                <span data-bind="text: name"></span>
                <span data-bind="text: summary"></span>
                <span data-bind="text: description"></span>
            </li>
        </ul>
    </li>

Solution

  • I am quite certian you have a typo in your HTML. Here is a working example using ko.observablearray

    HTML:

    <form data-bind="submit: addItem">
        prop1: <input data-bind='value: prop1, valueUpdate: "afterkeydown"' />
        prop2: <input data-bind='value: prop2, valueUpdate: "afterkeydown"' />
        <button type="submit">Add</button>
        <p>Your items:</p>
        <div data-bind="foreach: items">
            <span data-bind="text: prop1"></span> &nbsp - &nbsp
            <span data-bind="text: prop2"></span>
            <br />
        </div>
    </form>
    

    JS:

    var SimpleListModel = function() {
        this.items = ko.observableArray();
        this.prop1 = ko.observable("");
        this.prop2 = ko.observable("");
        this.addItem = function() {
            this.items.push({prop1:this.prop1, prop2: this.prop2});
        }.bind(this);  // Ensure that "this" is always this view model
    };
    
    ko.applyBindings(new SimpleListModel());
    

    http://jsfiddle.net/NjSBg/2/

    I suppose it's also possible you forgot to apply the bindings...

    Edit

    I appologize for posting the wrong fiddle, right one up now.

    self.addClient = function () {
        var client = {
            UserId: self.userId(),
            Name: self.name(),
            Logo: self.logo()
        }
        lucidServer.addClient(ko.toJSON(client));
        self.clients.push(client);
    }.bind(self);
    

    You add the parenthesis to get the current static value of the observable