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

前端 未结 2 1458
迷失自我
迷失自我 2020-12-10 11:46

I have finally found the time to start learning KnockoutJS while building a new MVC4 application. I am trying to figure out the best way to initialize an observable value fr

相关标签:
2条回答
  • 2020-12-10 12:16

    You could try creating your 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"/>
    
    0 讨论(0)
  • 2020-12-10 12:33

    For you googlers out there, here is the 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 appear before the value binding in your 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>
    
    0 讨论(0)
提交回复
热议问题