Reputation: 37905
I am creating a form with two checkboxes.
If the user checks checkbox 1, then 2 should be disabled. If checkbox 2 is checked, then 1 should be disabled. if the user unchecks 1, then 2 should be enabled. if the user unchecks 2, then 1 should be enabled.
(I know this could be done with a radio button, but the actual use case has many checkboxes which can be checked. This example has just two for simplicity of example.)
In other words, based on the user action, the remaining checkboxes will be enabled/disabled.
I have a binding expression on checkboxes like this:
<input type="checkbox" onclick="refreshBindings(event)" data-bind="enable: getIsEnabled(1)" value=1>
<input type="checkbox" onclick="refreshBindings(event)" data-bind="enable: getIsEnabled(2)" value=2>
var currentId=0;
functionRefreshBindings(event)
{
currentId = event.currentTarget.value;
//How do I get the bindings to reevaluate getIsEnabled() for each item?
}
function getIsEnabled(id) {
switch (+id) {
case 1:
if(currentId===2)
return false;
else return true;
case 2:
if(currentId===1)
return false;
else
return true;
}
return true;
}
So how to I get the bindings to refresh?
Upvotes: 0
Views: 395
Reputation: 63719
Try to stay far from using things like onclick
events and value
properties when using Knockout. With MVVM try to rely on data-binding as much as possible. Knockout should refresh the enabled status automatically if you properly bind it.
For example, supposing this view:
<input type="checkbox" data-bind="enable: shouldBeEnabled(propA), checked: propA" /> Check 1<br />
<input type="checkbox" data-bind="enable: shouldBeEnabled(propB), checked: propB" /> Check 2<br />
<input type="checkbox" data-bind="enable: shouldBeEnabled(propC), checked: propC" /> Check 3
This ViewModel should do what you request:
function ViewModel(){
var self = this;
self.propA = ko.observable(false);
self.propB = ko.observable(false);
self.propC = ko.observable(false);
self.shouldBeEnabled = function(myVal){
if (myVal() === true) { return true; }
return !self.propA() && !self.propB() && !self.propC();
}
}
See this fiddle for a demo.
Upvotes: 1