How to extend knockout observables to read default value from binding ?

How to extend knockout observables to read default value from binding ?

Asked on December 12, 2018 in knockout js.
Add Comment


  • 2 Answer(s)

        Try to make the  own custom binding handler to achieve this:

    ko.bindingHandlers.initializeValue = {
        init: function(element, valueAccessor) {
            valueAccessor()(element.getAttribute('value'));
        },
        update: function(element, valueAccessor) {
            var value = valueAccessor();
            element.setAttribute('value', ko.utils.unwrapObservable(value))
        }
    };
    <input type="hidden" value="@Model.SomeValue"
        data-bind="initializeValue:myObservableReference, value: myObservableReference"/>
    
    Answered on December 12, 2018.
    Add Comment

        Use this code to extend the initializeValue binding to a select box as well as input boxes :

    ko.bindingHandlers.initializeValue = {
        init: function(element, valueAccessor) {
            if (element.getAttribute('value')) {
                valueAccessor()(element.getAttribute('value'));
            } else if (element.tagName === 'SELECT') {
                valueAccessor()(element.options[element.selectedIndex].value);
            }
        },
        update: function(element, valueAccessor) {
            var value = valueAccessor();
        element.setAttribute('value', ko.utils.unwrapObservable(value));
        }
    }
    

        NOTE: The initializeValue binding should visible before the value binding in the select’s data-bind attribute or it will not work.

    <select data-bind='initializeValue: layout_id, value: layout_id, options: layouts, optionsText: "text", optionsValue: "id"'></select>
    
    Answered on December 12, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.