Custom styled checkbox with KnockoutJS not responding to 'checked' data binding

I have an advanced checkbox that is checked or not checked based on the original data, and then it also responds when the user manually checks or unchecks it. In the past, for my more primitive checkboxes , I really liked using checkboxes here .

The only problem is it doesn't work as expected with Knockout. Note that the checkbox is unresponsive when the custom checkbox is checked. But if you remove this code from the bottom of JavaScript, it works as expected.

// INITIALIZE CHECKBOX
$('#witnessSlider').checkboxpicker();

      

Here is the violin:

http://jsfiddle.net/maxgrr/r23q740u/1/

This can also apply to various other types of custom checkboxes.

+3


source to share


1 answer


Since you are introducing a custom plugin that transforms your own checkbox into a more complex structure, the built-in binding handler checked

will no longer be able to detect changes as it is designed to work with the this.checked

native element <input type="checkbox" />

(which is now hidden).

So, you need more handler plugins that can update the view model when the custom checkbox is changed, and also update the plugin when the model changes.

The next handler checkboxpicker

does exactly that: the function init

is called only once to set up the plugin, set its initial state according to the current state of the view model (value wereThereAnyWitnesses

), and register a listener ( change

) for any future changes that will then update the view model.

The function update

is called every time the view model changes and is responsible for updating the custom checkbox state.



ko.bindingHandlers.checkboxpicker =
{
    init: function(element, valueAccessor){
        var val = valueAccessor();
        $(element).checkboxpicker().prop('checked', val()).change(function() {
            val(this.checked);
        });
    },
    update: function(element, valueAccessor) {
        var val = valueAccessor();
        $(element).prop('checked', val());
    }
};

      

And in your HTML:

<input type="checkbox" data-bind="checkboxpicker: wereThereAnyWitnesses" />

      

See Fiddle

+5


source







All Articles