Knockout自定义绑定更新功能未触发

时间:2013-08-27 12:13:00

标签: knockout.js

我有一个自定义的敲除绑定,可以将切换开关设置为“开”或“关”位置。我的问题是更新函数只在init之后立即触发,而不是在可观察值发生变化时触发。我有什么想法吗?

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

1 个答案:

答案 0 :(得分:16)

更新事件未被触发,因为您没有直接绑定到observable,而是绑定到包含设置为observable的名为value的属性的对象。我以前如何完成这个是省略自定义绑定的更新功能,只是在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
    }
  }
};