Integrate iCheck plugin with knockout js

五迷三道 提交于 2019-12-01 22:34:30
ebohlman
//trying to change the observabe value
observable.checked = true;

You're overwriting the observable rather than setting it; you want

observable.checked(true);

Consider making it a two-way binding for if you change the observable value yourself in your components or handlers:

    ko.bindingHandlers.iCheck = {
        init: (el, valueAccessor) => {
            var observable = valueAccessor();
            $(el).on("ifChanged", function() {
                observable(this.checked);
            });
        },

        update: (el, valueAccessor) => {
            var val : boolean = ko.utils.unwrapObservable(valueAccessor());
            if (val) {
                $(el).iCheck('check');
            } else {
                $(el).iCheck('uncheck');
            }
        }
    };

this is working for me:

ko.bindingHandlers.iCheck = {
    init: function (element, valueAccessor) {
        $(element).iCheck({
            checkboxClass: "icheckbox_minimal-blue",
            radioClass: "iradio_minimal-blue"
        });

        $(element).on('ifChanged', function () {
            var observable = valueAccessor();
            observable($(element)[0].checked);
        });
    },
    update: function (element, valueAccessor) {
        var value = ko.unwrap(valueAccessor());
        if (value) {
            $(element).iCheck('check');
        } else {
            $(element).iCheck('uncheck');
        }
    }
};

usage:

 <input type="checkbox" class="checkbox" data-bind="iCheck: StaffIsHeadOffice" />Head Office
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!