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.
I've recently done this and put the condition check into the click function itself, so it won't do anything unless the condition is met. I also then use a computed function to provide the css class for the element, and change the cursor dependent on whether the element will react to the click:
In my view model:
Then bind like this:
It's actually a good amount simpler than any of these options. You can't make the binding conditional but you can make what function is fired conditional. Just use a conditional in the binding:
That will either fire
toggleDialog()
or an anonymousfunction(){}
that does nothing.You can even stack bound properties to disable the button itself:
Or have another function that runs in response to an unmet condition:
Hope this helps
Kyle, after reading your comment to nemsev, I believe you want to disable your button, not your dialog function.
The binding...
And the code...
http://jsfiddle.net/DQg5P/1/
You can use this approach that I did for anchors
http://jsfiddle.net/xCfQC/11/
More details: https://github.com/AndersMalmgren/Knockout.BindingConventions/wiki/Button-convention