简体   繁体   中英

Custom Styled Checkbox with KnockoutJS does not respond to data-bind 'checked'

I have an advanced checkbox which is checked or unchecked based on initial data, and then it also responds when the user manually checks or unchecks it. Previously for my more primitive checkboxes, I really enjoyed using the checkboxes from here .

The only problem is that it doesn't work properly with Knockout. Notice how the checkbox doesn't respond when the custom checkbox is initialized. But if you remove this code from the bottom of the JavaScript, it works as expected.

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

Here is a fiddle:

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

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

Since you're introducing a custom plugin that is transforming your native checkbox into some more complex structure, the built-in checked binding-handler is no longer able to detect changes because it was meant to work with this.checked of the native <input type="checkbox" /> element (that is now hidden).

So, you need a more plugin-aware handler that will be able to update the view-model when the custom checkbox is mutated and also update the plugin when the model changes.

The following checkboxpicker handler does just that: the init function is called only once to setup the plugin, set its initial state according to the current view-model state (the value of the wereThereAnyWitnesses ) and registering a listener ( change ) to any future changes that will then update the view-model.

The update function is called each time the view-model changes and is responsible of updating the custom checkbox state accordingly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM