Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a knockoutjs protected observable with checkboxes?

I'm using knockoutjs with protected observable and am having an issue with checkboxes. One implementation of protected observables can be found here but there are several that I've seen that are very similar.

A jsFiddle that demonstrates my issue can be found here. Here is a portion of the fiddle.

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

    self.protectedBool = ko.protectedObservable(true);
    self.commit = function(){
        ko.commitProtectedObservables(self);
    };
    self.rollback = function() {
        ko.rollbackProtectedObservables(self);
    };
};

$(function() {
    ko.applyBindings(new ViewModel());
});

To duplicate, do the following:

  1. Run the fiddle (default value for the checkbox is true)
  2. Uncheck the checkbox
  3. Click "Commit"
  4. Note that the value now shows as false (this is the correct behavior)
  5. Run the fiddle again (default value for the checkbox is true)
  6. Uncheck the checkbox then check it immediately (before clicking "Commit")
  7. Click "Commit"
  8. You'll see the value will be set to false/unchecked even though it was checked when you clicked "Commit".

The "write" event in the computed observable inside the protectedObservable definition does not get fired the second time you change the checkbox and thus when the value is commited, it's committing the incorrect value.

Also note that the protectedObservable works perfectly for strings. Any guidance would be greatly appreciated.

like image 732
rhoadsce Avatar asked Apr 12 '13 20:04

rhoadsce


1 Answers

protectedObservable's implementation is very old. It works with older versions of KO (<2) only.

For new KO versions refer the editor pattern implemented by the same author (Ryan Niemeyer) - http://www.knockmeout.net/2013/01/simple-editor-pattern-knockout-js.html

like image 128
Rango Avatar answered Sep 25 '22 06:09

Rango