Search code examples
javascriptjqueryknockout.jsknockout-3.2

preventDefault() `click` in Knockout.js 3


I have a data-bind="click: ..." event in Knockout.js and I'm trying to disable it whenever a disabled class is presence in the element.

<span class="disabled" data-bind="click: alerting">Two</span>

I'm trying this without success:

$('.disabled').click(function(e){
    e.preventDefault();
});

Reproduction online

I prefer to do it by using a classname as this way I can handle both the styling of the element and the interaction with it for multiple elements in the site.


Solution

  • The issue here is that there's no guarantee as to which click handler is going to run first. In this case, the knockout click binding is executing before the jquery handler.

    Given that you're working with knockout, the "proper" way to do this would be for the viewmodel to handle everything, and not rely on something external, such as jQuery, to prevent the click from happening.

    In your case, the viewmodel might look like this:

    var viewModel = {
        disabled: ko.observable(false),
        alerting: function(data, e) {
           if (!this.disabled())
               alert("two");
        }
    };
    

    You then just update the disabled observable to enable/disable the click handler. You could also make use of this observable to apply different styling to elements that should be disabled, eg adding the disabled style, rather than using the style to control the knockout behaviour.