我在模板中有一个自定义绑定(bind)。
自定义绑定(bind)涉及使用绑定(bind)到模板的 attrs 呈现的属性。
<script type="text/html" id="mc-radio-template">
<!-- ko foreach: Values -->
<div class="rounded_col" data-bind="complexRadio: $parent.Value">
<label data-bind="text: Description"></label>
<input type="radio" style="visibility:hidden" data-bind="attr: { 'name': $parent.Name, 'value': Value}" />
</div>
<!-- /ko -->
</script>
complexRadio 涉及由模板使用 attr 绑定(bind)呈现的输入值。
ko.bindingHandlers.complexRadio = {
init: function (element, valueAccessor) {
// Get radio button located inside this div
var radio = $(element).find('input[type="radio"]');
var isDisabled = !!radio.attr('disabled');
var value = valueAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
if (valueUnwrapped === true)
valueUnwrapped = 'true';
if (valueUnwrapped === false)
valueUnwrapped = 'false';
value(valueUnwrapped);
// When div is clicked, check the radio and trigger radio change event
if (!isDisabled)
$(element).click(function () {
radio.prop('checked', true);
radio.change();
});
// When radio button is checked, update the viewModel property!!
$(radio).change(function () {
if (radio.prop('checked')) // only if it was changed to checked
{
// Set viewModel property to value of the radio button that was clicked
var value = valueAccessor();
value(radio.val());
}
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
var value = valueAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
if (valueUnwrapped === true)
valueUnwrapped = 'true';
if (valueUnwrapped === false)
valueUnwrapped = 'false';
// Get radio button located inside this div
var radio = $(element).find('input[type="radio"]');
// Set radio to be checked or unchecked
var shouldBeChecked = valueUnwrapped == radio.val();
if (shouldBeChecked)
radio.parent().addClass('active');
else
radio.parent().removeClass('active');
}
};
我的问题是,complexRadio 初始化发生在模板渲染 value 属性之前。
在这条线上 -
var shouldBeChecked = valueUnwrapped == radio.val();
radio.val() 不是在模板渲染完成后渲染的。 这会导致 radio 的开始状态未被选中。
渲染结束后如何强制运行自定义绑定(bind)? 或者也许 - 如何使用 js 添加自定义绑定(bind),以便我可以将其添加到 afterRender 回调中。
最佳答案
您在 radio 上有一个 value
绑定(bind),并且您正在使用 jQuery 访问其 value
属性,但 radio 直到外部绑定(bind)之后才被绑定(bind)被申请;被应用。 radio 没有渲染是不正确的,它只是没有绑定(bind)。
解决方案是让外部绑定(bind)控制所包含 radio 的绑定(bind)。请参阅the documentation on descendant bindings .
关于javascript - Knockoutjs - 自定义绑定(bind)嵌套在模板内,attr 尚未在自定义绑定(bind)调用上绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35016529/