knockout.jsko-custom-binding

knockout.js and disable custom binding


I would like to bind disabled and css within a custom binding instead of using JQuery to assign a class and disabled it. Can you do this within a custom binding without doing $(element).attr('disabled', true).addClass('disabled');

data_bind="enabled: classroomId(), css: { 'disabled' : !classroomId() }"


data_bind="disable: { !classroomId() }

ko.bindingHandlers.disable = {
        update: function (element, valueAccessor) {
            var disabled = ko.utils.unwrapObservable(valueAccessor());


                 // Disable and Add Class to Button or Anchor Tag

        }
    };

Solution

  • Knockout now contains a disable binding that mirrors the enabled one, you can either use jQuery or call the existing css and disabled bindings (fiddle):

    ko.bindingHandlers.myDisabled = {
        update: function(element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor());
            ko.bindingHandlers.css.update(element, function() {return { disabled: value }; });
            ko.bindingHandlers.disable.update(element, valueAccessor);
        }
    };
    

    Html:

    <input type="text" data-bind="value: name, myDisabled: !enabled()"/>