Warm tip: This article is reproduced from serverfault.com, please click

Explicity set value binding handler inside a custom binding handler with knockout.js

发布于 2020-12-18 23:13:28

I am trying to get the observable FirstName to take like the default value binding on the element. For some reason the ko.bindingHandlers.value.init below doesnt work. When I update the textbox it doesnt refelect in the property, however if I manually set the value binding on the element it works fine.

HTML

<td class="text-center text-nowrap">
    @Html.TextBoxFor(q => q.Number, new { data_bind = "dynamicFormList: { observable: true, value: FirstName }" })
</td>

Handler

ko.bindingHandlers.dynamicFormList = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var values = ko.utils.unwrapObservable(valueAccessor());
            if (values.observable && values.value) {
                ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
            }
        }
}
Questioner
Mike Flynn
Viewed
0
Brother Woodrow 2020-12-19 20:51:40

You can't invoke binding handlers like that, but there is a method (for some reason undocumented) called applyBindingsToNode that you can use:

ko.bindingHandlers.dynamicFormList = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var values = ko.utils.unwrapObservable(valueAccessor());
        if (values.observable && values.value) {
            ko.applyBindingsToNode(
                element,
                { value: values.value }
            );
        }
    }
}

Fiddle: https://jsfiddle.net/thebluenile/12agb3x9/