从json填充可观察数组

时间:2013-05-21 08:04:08

标签: javascript json knockout.js

我有一个工作测试示例,说明我想在这里做什么:http://jsfiddle.net/2BxVk/6/

而不是测试月份,我现在用(像这样)填充名为allMonths的可观察数组

self.tak = ko.observable(100);
self.styckpris = ko.observable(10);
self.grundpris = ko.observable(500);

self.allMonths = ko.observableArray([
new monthData(2013, 1, 412, 142, self),
new monthData(2013, 2, 112, 642, self),              
new monthData(2013, 2, 100, 742, self),
new monthData(2013, 3, 6513, 69, self),
new monthData(2013, 4, 34, 211, self),
new monthData(2013, 5, 123, 435, self),
new monthData(2013, 6, 412, 142, self),
new monthData(2013, 7, 412, 142, self)
]);

我想做一个$ .getJSON并将其插入到我的obs数组中。

如果直接从url:

查看,这是$ .getJSON源的输出
[{"tak":2700,"styckpris":35,"grundpris":20000,"year":2012,"month":2,"ss":784,"ms":576,"count":1360,"price":20000},{"tak":2700,"styckpris":35,"grundpris":20000,"year":2012,"month":3,"ss":977,"ms":636,"count":1613,"price":20000},{"tak":2700,"styckpris":35,"grundpris":20000,"year":2012,"month":4,"ss":1040,"ms":726,"count":1766,"price":20000},{"tak":2700,"styckpris":35,"grundpris":20000,"year":2012,"month":5,"ss":1373,"ms":1013,"count":2386,"price":20000},{"tak":2700,"styckpris":35,"grundpris":20000,"year":2012,"month":6,"ss":856,"ms":612,"count":1468,"price":20000},{"tak":2700,"styckpris":35,"grundpris":20000,"year":2012,"month":7,"ss":594,"ms":299,"count":893,"price":20000},{"tak":2700,"styckpris":35,"grundpris":20000,"year":2012,"month":8,"ss":1261,"ms":826,"count":2087,"price":20000},{"tak":2700,"styckpris":35,"grundpris":20000,"year":2012,"month":9,"ss":1092,"ms":729,"count":1821,"price":20000},{"tak":2700,"styckpris":35,"grundpris":20000,"year":2012,"month":10,"ss":1097,"ms":747,"count":1844,"price":20000},{"tak":2700,"styckpris":35,"grundpris":20000,"year":2012,"month":11,"ss":872,"ms":706,"count":1578,"price":20000},{"tak":2700,"styckpris":35,"grundpris":20000,"year":2012,"month":12,"ss":329,"ms":110,"count":439,"price":20000},{"tak":2700,"styckpris":35,"grundpris":20000,"year":2013,"month":2,"ss":911,"ms":0,"count":911,"price":20000},{"tak":2700,"styckpris":35,"grundpris":20000,"year":2013,"month":3,"ss":1002,"ms":0,"count":1002,"price":20000},{"tak":2700,"styckpris":35,"grundpris":20000,"year":2013,"month":4,"ss":1157,"ms":0,"count":1157,"price":20000},{"tak":2700,"styckpris":35,"grundpris":20000,"year":2013,"month":5,"ss":852,"ms":421,"count":1273,"price":20000}]

我一直在尝试遍历我从getJSON获取的数组并将它们放在allMonths中,但我无法弄清楚正确的语法。我对tak,styckpris或grundpris,3个第一属性,我想要年,月,ss& MS

我想要像:

var allMonths = ko.observableArray();
$.getJSON('Simulera/monthData', function (data) {
            $.each(data, function (i, val) {
                allMonths.push( new monthData(val.year, val.month, val.ss, val.ms, self) );
            });
        });

但这不起作用。我如何查看json返回的信息并将它们作为monthData对象类型插入到我的可观察数组中?

1 个答案:

答案 0 :(得分:3)

尝试添加self

$.each(data, function (i, val) {
    self.allMonths.push( new monthData(val.year, val.month, val.ss, val.ms, self) );
});

你的小提琴的工作版here