1

I am trying to disable <a> elements (they have to be this rather than buttons because they are part of the dropdown for a bootstrap dropdown button) if they have the .menuitem-disabled class.

The click functionality for the <a> elements is being provided by the knockout click: binding (href="#" on all of them)

I put the following code at the top of my javascript. If I break on the line that assigns the click events, I can see that all the corrected elements are being selected by jquery, but the click: binding fires anyway.

$(window).load ->
        loadBindings()
        ko.applyBindings new ViewModel()
        $(".menuitem-disabled").click (e) ->
            e.stopImmediatePropagation()

I have also tried e.preventDefault() with the same results.

Does anyone have any idea how to accomplish this correctly / what is wrong with my code?

pquest
  • 3,151
  • 3
  • 27
  • 40
  • Could you use CSS instead? Like [this](http://stackoverflow.com/questions/2091168/disable-a-link-using-css) – Chiperific Jul 24 '14 at 03:06

2 Answers2

2

For this you can do some alternative. i suggest use if condition

var viewmodel = function(){
    self.enableAnchor = ko.computed(function(){
        return (self.otherobservable()) ? true : false
    })
}

<!-- ko if:enableAnchor -->

<a href="#" data-bind="click:someFunction">
    ....
</a>
<!-- /ko -->
<!-- ko ifnot:enableAnchor -->
<a href="#" data-bind="">
    ....
</a>    
<!-- /ko -->

If you need something more dynamic you can follow this

self.someFunction = function(value){
    if(value == true){
        // procees code after click
    }else{
        return false
    }
}


<a href="#" data-bind="click:someFunction.bind($data,someValue)">
    ....
</a>  
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103
2

You can do it like this

var orgClickInit = ko.bindingHandlers.click.init;
ko.bindingHandlers.click.init = function(element, valueAccessor, allBindingsAccessor, viewModel) {
    if (element.tagName === "A" && allBindingsAccessor().enable != null) {
        var disabled = ko.computed({
            read: function() {
                return ko.utils.unwrapObservable(allBindingsAccessor().enable) === false;
            },
            disposeWhenNodeIsRemoved: element
        });
        ko.applyBindingsToNode(element, { css: { "anchor-disabled": disabled } });
        var handler = valueAccessor();
        valueAccessor = function() {
            return function() {
                if (ko.utils.unwrapObservable(allBindingsAccessor().enable)) {
                    handler.apply(this, arguments);
                }
            };
        };
    }
    orgClickInit.apply(this, arguments);
};

http://jsfiddle.net/xCfQC/13/

Anders
  • 17,306
  • 10
  • 76
  • 144