从自定义bindingHandler中更改另一个绑定

时间:2014-09-08 12:47:54

标签: javascript knockout.js

如何更改自定义bindingHandler(fadeVisible)另一个绑定(isFadingIn)的值。最好用一个例子来解释。

<div data-binding="fadeVisible: isVisible; fadingIn: isFadingIn; animationDuration: 500">...</div>


ko.bindingHandlers.fadeVisible = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // Initially set the element to be instantly visible/hidden depending on the value
        var value = valueAccessor();
        $(element).toggle(ko.unwrap(value)); // Use "unwrapObservable" so we can handle values that may or may not be observable
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // Whenever the value subsequently changes, slowly fade the element in or out

        var duration = allBindings.get('animationDuration') || 400;
        //vvvvvvvvv here
        allBindings.get('fadingIn') = true;

        var value = valueAccessor();
        ko.unwrap(value) ? $(element).fadeIn(duration).then(function () {
           //vvvvvvvvv here
           allBindings.get('fadingIn') = false;
        }) : $(element).fadeOut(duration).then(function () {
           //vvvvvvvvv here
           allBindings.get('fadingIn') = false;
        });
    }
};

修改:更改参数

(element, valueAccessor)

(element, valueAccessor, allBindings, viewModel, bindingContext)

1 个答案:

答案 0 :(得分:1)

函数签名中缺少

allBindings参数。 allBindings.get将返回一个observable,因此您应该将其设置为observable:

allBindings.get('fadingIn')(true);
allBindings.get('fadingIn')(false);