RobVious
RobVious

Reputation: 12915

Custom virtual binding handler not working

Fiddle: http://jsfiddle.net/xH3mh/6/

I'm trying to fade the whole list away with a virtual fadeVisible - I can't use a container element, so previously I was using a structure like this:

<!-- ko if: show -->
<!-- ko foreach: items() -->
<div data-bind="text: name"></div>
<!-- /ko -->
<!-- /ko -->

Now, I have this:

<!-- ko fadeVisible: show -->
<!-- ko foreach: items() -->
<div data-bind="text: name"></div>
<!-- /ko -->
<!-- /ko -->

With the following bindingHandler:

ko.bindingHandlers.fadeVisible = {
        init: function(element, valueAccessor) {
            var value = valueAccessor();
            $(element).toggle(ko.utils.unwrapObservable(value)); // Use "unwrapObservable" so we can handle values that may or may not be observable
        },
        update: function(element, valueAccessor) {
            var value = valueAccessor();
            ko.utils.unwrapObservable(value) ? $(element).fadeIn() : $(element).fadeOut();
        }
    };  

ko.virtualElements.allowedBindings.fadeVisible = true;

But this is not working for some reason. Locally I get this error:

Unable to process binding "fadeVisible: function (){return show() }" Message: Cannot set property 'cur' of undefined

on JSFiddle I get this:

Uncaught TypeError: Cannot read property 'display' of undefined

If I use the getFirstRealElement function to capture the first element and use that in place of element, it works, but I need the whole list.

What am I doing wrong?

Upvotes: 1

Views: 1373

Answers (1)

Damien
Damien

Reputation: 8987

You can't fadeOut/In a virtual element. Because a virtual element is not associated to dom element.

What you attempt to do is like using the visible binding to an virtual element. If you do that you will get this error :

The binding 'visible' cannot be used with virtual elements.

The reason is, the visible binding and your fadeOut binding try modify a dom element ($(element).show() and $(element).fadeIn()), which doesn't exists.

So if you want to have fadeOut/In transition you can't use an virtual element.

In brief : bindings which modify the style of an element and not its flow can't be applied to virtual element.

Upvotes: 2

Related Questions