问题
Can somebody help me to correctly integrate iCheck
plugin with knockout
? because I tried to use custom binding to initialize the plugin to my radio button but it's not updating the value of the view model.
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" />
**<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>
knockout binding
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.
}
};
回答1:
//trying to change the observabe value
observable.checked = true;
You're overwriting the observable rather than setting it; you want
observable.checked(true);
回答2:
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');
}
}
};
回答3:
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
来源:https://stackoverflow.com/questions/21297542/integrate-icheck-plugin-with-knockout-js