Enable/Disable jQuery buttons in Knockout with a Custom Binding Handler

Still working on those jQuery buttons, trying to update old ASP.Net Webforms using jQuery, Knockout, and Amplify. New problem today.

I was having problems getting Knockout to enable/disable my jQuery buttons using the Knockout ‘enable’ bindingHandler. It would enable/disable the underlying element that I had run the .button() method on, but it had no idea about the div that jQuery had wrapped my element in, or how to handle it.

So I wrote a custom bindingHandler for Knockout to handle this case. It also can handle non-jQuery elements as well, so you could change the declaration from ‘jEnable’ to ‘enable’, and this would work as a all-comers enable function. However, since this method uses jQuery (and therefore is much expensive than the plain old ‘enable’), I figured the extra binding was the best approach.

if (ko && ko.bindingHandlers) {
    ko.bindingHandlers['jEnable'] = {
        'update': function(element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor());
            var $element = $(element);
            $element.prop("disabled", !value);

            if ($element.hasClass("ui-button")) {
                $element.button("option", "disabled", !value);
            }
        }
    };
}

An example on how to use this:


<input id="btnToEnable" type="button" data-bind="jEnable: isEnabled" />

<script>
   $("#btnToEnable").button();
   var viewModel = { isEnabled: ko.observable(true) };
   ko.applyBindings(viewModel);
</script>

A gist of this code is located here.

Advertisements

4 thoughts on “Enable/Disable jQuery buttons in Knockout with a Custom Binding Handler

  1. Hi, I am new in knockout and sending this email from paris. i think this is exactly what i am looking for. i would like to make disable the button. It works well with out jquery ui, but can’t make it disable with jquery ui buttons.
    I put your code in knockout.js file and tried nothing happened!!!
    Would u please tell me how should i do,
    Thank’s
    Soheil.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s