DreamChild
DreamChild

Reputation: 421

Knockout and its bindings

I have two checkboxes and i want the values of these ones depend on each other. When i check first checkbox second one is getting unchecked, when i uncheck first one the second one is getting checked and vice versa. I can do it with jQuery: example.

$('input').on('change', 
     function() {         
         var anotherId = $(this).attr('id') == 'first' ? 'second' : 'first';        
         if($(this).is(':checked'))
             $('[id="' + anotherId + '"]').removeAttr('checked');
         else 
             $('[id="' + anotherId + '"]').attr('checked', 'true');
     });

But it isn't the best way i think. I know i can do it with knockout.js but don't know how do it. Could you help me with this problem?

Upvotes: 0

Views: 46

Answers (1)

Jeroen
Jeroen

Reputation: 63830

Have you considered using radio buttons instead? ;-)

You haven't given much practical context; there are a lot of ways to solve this and which is best depends on the circumstances. In any case, here's one way to do this.

Create "private" observables for the value, and have "public" computed observables that have some extra logic inside the write bit (akin to properties with complex setters in C#):

var ViewModel = function() {
    var self = this;

    var _first = ko.observable(true);
    var _second = ko.observable(false);

    self.first = ko.computed({
        read: _first,
        write: function(val) {
            _first(val);
            _second(!val);
        }});

    self.second = ko.computed({
        read: _second,
        write: function(val) {
            _second(val);
            _first(!val);
        }});
};

ko.applyBindings(new ViewModel());

See a working demo in this fiddle. Again, note that the checkboxes now merely behave as if they were radio buttons...

Upvotes: 5

Related Questions