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:
However, i would like:
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);
}
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With