Knockout.js mapping a JSON into an observable-array
Asked Answered
B

1

18

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/

Biophysics answered 6/6, 2012 at 20:21 Comment(0)
S
32

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.

Startle answered 6/6, 2012 at 21:10 Comment(1)
For everyone's reference, the middle empty object literal in this example is an empty placeholder for the mapping options object.Cellist

© 2022 - 2024 — McMap. All rights reserved.