0
votes

I'm in the process of trying out a javscript framework for a new web site and I started with knockoutjs this very day. Right now I'm stuck as data isn't rendered. Hope anyone can point me in the right direction. I'm using knockoutjs 2.2.1 and knockout mapping 2.4.0.

My viewmodel looks like this:

var UserModel = function () {
    var self = this;
    self.user = ko.observable();

    // Load user.
    self.load = function() {
        self.loadUser();     
    };

    self.loadUser = function() {
        // Load the main user object
        $.getJSON('/api/v1/users/17368',
            function(data) {
                var loadedUser = {};
                console.dir(data);
                ko.mapping.fromJS(data, {}, loadedUser);
                self.user(loadedUser);
            }
        );
    };

}

$(document).ready(function () {
    var userModel = new UserModel();
    ko.applyBindings(userModel);
    userModel.load();
})

I can see that the data is loaded in the ajax request. UPDATE: I've tried different mappings without success so far:

ko.mapping.fromJS(data, {}, loadedUser);

ko.mapping.fromJS(data, loadedUser);

In loadUser above the data output to the console looks like this:

Array[1]
  0: Object
    id: "17368"
    email: "john@domain.net"
    firstname: "John"
    lastname: "Morris"
    phone1: "000-1234567"

However nothing is rendered in this data bound snippet. It chokes on missing lastname or firstname:

<table>
     <thead>
        <tr>
            <th>lastname</th>
            <th>firstname</th>
        </tr>
    </thead>    
    <tbody data-bind="foreach: user">
        <tr>
            <td><span data-bind="text: lastname"></span></td>
            <td><span data-bind="text: firstname"></span></td>
        </tr>                
    </tbody>
 </table>
1
self.user user shouldn't it be a ko.observableArray() if you want to have multiple users??nemesv

1 Answers

2
votes

You shouldn't use foreach binding for user, because user is not observable array. Use with binding instead:

<tbody data-bind="with: user">
    <tr>
        <td><span data-bind="text: lastname"></span></td>
        <td><span data-bind="text: firstname"></span></td>
    </tr>                
</tbody>