3

有人可以帮我正确集成iCheck插件knockout吗?因为我尝试使用自定义绑定将插件初始化为我的单选按钮,但它没有更新视图模型的值。

HTML

<div data-bind="foreach: InstituteContactNumber">
   <div class="controls multiple-controllers">
       <input type="hidden" data-bind="value: CNoId" />
       <input class="tb-contact-no" type="text" data-bind="value: CNo" />
       &nbsp;
       **<input type="radio" name="radio-cno" 
                     data-bind="RadioButton: { checked: IsPrimary }" />**
         <i class="fa fa-trash-o ctr-btn" style="color: red;" 
               data-bind="click: $parent.RemoveContactNo, visible: $index() > 0"></i>           
   </div>
</div>

淘汰赛绑定

ko.bindingHandlers.RadioButton = {
    init: function (element, valueAccessor) {
        //initialize icheck to the element
        $(element).iCheck({
            radioClass: 'iradio_square-blue'
        });

        $(element).on('ifChecked', function () {
            var observable = valueAccessor();
            // trying to change the observable value
            observable.checked = true;
        });
    },
    update: function (element, valueAccessor) {
        var observable = valueAccessor();
        //initially fires but it not fired when I tried to change the observable value
        //I hope that means the value has not been changed
        //anyway I have checked the model on submit, it also did not contain the values.
    }
};
4

3 回答 3

1
//trying to change the observabe value
observable.checked = true;

您正在覆盖 observable 而不是设置它;你要

observable.checked(true);
于 2014-01-23T05:21:34.277 回答
0

如果您自己在组件或处理程序中更改可观察值,请考虑将其设置为双向绑定:

    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');
            }
        }
    };
于 2015-07-31T08:08:02.387 回答
0

这对我有用:

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');
        }
    }
};

用法:

 <input type="checkbox" class="checkbox" data-bind="iCheck: StaffIsHeadOffice" />Head Office
于 2017-03-15T03:58:07.993 回答