Skip to content

Instantly share code, notes, and snippets.

@jackwanders
Last active December 31, 2015 23:49
Show Gist options
  • Save jackwanders/8062419 to your computer and use it in GitHub Desktop.
Save jackwanders/8062419 to your computer and use it in GitHub Desktop.
/*global define*/
/**
* Backbone.Maid - Someone's gotta clean up after your mess
*
* An attempt to write a(n admittedly opinionated) version
* of Backbone.View that better manages sub-views
*
*/
define([
'underscore',
'backbone'
], function (_, Backbone) {
'use strict';
Backbone.Maid = {};
var oldView = Backbone.View;
/**
* Backbone.Maid.View
* An extension of Backbone.View that can store an array of any nested views
* and on .remove(), first remove said nested views
*/
Backbone.Maid.View = Backbone.View.extend({
// define any properties or methods specific to Maid.View instances
constructor: function() {
this.childViews = [];
var oldRender = this.render;
// Before rendering, clean the view of any existing child views
this.render = function() {
this.cleanView();
return oldRender && oldRender.apply(this,arguments);
};
oldView.apply(this, arguments);
},
// iterate over array of child views, removing each one
removeChildViews: function() {
while(this.childViews.length > 0) {
this.childViews.shift().remove();
}
},
// override remove method, removing all child views first
remove: function() {
this.removeChildViews();
oldView.prototype.remove.apply(this,arguments);
},
// pre-render method to remove all child views (they're about to get re-rendered)
cleanView: function() {
this.removeChildViews();
// commented out for now; you could have content in this.$el that isn't added in .render
//this.$el.empty();
}
});
// Override default view with Maid.View
Backbone.View = Backbone.Maid.View;
// requisite noConflict option
Backbone.Maid.View.noConflict = function() {
Backbone.View = oldView;
};
return {
noConflict: function() {
Backbone.Maid.View.noConflict();
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment