simple
simple

Reputation: 2397

Knockout.js updating form values with json data

I am a total newbie with knockout.js and need a very basic understanding of how to simply update my form fields with json data. I have a viewmodel. How do I pull the json data into the observable fields?

<p>Errors: <input data-bind="value: errors" /></p>
<p>Message: <input data-bind="value: message" /></p>

// Here's my data model
var ViewModel = function(myError, myMessage) {
    this.errors = ko.observable(myError);
    this.message = ko.observable(myMessage);
};

ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work

$.getJSON("http://api.twitter.com/1/statuses/public_timeline.json", function(data) {

})

Upvotes: 1

Views: 2306

Answers (1)

Joseph Gabriel
Joseph Gabriel

Reputation: 8510

I prefer to set the view model properties explicitly - I feel that is easier to control and maintain.

var ViewModel = function(myError, myMessage) {
    var self = this;
    self.errors = ko.observable(myError);
    self.message = ko.observable(myMessage);
    self.property1 = ko.observable();
    self.property2 = ko.observable();
};

var vm = new ViewModel("Planet", "Earth");
ko.applyBindings(vm); // This makes Knockout get to work
$.getJSON("http://api.twitter.com/1/statuses/public_timeline.json", function(data) {
    vm.property1(data.field1);
    vm.property2(data.field2);
    ...etc
})

If this seems too verbose, there is also the mapping plugin that you can use to automatically map values from JSON into your view model.

Read more about it here: http://knockoutjs.com/documentation/plugins-mapping.html

var vm = new ViewModel("Planet", "Earth");
ko.applyBindings(vm); // This makes Knockout get to work
$.getJSON("http://api.twitter.com/1/statuses/public_timeline.json", function(data) {
    var jsObject = ko.fromJSON(data);
    ko.mapping.fromJS(jsObject , viewModel);
})

Upvotes: 1

Related Questions