javascript - Use CustomBindings to fade out a DOM element before it is removed by Knockout - Stack Overflow

Using KnockoutJS Custom Bindings I am trying 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);
    }  
}

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);
    }  
}
Share Improve this question asked Oct 30, 2012 at 4:30 JamesJames 7,8977 gold badges44 silver badges58 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744244758a4564872.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信