有人可以帮我正确地将iCheck
插件与knockout
集成吗?因为我试图使用自定义绑定将插件初始化为我的单选按钮,但它没有更新视图模型的值。
<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" />
**<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.
}
};
答案 0 :(得分:1)
//trying to change the observabe value
observable.checked = true;
你覆盖了可观察物而不是设置它;你想要
observable.checked(true);
答案 1 :(得分: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');
}
}
};
答案 2 :(得分:0)
这对我有用:
onSubmit
用法:
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');
}
}
};