Mark Hollas
Mark Hollas

Reputation: 1137

knockout.js with binding

This is probably a really basic question but in the following view model I am populating self.userData from an ajax call. I want to display this information in the UI and I figured the 'with' binding is the way to go.. however since self.userData is empty until the ajax function is called I get an error from the with binding

HTML

<div data-bind="with: userData">
    <div data-bind="text: userId"></div>
     ...
</div>

Model

var viewModel = function () {
        var self = this;
        self.userData = {};
        self.login =  function(data) {
            var postData = { ..trimmed out.. };
            $.ajax({
                type: "POST",
                url: "myService",
                data: postData
            }).done(function (data, status) {
                self.userData = ko.mapping.fromJS(data, userData);
                console.log(self.userData);

            }).fail(function (data, status) {
                alert('Could Not Login');
            });
        }

    };
    ko.applyBindings(new viewModel());

Upvotes: 0

Views: 337

Answers (2)

Neil Thompson
Neil Thompson

Reputation: 6425

You need to initialize userData as an empty observable (single object from ajax call) or observable array (multiple objects) first:

self.userData = ko.observableArray([]);

or

self.userData = ko.observable();

Upvotes: 1

Grim
Grim

Reputation: 1648

Initialize userData with an empty observable, an then set it with the object created by the the mapping plugin once the call return. I.e. change

self.userData = {};

with

self.userDara = ko.observable();

and change

self.userData = ko.mapping.fromJS(data, userData);

with

self.userData(ko.mapping.fromJS(data,userData));

Upvotes: 2

Related Questions