我正在尝试设置动画,以使用Backbone.Marionette渲染和关闭ItemView。对于渲染 View ,这非常简单:
MyItemView = Backbone.Marionette.View.extend({
...
onRender: function() {
this.$el.hide().fadeIn();
}
...
});
当我渲染它时,我的 View 会淡入。但是,假设我想在关闭时淡出我的视线。
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 的新手,所以我不确定这是否是最佳解决方案。如果这是最好的方法,那么我将提交一个拉取请求,尽管我想再想一想如何将其与其他类型的 View 一起使用。
这可能会用于其他目的,例如在关闭时要求确认(请参阅issue),或运行任何类型的异步请求。
有什么想法吗?
最佳答案
重写close
方法是实现此目的的一种方法,但是您可以编写得短一些,因为您可以调用Marionettes close
方法而不是复制它:
_.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);
},
});
另一个想法是覆盖 View 的
remove
方法。因此,您淡出 View 的元素,然后将其从DOM中删除remove: function(){
this.$el.fadeOut(function(){
$(this).remove();
});
}
关于javascript - Backbone.Marionette : Defer view close until beforeClose animation is complete,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12449116/