网站搜索

javascript - 延迟移除视图以便可以进行动画处理


假设我有一个根据属性显示视图的模板:

{{#if App.contentsAreVisible}}
    {{view ToggleContents}}
{{/if}}

此区域可以通过 UI 的其他任何部分通过设置 App.set("contentsAreVisible", [true/false]); 来切换

这一切都运作良好。

然而,我现在想在视图切换时进行动画。在 didInsertElement 中挂钩可以实现显示区域的动画,但我不能在 willDestroyElement 中做同样的事情,因为元素在该函数返回后立即被移除,动画还没有机会运行。

App.ToggleContents = Ember.View.extend({

    // this works fine
    didInsertElement: function(){
        this.$().hide().show("slow");
    },

    // this doesn't work
    willDestroyElement: function(){
        this.$().hide("slow", function(){
            // animation is complete, notify that the element can be removed
        });
    }
});

有没有办法告诉视图在动画完成之前不要从 DOM 中删除元素?

这是一个带有互动示例的小提琴: http://jsfiddle.net/rlivsey/RxxPU/

答案#1

你可以在你的视图上创建一个 hide 函数,当回调完成时移除该视图,参考 http://jsfiddle.net/7EuSC/

车把:

<script type="text/x-handlebars" data-template-name="tmpl" >
    <button {{action "hide" }}>hide</button>

    This is my test view which is faded in and out
</script>

JavaScript:

Ember.View.create({
    templateName: 'tmpl',

    didInsertElement: function() {
        this.$().hide().show("slow");
    },

    _hideViewChanged: function() {
        if (this.get('hideView')) {
            this.hide();
        }
    }.observes('hideView'),

    hide: function() {
        var that = this;
        this.$().hide("slow", function() {
            that.remove();
        });
    }
}).append();

答案#2

我知道这个已经有正确答案了,但我想我还是发一些类似的内容,以防其他人像我一样通过谷歌找到这个。

我的一个应用程序有一个“详细信息”部分,它总是有相同的内容绑定,但会根据查看/编辑等模式更改模板。

因为我正在使用 rerender() 来实现这一点,并且希望视图先淡出然后再淡入,这样可以隐藏 rerender 函数的任何小故障(同时也让它看起来更好),所以我将其包裹在一个用于动画的 <div> 中。

<script>
_templateChanged: function(){
  self = this;
  $('#effects-wrapper').fadeOut('fast',function(){
    self.rerender();
    $(this).fadeIn('fast');
  });            
}.observes('template')
</script>

和

<div id="effects-wrapper">
{{App.Views.Whatever}}
</div>

也许不是最好的选择,但也可能对某些人有用