Knockout.js将JSON映射到可观察数组 [英] Knockout.js mapping a JSON into an observable-array

查看:106
本文介绍了Knockout.js将JSON映射到可观察数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Knockout.js为我的REST服务构建客户端. 我有很多存储库,我想通过不同的URL访问-所以我想出了使用Revealing-Prototype-Pattern的解决方案. 我的问题:我不知道如何使用我从服务中收到的数据"来映射ItemsProperty.

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();

我认为问题出在此: ko.mapping.fromJS(data,self.Items); ,但是我找不到正确的方法.
问题:我在做什么错?我找到了一个示例-我也在做同样的事情: http://jsfiddle.net/jearles/CGh9b/

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/

推荐答案

我相信fromJS的两个参数版本仅用于先前映射的对象,即它们具有隐式的空映射选项对象.由于映射是第一次运行,因此需要像这样提供空选项对象.

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/

希望这会有所帮助.

这篇关于Knockout.js将JSON映射到可观察数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆