2013-02-25 88 views
0

我正在使用不同類型的控件(http://jsfiddle.net/gZC5k/993/)的嵌套窗體,該窗體在添加下拉控件時出現了問題。Knockout optionValues建模問題

我有這個在我的HTML

     <tr class='person'> 
         <td>Gender</td> 
         <td> 
          <select data-bind="options: optionGender, value: gender"></select> 
         </td> 
        </tr> 

,這在模型

self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) { 
    return { 
     firstName: ko.observable(contact.firstName), 
     lastName: ko.observable(contact.lastName), 
     isKey: ko.observable(contact.isKey), 
     gender: ko.observable(contact.gender), 
     phones: ko.observableArray(ko.utils.arrayMap(contact.phones, function (phone) { 
      return { 
       type: ko.observable(phone.type), 
       number: ko.observable(phone.number), 
       calls: ko.observableArray(phone.calls) 
      }; 
     })), 
     addresses: ko.observableArray(contact.addresses), 
     optionGender: ["Male", "Female"] 
    }; 
})); 

self.addContact = function() { 
    self.contacts.push({ 
     firstName: "", 
     lastName: "", 
     isKey: "false", 
     gender: "Female", 
     phones: ko.observableArray(), 
     addresses: ko.observableArray() 
    }); 
}; 

當我inititally加載數據,我可以編輯的所有值和相應的JSON是O.K.當添加一個新的人時,事情就會出錯。

當與性別字段相關的所有內容都被刪除時,表單可以正常工作(請參閱http://jsfiddle.net/gZC5k/995/)。我假設我把

  optionGender: ["Male", "Female"], 

放在錯誤的地方,但不能確定它應該在哪裏。

回答

0

以爲我發現它由的addContact功能重複optionGender(在http://jsfiddle.net/gZC5k/997/

var optionGender = [ 
"Male", 
"Female"]; 

var ContactsModel = function (contacts) { 
var self = this; 
self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) { 
    return { 
     firstName: ko.observable(contact.firstName), 
     lastName: ko.observable(contact.lastName), 
     isKey: ko.observable(contact.isKey), 
     gender: ko.observable(contact.gender), 
     phones: ko.observableArray(ko.utils.arrayMap(contact.phones, function (phone) { 
      return { 
       type: ko.observable(phone.type), 
       number: ko.observable(phone.number), 
       calls: ko.observableArray(phone.calls) 
      }; 
     })), 
     addresses: ko.observableArray(contact.addresses), 
     optionGender: optionGender, 
    }; 
})); 

self.addContact = function() { 
    self.contacts.push({ 
     firstName: ko.observable(""), 
     lastName: ko.observable(""), 
     isKey: ko.observable("true"), 
     gender: ko.observable("Female"), 
     optionGender: optionGender, 
     phones: ko.observableArray(), 
     addresses: ko.observableArray() 
    }); 
}; 

但是這導致其在生成JSON的選項列表,像這樣

[ 
{ 
"firstName": "", 
"lastName": "", 
"isKey": "true", 
"gender": "Male", 
"optionGender": [ 
    "Male", 
    "Female" 
], 
"phones": [], 
"addresses": [] 
}, 
{ 
"firstName": "", 
"lastName": "", 
"isKey": "true", 
"gender": "Female", 
"optionGender": [ 
    "Male", 
    "Female" 
], 
"phones": [], 
"addresses": [] 
} 
] 

所以我仍在尋找解決方案..