Is there any way to specify an enable condition for the click binding? For example if I have the following:
<div data-bind="click: toggleDialog">Click Me</div>
I'd like to be able to disable clicking if a specified condition occurs so something to the effect of:
<div data-bind="click: toggleDialog, enableClick: myName() === 'John'">Click Me</div>
I'm thinking maybe a custom binding would work for this, but not quite exactly sure how to go about doing it.
Click binding is one of the simplest binding and is used to invoke a JavaScript function associated with a DOM element based on a click. This binding works like an event handler. This is most commonly used with elements such as button, input, and a, but actually works with any visible DOM element.
To apply bindings for the whole HTML document, it can be done using the Knockout function applyBindings() with passing the view model as the first and the only parameter: ko. applyBindings(viewModel); To apply Knockout for a part of the HTML document, pass the DOM element as a second parameter: ko.
Knockout. js defines an important role when we want to detect and respond to changes on one object, we uses the observable. An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted.
A data binding connects data from a custom element (the host element) to a property or attribute of an element in its local DOM (the child or target element). The host element data can be a property or sub-property represented by a data path, or data generated based on one or more paths.
You can use this approach that I did for anchors
http://jsfiddle.net/xCfQC/11/
(function() {
//First make KO able to disable clicks on Anchors
var orgClickInit = ko.bindingHandlers.click.init;
ko.bindingHandlers.click.init = function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
if(element.tagName === "DIV" && allBindingsAccessor().enable != null) {
var disabled = ko.computed({
read: function() {
return ko.utils.unwrapObservable(allBindingsAccessor().enable) === false;
},
disposeWhenNodeIsRemoved: element
});
ko.applyBindingsToNode(element, { css: { disabled: disabled} });
var handler = valueAccessor();
valueAccessor = function() {
return function() {
if(ko.utils.unwrapObservable(allBindingsAccessor().enable)) {
handler.apply(this, arguments);
}
}
};
}
orgClickInit.apply(this, arguments);
};
})();
More details: https://github.com/AndersMalmgren/Knockout.BindingConventions/wiki/Button-convention
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With