有一个向下钻取的表单字段,其中的字段逐渐出现。虽然我已经弄清楚了让它们一次出现在页面下方的逻辑,包括一个简单的切换,但问题是在单击“否”时将所有可观察对象重置为其原始状态(并清除所有字段)。目前,如果第二次单击“是”(在完成表格后,然后决定“否”),所有字段都会立即重新出现,而不是逐步出现。http://jsfiddle.net/hotdiggity/JJ6f6/
淘汰模型:
var ViewModel = function () {
var self = this;
self.showField1 = ko.observable(true);
self.showField2 = ko.observable(false);
self.showField3 = ko.observable(false);
self.showField4 = ko.observable(false);
self.yesOrNo = ko.observable("");
self.hasValue = ko.observable("");
self.toggleCalc = ko.observable("");
self.showField2 = ko.computed(function () {
return self.yesOrNo() == 'yes';
});
self.showField3 = ko.computed(function () {
self.showField4(false);
return ( !! self.hasValue());
});
self.toggleCalc = function () {
self.showField4(!self.showField4());
};
};
ko.bindingHandlers.fadeVisible = {
init: function (element, valueAccessor) {
var value = valueAccessor();
$(element).toggle(ko.utils.unwrapObservable(value));
},
update: function (element, valueAccessor) {
var value = valueAccessor();
ko.utils.unwrapObservable(value) ? $(element).fadeIn() : $(element).fadeOut();
}
};
ko.applyBindings(new ViewModel());
HTML:
<div class='list-inputs'>
<h2>Drilldown toggle interaction</h2>
<!--LEVEL 1-->
<div data-bind='fadeVisible: showField1'>(L1) Choose one to display more options:
<p>
<label>
<input type='radio' name="type" value='yes' data-bind='checked: yesOrNo' />Yes</label>
<label>
<input type='radio' name="type" value='no' data-bind='checked: yesOrNo' />No</label>
</p>
<!--LEVEL 2-->
<div data-bind='fadeVisible: showField2'>
<p>(L2) Enter input and click off:
<input type="text" data-bind='value: hasValue' />
</p>
<!--LEVEL 3-->
<div data-bind='fadeVisible: showField3'>
<p><span>(L3) Earnings:</span>
<input type="text" /> <a data-bind="click: toggleCalc" href="#">Toggle calculator</a>
</p>
<!--LEVEL 4-->
<div data-bind='fadeVisible: showField4'>
<br />
<p><b>(L4) Calculator</b>
</p>
<p><span>Input 1:</span>
<input type="text" />
</p>
<p><span>Input 2:</span>
<input type="text" />
</p>
<p><span><b>Total:</b></span>
<input type="text" />
</p>
</div>
</div>
</div>
</div>
</div>