我有一个自定义的敲击绑定,将一个切换开关设为“开”或“关”位置.我的问题是更新函数只在init之后立即触发,而不是在observable值发生变化时才会触发.任何想法我做错了什么?
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 -->
解决方法
更新事件没有被触发,因为你不直接绑定到observable,而是包含一个名为value的属性设置为observable的对象.过去我已经完成了这个工作就是省略自定义绑定的更新功能,只需在init函数中的observable上设置一个订阅,就像这样:
ko.bindingHandlers.toggleSwitch = { init: function (element,valueAccessor) { var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor()); var value = valueUnwrapped.value; /// logic omitted for clarity value.subscribe(function(newValue) { console.log('update called'); }); if (!disabled) { /// omitted for clarity } } };