11

我正在尝试使用 Backbone.Marionette 设置渲染和关闭 ItemView 的动画。对于渲染视图,这相当简单:

MyItemView = Backbone.Marionette.View.extend({
   ...
   onRender: function() {
     this.$el.hide().fadeIn();
   }
   ...
});

当我渲染它时,这将使我的视图淡入淡出。但是,假设我想在关闭时淡出我的视图。

beforeClose: function() {
   this.$el.fadeOut();       // doesn't do anything....
}

这不起作用,因为项目在调用后立即关闭this.beforeClose(),所以动画没有时间完成。

有什么方法可以使用 Marionette 来完成结束动画?


或者,这是我一直在使用的解决方法:

_.extend(Backbone.Marionette.ItemView.prototype, {
    close: function(callback) {

        if (this.beforeClose) {

            // if beforeClose returns false, wait for beforeClose to resolve before closing
            // Before close calls `run` parameter to continue with closing element
            var dfd = $.Deferred(), run = dfd.resolve, self = this;
            if(this.beforeClose(run) === false) {
                dfd.done(function() {
                    self._closeView();              // call _closeView, making sure our context is still `this`
                });
                return true;
            }
        }

        // Run close immediately if beforeClose does not return false
        this._closeView();
    },

// The standard ItemView.close method.
    _closeView: function() {
        this.remove();

        if (this.onClose) { this.onClose(); }
        this.trigger('close');
        this.unbindAll();
        this.unbind();      
    }
});

现在我可以这样做了:

beforeClose: function(run) {
    this.$el.fadeOut(run);      // continue closing view after fadeOut is complete
    return false;
},

我是使用 Marionette 的新手,所以我不确定这是否是最佳解决方案。如果这是最好的方法,我会提交一个拉取请求,不过我会想更多地思考这如何与其他类型的视图一起使用。

这可能会用于其他目的,例如在关闭时要求确认(请参阅此问题),或运行任何类型的异步请求。

想法?

4

1 回答 1

18

覆盖该close方法是执行此操作的一种方法,但您可以将其写得更短一些,因为您可以调用 Marionettesclose方法而不是复制它:

_.extend(Backbone.Marionette.ItemView.prototype, {
    close: function(callback) {
        var close = Backbone.Marionette.Region.prototype.close;
        if (this.beforeClose) {

            // if beforeClose returns false, wait for beforeClose to resolve before closing
            // Before close calls `run` parameter to continue with closing element
            var dfd = $.Deferred(), run = dfd.resolve, self = this;
            if(this.beforeClose(run) === false) {
                dfd.done(function() {
                    close.call(self);
                });
                return true;
            }
        }

        // Run close immediately if beforeClose does not return false
        close.call(this);
    },


});

另一个想法是覆盖remove视图的方法。所以你淡出视图的元素,然后从 DOM 中删除它

remove: function(){
  this.$el.fadeOut(function(){
    $(this).remove();
  }); 
}
于 2012-09-16T19:18:02.820 回答