最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论