10

我有一个自定义敲除绑定,可以将切换开关设置为“开”或“关”位置。我的问题是更新函数仅在初始化后立即触发,而不是在可观察值更改时触发。任何想法我做错了什么?

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 -->
4

1 回答 1

16

update 事件没有被触发,因为您没有直接绑定到 observable,而是绑定到包含名为valueset 到 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
    }
  }
};
于 2013-08-27T12:47:18.903 回答