2

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>
2
  • I don't know if this matters, but you have commas at the end of lines 6-8 on the first snippet. Commented Oct 31, 2012 at 3:36
  • good catch, doesn't fix it though :/ Commented Oct 31, 2012 at 3:39

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the answer, but I still don't see what I am doing wrong. I add the html to the questions, maybe you can catch an error I am not seeing?
shit that might be the trick, can't test til this evening.. Makes sense though because a blank record was added to the list, so with the parens perhaps it will bring in the actual value.
Ah, I was so hopeful, but nope, still not working. Any idea what could be causing this?? I posted an update to my question with the edits you suggested.
@davidisawesome did you also get rid of the extra comma in the client object <s>and change the addClient function so that you are not pushing a json string to the self.clients array</s>?
@davidisawesome, I'd recommend you go through some tutorials... anyways here is a working version of the code you gave me, jsfiddle.net/2EX8R/2. On further review there are quite a few things wrong with the code you posted... One of the main things is that you are referencing variables in your template that are not in your client object.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.