Knockout.js mapping a JSON into an observable-array

安稳与你 提交于 2019-11-30 00:48:37

问题


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/


回答1:


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.



来源:https://stackoverflow.com/questions/10921654/knockout-js-mapping-a-json-into-an-observable-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!