simple
simple

Reputation: 2397

knockout.js using the mapping plugin

I am a newbie with knockout.js and want to start using the automatic mapping plugin. How can I convert this manually mapped code to use the mapping plugin?

http://jsfiddle.net/infatti/jWTtb/6/

// Here's my data model
var ViewModel = function (firstName, lastName) {
    var self = this;
    self.firstName = ko.observable(firstName);
    self.lastName = ko.observable(lastName);

    self.loadJson = function () {
        $.getJSON("http://echo.jsontest.com/firstName/Stuart/lastName/Little",
        function (data) {
            self.firstName(data.firstName);
            self.lastName(data.lastName);
        });
        return true;
    };

};
var vm = new ViewModel();
ko.applyBindings(vm); // This makes Knockout get to work

Upvotes: 0

Views: 54

Answers (1)

woz
woz

Reputation: 11004

Well, I am not very experienced with Knockout myself, but from the documentation it looks like all you should have to do is:

var viewModel = ko.mapping.fromJS(data);

In your case, it would look more like this:

var viewModel;
$.getJSON("http://echo.jsontest.com/firstName/Stuart/lastName/Little", function (data) {
    viewModel = ko.mapping.fromJS(data);
    ko.applyBindings(viewModel);
});

I tested it in jsFiddle.

Upvotes: 1

Related Questions