0

我正在尝试使用 knockoutjs 和以下数据源创建级联下拉列表:

[{"$id":"1",
  "Id":1,
  "Name":"Nikon",
  "Cameras":[{
       "$id":"2",
       "Id":1,
       "Name":"D90"},
      {"$id":"3",
       "Id":2,
       "Name":"D5100"},
      {"$id":"4",
       "Id":3,
       "Name":"D700"}]},
 {"$id":"5",
  "Id":2,
  "Name":"Canon",
  "Cameras":[{
       "$id":"6",
       "Id":4,
       "Name":"550D"},
      {"$id":"7",
       "Id":5,
       "Name":"600D"},
      {"$id":"8",
       "Id":6,
       "Name":"650D"}]},
 {"$id":"9",
  "Id":3,
  "Name":"Sony",
  "Cameras":[]},
 {"$id":"10",
  "Id":4,
  "Name":"Pentax",
  "Cameras":[]},
 {"$id":"11",
  "Id":5,
  "Name":"Olympus",
  "Cameras":[]},
 {"$id":"12",
  "Id":6,
  "Name":"Panasonic",
  "Cameras":[]},
 {"$id":"13",
   "Id":7,
   "Name":"Leica",
   "Cameras":[]}]

我尝试使用用于 knockoutjs 的映射插件将此 json 映射到我的公司对象:

$.getJSON(url, function (data) {
      $.each(data, function () {
        companies.push(ko.mapping.fromJS(this));
      });
});

但似乎没有映射 Cameras 数组。你能告诉我为什么会这样吗?谢谢。

4

1 回答 1

0

Wrapping your list in an object using companies as key should make your code work.

var Model = function () {
   this.companies= ko.observableArray();        
};
var model = new Model();
ko.applyBindings(model);
ko.mapping.fromJS({companies: data}, mappingOptions, model);

see this fiddle (changing value in input boxes shows that Cameras array is mapped).

于 2012-09-13T12:20:11.257 回答