假设我有一组 3 个单选按钮:
<div>
<label>
<input type="radio" name="Who" value="Myself"
checked="@isMyselfChecked" data-bind="checked: who" />
Mine
</label>
<label>
<input type="radio" name="Who" value="MemberId"
checked="@isMemberIdChecked" data-bind="checked: who" />
I know the member's ID
</label>
<label>
<input type="radio" name="Who" value="MemberUrl"
checked="@isMemberUrlChecked" data-bind="checked: who" />
I know the member's URL
</label>
</div>
当用户选择第一个单选按钮(Mine/Myself)时,不需要额外的输入。但是,选择第二或第三,需要附加输入:
<div>
<input type="text" name="MemberId" placeholder="Enter Member ID"
data-bind="toggleWho: who()" style="display: none" />
<input type="text" name="MemberUrl" placeholder="Enter Member URL"
data-bind="toggleWho: who()" style="display: none; width: 450px;" />
</div>
只需要data-bind="visible: who() === '[MemberId|MemberUrl]'"
依赖文本框就很容易了。但是,如果我想添加淡入/淡出过渡怎么办?
我从淘汰网站上试用了示例自定义fadeVisible
bindingHandler
,并且我了解它是如何工作的。但是,这将同时淡出并淡入文本框中。如果选择了收音机'MemberId'
,并且用户选择'MemberUrl'
了收音机,我希望MemberId
文本框在文本框淡入之前MemberUrl
淡出。
下面是我现在所拥有的,它可以工作,但我认为它不是最佳的。在前一个元素淡出之前,如何告诉淘汰赛不执行淡入?我需要另一个ko.observale
,或者可能是一个ko.computed
?
var viewModel = {
fadeSpeed: 150,
who: ko.observable($('input[type=radio][name=Who]:checked').val())
};
ko.bindingHandlers.toggleWho = {
init: function (element, valueAccessor) {
var value = valueAccessor();
var unwrapped = ko.utils.unwrapObservable(value);
if (unwrapped === element.name)
$(element).show();
},
update: function (element, valueAccessor) {
var value = valueAccessor();
var unwrapped = ko.utils.unwrapObservable(value);
// when selected value is myself, fade out the visible one, if any
if (unwrapped === 'Myself') {
$('input[type=text][name=MemberId]:visible')
.fadeOut(viewModel.fadeSpeed);
$('input[type=text][name=MemberUrl]:visible')
.fadeOut(viewModel.fadeSpeed);
}
// when selected value is memberid, may need to fade out url first
else if (unwrapped === 'MemberId') {
if ($('input[type=text][name=MemberUrl]:visible').length > 0) {
$('input[type=text][name=MemberUrl]:visible')
.fadeOut(viewModel.fadeSpeed, function () {
$('input[type=text][name=MemberId]')
.fadeIn(viewModel.fadeSpeed);
});
} else {
$('input[type=text][name=MemberId]')
.fadeIn(viewModel.fadeSpeed);
}
}
// when selected value is memberurl, may need to fade out id first
else if (unwrapped === 'MemberUrl') {
if ($('input[type=text][name=MemberId]:visible').length > 0) {
$('input[type=text][name=MemberId]:visible')
.fadeOut(viewModel.fadeSpeed, function () {
$('input[type=text][name=MemberUrl]')
.fadeIn(viewModel.fadeSpeed);
});
} else {
$('input[type=text][name=MemberUrl]')
.fadeIn(viewModel.fadeSpeed);
}
}
}
};
ko.applyBindings(viewModel);