我試圖填充一個對象的可觀察屬性,當我從中選擇的列表從另一個對象生成時。選擇的選項是$root.Rider
的屬性,而選定的選項是$root
的屬性。當從另一個生成列表時,填充一個對象的observable屬性
如果我在選擇標籤的綁定中使用value: selectedContract
(如示例中所示),選擇一個選項將更改selectedContract
,但在加載時未選擇預設的selectContract
。
如果我將值更改爲value: payment_contract().option_value
,並添加optionsValue:'option_value'
,預置填充負載但selectContract
從選項列表中選擇時,不會更新。
代碼:
$(function() {
ko.applyBindings(new ViewModel());
});
var ViewModel = function() {
var self = this;
self.selectedContract = ko.observable();
self.rider = new Rider({
id: 11
});
contract = new Contract({
terms: 'Terms 2',
account_id: '2',
account_name: 'Account 2'
});
self.selectedContract(contract)
};
//Rider
function Rider(data) { //charge options and prepaid options are arrays of contract objects
var self = this;
self.id = data.id;
self.contract_options = ko.observableArray();
//populate contract_options for demo
var contract = new Contract({
terms: 'charge',
account_id: '1',
account_name: 'Account 1'
});
self.contract_options.push(contract);
contract = new Contract({
terms: 'charge',
account_id: '2',
account_name: 'Account 2'
});
self.contract_options.push(contract);
contract = new Contract({
terms: 'charge',
account_id: '3',
account_name: 'Account 3'
});
self.contract_options.push(contract);
}
function Contract(data) {
var self = this;
self.terms = data.terms;
self.contract_id = data.contract_id;
self.account_id = data.account_id;
self.account_name = ko.observable(data.account_name);
self.option_value = ko.computed(function() {
return self.account_id + '|' + self.contract_id;
});
};
<select name="contract_id_charge" data-bind="options: rider.contract_options,
value: selectedContract,
optionsText: 'account_name',
optionsCaption: 'Select Charge'
"></select>
<div data-bind="with: selectedContract">
<div>
<label>Terms:</label><span data-bind="text: terms"></span>
</div>
<div>
<label>Account Id:</label><span data-bind="text: account_id"></span>
</div>
<div>
<label>Account Name:</label><span data-bind="text: account_name"></span>
</div>
</div>
能否請您簡化你的問題。這很難理解。我會發布你的模型的一小部分,並查看和解釋你正在嘗試做什麼。 – 2014-12-28 00:42:44
感謝您的反饋。我儘可能簡化並在帖子中添加了代碼。鏈接的小提琴是功能性的,並且有更多的上下文。 – ctrane 2014-12-28 04:10:40
你的問題現在更長。你能否簡單地用一行來解釋,這個問題是什麼? – 2014-12-28 04:26:25