Knockout.js mapping a JSON into an observable-array

Thomas Deutsch picture Thomas Deutsch · Jun 6, 2012 · Viewed 24k times · Source

I want to build a client for my REST-Service using Knockout.js. I have a lot of Repositorys i want to access through different urls - so i came up with this solution using the Revealing-Prototype-Pattern. My problem: I can not find out how to map the ItemsProperty with my "data" i receive from my service.

var Repository = function (url) {
    this.Url = url;
    this.Items = ko.observableArray([]);
    this.PendingItems = ko.observableArray([]);
};

Repository.prototype = function () {
    var  
        getAllItems = function () {
            var self = this;
            $.getJSON(self.Url, function (data) {
            // data=[{"Id":1,"Name":"Thomas","LastName":"Deutsch"},{"Id":2,"Name":"Julia","LastName":"Baumeistör"}]
                ko.mapping.fromJS(data, self.Items);
            });
        }, 
    ...


// i call it like this:
customerRepository = new Repository('http://localhost:9200/Customer');
customerRepository.getAllItems();

I think the problem is in this: ko.mapping.fromJS(data, self.Items); but i can not find the right way to do it.
Question: what am i doing wrong? i have found an example - and they are doing the same i think: http://jsfiddle.net/jearles/CGh9b/

Answer

madcapnmckay picture madcapnmckay · Jun 6, 2012

I believe that the two argument version of fromJS is only used for objects that were previously mapped, i.e they had an implicit empty mapping options object. Since your mapping is the first time it has been run, it needs to provider that empty options object like so.

ko.mapping.fromJS(data, {}, self.Items);

http://jsfiddle.net/madcapnmckay/j7Qxh/1/

Hope this helps.