Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use CustomBindings to fade out a DOM element before it is removed by Knockout

Using KnockoutJS Custom Bindings I am trying to fade out a DOM element before it is removed by Knockout. I have a JSFiddle example that currently behaves as follows when the list selection is changed:

  • The old text instantly disappears
  • The new text gradually fades in.

However, i would like:

  • The old text gradually fades out
  • The new text gradually fades in

Is this possible? I can't see a way to operate on DOM elements about to be removed. The following Update method only fires after they have already been removed (but prior to the new DOM elements being added).

ko.bindingHandlers.fade= {
    update: function(element, valueAccessor) {
        $(element).hide().fadeIn(1500);
    }  
}
like image 655
James Avatar asked Oct 30 '12 04:10

James


People also ask

What is $data in knockout?

The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.

What is applyBindings in knockout?

applyBindings do, The first parameter says what view model object you want to use with the declarative bindings it activates. Optionally, you can pass a second parameter to define which part of the document you want to search for data-bind attributes. For example, ko.

What is Knockout development?

js Application Development. Knockout is a JavaScript library that uses a Model-View-View Model (MVVM) architecture that makes it easy for developers to create dynamic and interactive UI with a logical underlying data model. Knockout is used for creating rich client side applications.


1 Answers

One way to solve it with don't using the text binding, instead of your custom fade binding should also handle the text additional and removal. With this approach you can hook your fade in/out logic.

So your fade binding should look like:

ko.bindingHandlers.fade = {
    init: function(element, valueAccessor) { 
        // initially don't show the element        
        $(element).hide();        
    },
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).fadeOut(500, function() {
            // set the text of the element, 
            // value needs to be defined outside of the fadeOut callback to work
            ko.utils.setTextContent(element, value);
            $(element).fadeIn(500);
        });
    }
};

And the usage:

<div data-bind="fade: selectedName" class="main"></div>

A demo JSFiddle.

like image 61
nemesv Avatar answered Sep 18 '22 13:09

nemesv