这就是它应该做的事情(至少在理论上/文档中),但显然这不是它正在做的事情。我有同样的问题,我也相信其他问题:https ://groups.google.com/forum/?fromgroups=#!topic/knockoutjs/uKY84iZaxcs
对象必须是:
{ "someName" : [ { x: 1, y: "test" } ] }
要坚持您的对象模式,您可以使用 ko.utils.arrayMap 将对象映射到您的 KO ViewModel:http ://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html
function Item(name, category, price) {
this.name = ko.observable(name);
this.category = ko.observable(category);
this.price = ko.observable(price);
this.priceWithTax = ko.dependentObservable(function() {
return (this.price() * 1.05).toFixed(2);
}, this);
}
//do some basic mapping (without mapping plugin)
var mappedData = ko.utils.arrayMap(dataFromServer, function(item) {
return new Item(item.name, item.category, item.price);
});
编辑
我对此进行了更多研究,您实际上可以使用 KO 映射映射 JS 数组对象,但是,映射后对象不会是 KO Observable Array。它只是普通的 JS 数组对象,就此而言,您可以使用 KO 进行数据绑定:
var bd = [ { x: 1, y: "bd test" }, { x: 2, y: "bd test 1dsf" } ];
var bdViewModel = ko.mapping.fromJS(bd);
// 'bdViewModel' is NOT KO Observable Array, so you can't use KO Binding. However, all the properties of 'bdViewModel' (x and y) are KO Observable.
//ko.applyBindings(bdViewModel, $("#bd").get(0));
console.log(bdViewModel());
// 'bdViewModel' must be called as function (with open and close parentheses) to see the data.
$.each(bdViewModel(), function (i, d) {
$("#bdList").append("<li>" + d.y() + "</li>");
});
这是用于比较映射 JS 数组和 JSON 的 JSBin:http: //jsbin.com/uzuged/5/