Skip to content

Instantly share code, notes, and snippets.

@tonyhb
Last active February 8, 2017 15:04
Show Gist options
  • Save tonyhb/7622836 to your computer and use it in GitHub Desktop.
Save tonyhb/7622836 to your computer and use it in GitHub Desktop.
Marionette.Region.replace: Show and hide regions with a fadeIn/fadeOut animation
Marionette.Region.prototype.replace = (view, speed) ->
speed = speed || 150
if ! @currentView
@show(view)
return
@ensureEl()
isViewClosed = view.isClosed || _.isUndefined view.$el
isDifferentView = view isnt @currentView
view.render()
@currentView.$el.fadeOut(speed).promise().done =>
@close()
# Tidy up: fadeIn/fadeOut could be integrated into open()
@$el.hide()
@open view if isDifferentView or isViewClosed
@$el.fadeIn(speed)
@currentView = view
Marionette.triggerMethod.call @, "show", view
Marionette.triggerMethod.call view, "show"
Marionette.Region.prototype.replace = function(view, speed) {
var isDifferentView, isViewClosed,
_this = this;
speed = speed || 150;
if (!this.currentView) {
this.show(view);
return;
}
this.ensureEl();
isViewClosed = view.isClosed || _.isUndefined(view.$el);
isDifferentView = view !== this.currentView;
view.render();
return this.currentView.$el.fadeOut(speed).promise().done(function() {
_this.close();
_this.$el.hide();
if (isDifferentView || isViewClosed) {
_this.open(view);
}
_this.$el.fadeIn(speed);
_this.currentView = view;
Marionette.triggerMethod.call(_this, "show", view);
return Marionette.triggerMethod.call(view, "show");
});
};
@tonyhb
Copy link
Author

tonyhb commented Nov 24, 2013

Unfortunately, we can't just call Marionette's show() method on line 14 because it breaks layouts. For example, in your controller you might have:

layout = new ModuleLayout()
module.region.replace(layout)
layout.show(new PageCompositeView())

In this case, the Region calls show() on the layout after the animation has finished, which wipes out all of the layout's regions. This is why we've had to reimplement show, which renders the layout immediately (before the animation) and shows it after the animation has finished.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment