2012-09-12 129 views
0

我試圖創建級聯下拉使用knockoutjs列表和以下數據來源:淘汰賽mappins兒童陣列

[{"$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":[]}] 

我試圖映射此JSON到我的公司對象使用knockoutjs映射插件:

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

但似乎攝像機陣列沒有映射。你能告訴我爲什麼會發生這種情況?謝謝。

回答

0

使用公司將對象包裝爲對象,因爲關鍵應該使您的代碼正常工作。

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

看到此fiddle(在輸入框變更值示出了相機陣列被映射)。