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

查看:27
本文介绍了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天全站免登陆