Skip to content

Instantly share code, notes, and snippets.

@trezy
Last active August 29, 2015 14:10
Show Gist options
  • Save trezy/978d241908060b2f902a to your computer and use it in GitHub Desktop.
Save trezy/978d241908060b2f902a to your computer and use it in GitHub Desktop.
Add `replaceElement` option to Marionette.Region
Marionette.Region.prototype.show = function(view, options) {
var forceShow, isChangingView, isDifferentView, preventDestroy, replaceElement, showOptions, _shouldDestroyView, _shouldReplaceElement, _shouldShowView;
this._ensureElement();
showOptions = options || {};
isDifferentView = view !== this.currentView;
preventDestroy = !!showOptions.preventDestroy;
forceShow = !!showOptions.forceShow;
replaceElement = !!showOptions.replaceElement;
isChangingView = !!this.currentView;
_shouldDestroyView = isDifferentView && !preventDestroy;
_shouldShowView = isDifferentView || forceShow;
_shouldReplaceElement = replaceElement;
if (isChangingView) {
this.triggerMethod('before:swapOut', this.currentView);
}
if (_shouldDestroyView) {
this.empty();
}
if (_shouldShowView) {
view.once('destroy', this.empty, this);
view.render();
if (isChangingView) {
this.triggerMethod('before:swap', view);
}
this.triggerMethod('before:show', view);
Marionette.triggerMethodOn(view, 'before:show');
this.attachHtml(view, _shouldReplaceElement);
if (isChangingView) {
this.triggerMethod('swapOut', this.currentView);
}
this.currentView = view;
if (isChangingView) {
triggerMethod('swap', view);
}
this.triggerMethod('show', view);
Marionette.triggerMethodOn(view, 'show');
return this;
}
return this;
};
Marionette.Region.prototype.replaceEl = function(view) {
var parent;
parent = this.el.parentNode;
parent.replaceChild(view.el, this.el);
this.replaced = true;
};
Marionette.Region.prototype.restoreEl = function() {
var parent, view;
view = this.currentView;
parent = this.el.parentNode;
parent.replaceChild(this.el, view.el);
this.replaced = false;
};
Marionette.Region.prototype.attachHtml = function(view) {
if (arguments[1]) {
this.replaceEl(view);
} else {
this.el.innerHTML = '';
this.el.appendChild(view.el);
}
};
Marionette.Region.prototype.empty = function() {
var view;
view = this.currentView;
if (!view) {
return;
}
this.triggerMethod('before:empty', view);
if (this.replaced) {
this.restoreEl();
}
this._destroyView();
this.triggerMethod('empty', view);
delete this.currentView;
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment