我有一个自定义敲除绑定,可以将切换开关设置为“开”或“关”位置。我的问题是更新函数仅在初始化后立即触发,而不是在可观察值更改时触发。任何想法我做错了什么?
ko.bindingHandlers.toggleSwitch = {
init: function (element, valueAccessor) {
var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
var value = valueUnwrapped.value;
var target = $(element);
var disabled = valueAccessor().disabled;
var id = 'ul' + (++ko.bindingHandlers['uniqueId'].currentIndex);
var html = ['<div class="switch-mask"><ul id="' + id + '"', 'class="on-off-switch">', '<li class="on-switch">' + valueAccessor().on + '</li>', '<li class="on-off-knob"></li>', '<li class="off-switch">' + valueAccessor().off + '</li>', '</ul></div>'].join('');
target.replaceWith(html);
var mainTarget = $('#' + id);
if (value()) {
mainTarget.children('.on-switch').animate({ 'margin-left': '0px' });
mainTarget.children('.on-off-knob').animate({ 'margin-left': '0px' });
}
else {
mainTarget.children('.on-switch').animate({ 'margin-left': '-28px' });
mainTarget.children('.on-off-knob').animate({ 'margin-left': '-1px' });
};
if (!disabled) {
mainTarget.on('click', function() {
//this fires every time the toggle switch is clicked.
var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
if (value()) {
mainTarget.children('.on-switch').animate({ 'margin-left': '0px' });
mainTarget.children('.on-off-knob').animate({ 'margin-left': '0px' });
value(false);
} else {
mainTarget.children('.on-switch').animate({ 'margin-left': '-28px' });
mainTarget.children('.on-off-knob').animate({ 'margin-left': '-1px' });
value(true);
}
value.valueHasMutated();
});
}
},
update: function (element, valueAccessor) {
var value = valueAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
console.log('update called');
}
};
ko.virtualElements.allowedBindings.toggleSwitch = true;
这是我的绑定:
<!-- ko toggleSwitch:{value:data.model.Settings.HtmlEmail,on:'On',off:'Off'}-->
<!-- /ko -->