How can I disable and enable an anchor tag with this custom binding. It works great with input elements but the anchor tag just changes the CSS, not the disabling.
<a href="link" data-bind="myDisabled: !enabled()"/>
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);
}
};
You need to capture click event in your binding handler.
HTML:
JavaScript:
Here is a working example:
http://jsfiddle.net/kp74u/54/
UPDATE 1: If you need to prevent other event handlers bound after knockout binding handler was attached, you need to add
stopImmediatePropagationto the event handler along withpreventDefault.example: http://jsfiddle.net/kp74u/55/
UPDATE 2: If you want to disable all event handlers (along with click event handlers attached before your binding handler, you need to ‘hack’ the jquery events array). Please note that this may not work other versions of jquery (example uses 1.7):
example: http://jsfiddle.net/nickolsky/kp74u/40/
UPDATE 3: As was mentioned there (suggested edit by FIR55TORM, sorry can’t approve this completely correct edit because I am too late to review): if you’re using jQuery 1.10.x, you will need to add an underscore to access the ‘data’ object like so:
Revised fiddle for jQuery 1.10.x: http://jsfiddle.net/nickolsky/kp74u/41/