Knockout custom binding extending the "IF" binding

988 Views Asked by At

I have the following custom binding based on Ryan Niemeyer's blog but I was it doesn't work. Instead of fading him the div just doesn't show at all. I tried adding the "init" function but that did not resolve the issue so I went back to just the simple update function like Ryan has it in the example.

ko.bindingHandlers.fadeInIf = {
    update: function(element, valueAccessor) {
        ko.bindingHandlers.if.update(element, valueAccessor);
        $(element).fadeIn(); 
    } 
};

in the html I do the following:

<div data-bind="fadeInIf: show">...</div>

Blog post: http://www.knockmeout.net/2011/07/another-look-at-custom-bindings-for.html

1

There are 1 best solutions below

0
On

The if binding you are proxying to in your fadeInIf is actually used for creating dom elements, see this documentation for details.

To achieve a fadeInIf you simple need.

ko.bindingHandlers.fadeInIf = {
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        if (value) {
            $(element).fadeIn();
        }
    }
};

http://jsfiddle.net/madcapnmckay/3rRUQ/2/

If what you want is more of a fadeVisible binding I have included an example of that also in the fiddle.

Hope this helps.